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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
39,358 | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma/plasma/lib/fileformat/binary.py | 301,302 | 134,374 | is_string | Binary | 302,329 | 302,329 | class Binary(object):
def __init__(self):
self.reverse_symbols = {} # ad -> name
self.symbols = {} # name -> ad
self.section_names = {}
self.demangled = {} # name -> ad
self.reverse_demangled = {} # ad -> name
self.imports = {} # ad -> True (the bool is just for msgpa... | class Binary(object):
def __init__(self):
self.reverse_symbols = {} # ad -> name
self.symbols = {} # name -> ad
self.section_names = {}
self.demangled = {} # name -> ad
self.reverse_demangled = {} # ad -> name
self.imports = {} # ad -> True (the bool is just for msgpa... | if s is None:
s = self.get_section(addr)
if s is None:
return 0
data = s.data
off = addr - s.start
n = 0
c = 0
while off < len(data):
c = data[off]
if c == 0:
n += 1
break
... | if s is None:
s = self.get_section(addr)
if s is None:
return 0
data = s.data
off = addr - s.start
n = 0
c = 0
while off < len(data):
c = data[off]
if c == 0:
n += 1
break
... | 84 | 1,824 | 198 | 2,022 | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... |
39,359 | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma/plasma/lib/fileformat/binary.py | 102,103 | 33,116 | read_qword | SectionAbs | 103,116 | 103,116 | class SectionAbs():
# virt_size: size of the mapped section in memory
def __init__(self, name, start, virt_size, real_size, is_exec, is_data, is_bss, data):
self.name = name
self.start = start
self.virt_size = virt_size
self.real_size = real_size
self.end = start + virt_s... | class SectionAbs():
# virt_size: size of the mapped section in memory
def __init__(self, name, start, virt_size, real_size, is_exec, is_data, is_bss, data):
self.name = name
self.start = start
self.virt_size = virt_size
self.real_size = real_size
self.end = start + virt_s... | if ad > self.real_end:
return None
off = ad - self.start
w = self.data[off:off+8]
if len(w) != 8:
return None
if self.big_endian:
return (w[0] << 56) + (w[1] << 48) + (w[2] << 40) + (w[3] << 32) + \
(w[4] << 24) + (w[5] << 16... | if ad > self.real_end:
return None
off = ad - self.start
w = self.data[off:off+8]
if len(w) != 8:
return None
if self.big_endian:
return (w[0] << 56) + (w[1] << 48) + (w[2] << 40) + (w[3] << 32) + \
(w[4] << 24) + (w[5] << 16... | 84 | 763 | 236 | 999 | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... |
39,360 | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma/plasma/lib/fileformat/pefile2.py | 87,88 | 79,93 | get_string_at_offset | PE2 | 88,93 | 88,93 | class PE2(pefile.PE):
def get_sym_at_offset(self, off):
end = off + sizeof(SymbolEntry)
if end > len(self.__data__):
return None
return SymbolEntry.from_buffer_copy(self.__data__[off:end])
def get_string_at_offset(self, off):
FILL_FUNC_BODY | class PE2(pefile.PE):
def get_sym_at_offset(self, off):
end = off + sizeof(SymbolEntry)
if end > len(self.__data__):
return None
return SymbolEntry.from_buffer_copy(self.__data__[off:end])
def get_string_at_offset(self, off):
FILL_FUNC_BODY | s = ""
while self.__data__[off] != 0:
s += chr(self.__data__[off])
off += 1
return s
| s = ""
while self.__data__[off] != 0:
s += chr(self.__data__[off])
off += 1
return s
| 15 | 100 | 47 | 147 | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... |
39,361 | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma/plasma/lib/fileformat/raw.py | 56,57 | 23,58 | get_entry_point | Raw | 57,58 | 57,58 | class Raw(Binary):
def __init__(self, filename, raw_type, raw_base, raw_big_endian):
Binary.__init__(self)
self.raw = open(filename, "rb").read()
self.raw_base = raw_base
self.raw_big_endian = raw_big_endian
arch_lookup = {
"x86": "x86",
"x64": "x64"... | class Raw(Binary):
def __init__(self, filename, raw_type, raw_base, raw_big_endian):
Binary.__init__(self)
self.raw = open(filename, "rb").read()
self.raw_base = raw_base
self.raw_big_endian = raw_big_endian
arch_lookup = {
"x86": "x86",
"x64": "x64"... | return self.raw_base
| return self.raw_base
| 2 | 290 | 9 | 299 | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... |
39,362 | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma/plasma/lib/fileformat/relocations/i386.py | 17,19 | 16,20 | value | R_386_PC32 | 19,20 | 19,20 | class R_386_PC32(generic.Relocation):
@property
def value(self):
FILL_FUNC_BODY | class R_386_PC32(generic.Relocation):
@property
def value(self):
FILL_FUNC_BODY | return self.resolvedby.rebased_addr + self.addend - self.rebased_addr
| return self.resolvedby.rebased_addr + self.addend - self.rebased_addr
| 6 | 38 | 25 | 63 | from . import generic
arch = 'x86'
R_386_32 = generic.GenericAbsoluteAddendReloc
R_386_COPY = generic.GenericCopyReloc
R_386_GLOB_DAT = generic.GenericJumpslotReloc
R_386_JMP_SLOT = generic.GenericJumpslotReloc
R_386_RELATIVE = generic.GenericRelativeReloc
R_386_IRELATIVE = generic.GenericIRelativeReloc
R_386_TLS_DT... | from . import generic
arch = 'x86'
R_386_32 = generic.GenericAbsoluteAddendReloc
R_386_COPY = generic.GenericCopyReloc
R_386_GLOB_DAT = generic.GenericJumpslotReloc
R_386_JMP_SLOT = generic.GenericJumpslotReloc
R_386_RELATIVE = generic.GenericRelativeReloc
R_386_IRELATIVE = generic.GenericIRelativeReloc
R_386_TLS_DT... |
39,363 | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma/plasma/lib/fileformat/relocations/ppc64.py | 7,8 | 6,25 | relocate | R_PPC64_JMP_SLOT | 8,25 | 8,25 | class R_PPC64_JMP_SLOT(generic.Relocation):
def relocate(self, solist):
FILL_FUNC_BODY | class R_PPC64_JMP_SLOT(generic.Relocation):
def relocate(self, solist):
FILL_FUNC_BODY | if not self.resolve_symbol(solist):
return False
if self.owner_obj.is_ppc64_abiv1:
# R_PPC64_JMP_SLOT
# http://osxr.org/glibc/source/sysdeps/powerpc/powerpc64/dl-machine.h?v=glibc-2.15#0405
# copy an entire function descriptor struct
addr = se... | if not self.resolve_symbol(solist):
return False
if self.owner_obj.is_ppc64_abiv1:
# R_PPC64_JMP_SLOT
# http://osxr.org/glibc/source/sysdeps/powerpc/powerpc64/dl-machine.h?v=glibc-2.15#0405
# copy an entire function descriptor struct
addr = se... | 46 | 42 | 329 | 371 | from . import generic
# http://refspecs.linuxfoundation.org/ELF/ppc64/PPC-elf64abi-1.9.pdf
arch = 'PPC64'
class R_PPC64_JMP_SLOT(generic.Relocation):
def relocate(self, solist):
FILL_FUNC_BODYR_PPC64_DTPMOD64 = generic.GenericTLSModIdReloc
R_PPC64_DTPREL64 = generic.GenericTLSDoffsetReloc
R_PPC64_TPREL64 = generi... | from . import generic
# http://refspecs.linuxfoundation.org/ELF/ppc64/PPC-elf64abi-1.9.pdf
arch = 'PPC64'
class R_PPC64_JMP_SLOT(generic.Relocation):
def relocate(self, solist):
FILL_FUNC_BODYR_PPC64_DTPMOD64 = generic.GenericTLSModIdReloc
R_PPC64_DTPREL64 = generic.GenericTLSDoffsetReloc
R_PPC64_TPREL64 = generi... |
39,367 | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma/plasma/lib/ui/utils.py | 26,27 | 1,84 | popup_listbox | 31,53 | 27,53 | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | h2 = par_widget.height * 3 // 4
w2 = par_widget.width * 6 // 7
x = (par_widget.width - w2) // 2 - 1
y = (par_widget.height - h2) // 2 - 1
# A background with borders
borders = curses.newwin(h2 + 2, w2 + 2, par_widget.y + y, par_widget.x + x)
borders.border()
borders.addstr(0, (w2 - len... | """
It opens a centered popup. output is an instance of the class Output.
Returns (bool, line number of the cursor)
"""
h2 = par_widget.height * 3 // 4
w2 = par_widget.width * 6 // 7
x = (par_widget.width - w2) // 2 - 1
y = (par_widget.height - h2) // 2 - 1
# A background with bord... | 91 | 666 | 282 | 948 | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | |
39,369 | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma/plasma/lib/ui/widget.py | 74,75 | 66,78 | draw | VertivalSep | 75,78 | 75,78 | class VertivalSep(Widget):
def __init__(self, x, y, h):
w = 2
Widget.__init__(self, x, y, w, h)
self.is_passive = True
self.mapping = {}
def draw(self):
FILL_FUNC_BODY | class VertivalSep(Widget):
def __init__(self, x, y, h):
w = 2
Widget.__init__(self, x, y, w, h)
self.is_passive = True
self.mapping = {}
def draw(self):
FILL_FUNC_BODY | c = color_pair(COLOR_COMMENT.val) #| A_REVERSE
for i in range(self.height):
self.screen.addstr(i, 0, "▕", c)
| c = color_pair(COLOR_COMMENT.val) #| A_REVERSE
for i in range(self.height):
self.screen.addstr(i, 0, "▕", c)
| 13 | 81 | 56 | 137 | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... |
39,370 | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma/plasma/lib/ui/widget.py | 41,42 | 27,66 | draw | Widget | 42,45 | 42,45 | class Widget():
def __init__(self, x, y, w, h):
self.mapping = {}
self.x = x
self.y = y
self.height = h
self.width = w
self.has_focus = False
self.screen = curses.newwin(h, w, y, x)
self.should_stop = False
self.value_selected = False
s... | class Widget():
def __init__(self, x, y, w, h):
self.mapping = {}
self.x = x
self.y = y
self.height = h
self.width = w
self.has_focus = False
self.screen = curses.newwin(h, w, y, x)
self.should_stop = False
self.value_selected = False
s... | raise NotImplementedError
| raise NotImplementedError
| 2 | 238 | 13 | 251 | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... |
39,371 | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma/plasma/lib/ui/window.py | 56,57 | 31,267 | search_focus | Window | 57,64 | 57,64 | class Window():
def __init__(self):
self.screen = None
self.widgets = []
self.set_key_timeout = True
self.time_last_mouse_key = MOUSE_INTERVAL + 1
self.focus_widget_idx = 0
self.cursor_x = 0
self.cursor_y = 0
# Returns True if we should refresh the scree... | class Window():
def __init__(self):
self.screen = None
self.widgets = []
self.set_key_timeout = True
self.time_last_mouse_key = MOUSE_INTERVAL + 1
self.focus_widget_idx = 0
self.cursor_x = 0
self.cursor_y = 0
# Returns True if we should refresh the scree... | for i, w in enumerate(self.widgets):
if w.x <= x < w.x + w.width and w.y <= y < w.y + w.height and \
not w.is_passive:
return i
return -1
| for i, w in enumerate(self.widgets):
if w.x <= x < w.x + w.width and w.y <= y < w.y + w.height and \
not w.is_passive:
return i
return -1
| 29 | 1,941 | 75 | 2,016 | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... |
39,372 | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma | /home/hieuvd/dung_repo/raw/stars_02/plasma-disassembler_plasma/plasma/plasma/lib/utils.py | 137,138 | 1,193 | print_dict | 138,164 | 138,164 | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | print("[", file=sys.stderr)
for i in dic:
if isinstance(i, str):
print("%s: " % i, end="", file=sys.stderr)
elif isinstance(i, tuple):
print_tuple(i, end="")
else:
print("%x: " % i, end="", file=sys.stderr)
v = dic[i]
if isinstance(v, l... | print("[", file=sys.stderr)
for i in dic:
if isinstance(i, str):
print("%s: " % i, end="", file=sys.stderr)
elif isinstance(i, tuple):
print_tuple(i, end="")
else:
print("%x: " % i, end="", file=sys.stderr)
v = dic[i]
if isinstance(v, l... | 67 | 1,598 | 294 | 1,892 | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | |
39,413 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/_utils.py | 17,18 | 1,64 | _sanitize_dates | 30,56 | 18,56 | import datetime as dt
from pandas import to_datetime
import requests
from pandas_datareader.compat import is_number
class SymbolWarning(UserWarning):
pass
class RemoteDataError(IOError):
pass
def _sanitize_dates(start, end):
FILL_FUNC_BODYdef _init_session(session):
if session is None:
sessi... | import datetime as dt
from pandas import to_datetime
import requests
from pandas_datareader.compat import is_number
class SymbolWarning(UserWarning):
pass
class RemoteDataError(IOError):
pass
def _sanitize_dates(start, end):
"""
Return (timestamp_start, timestamp_end) tuple
if start is None ... | if is_number(start):
# regard int as year
start = dt.datetime(start, 1, 1)
start = to_datetime(start)
if is_number(end):
end = dt.datetime(end, 1, 1)
end = to_datetime(end)
if start is None:
# default to 5 years before today
today = dt.date.today()
s... | """
Return (timestamp_start, timestamp_end) tuple
if start is None - default is 5 years before the current date
if end is None - default is today
Parameters
----------
start : str, int, date, datetime, Timestamp
Desired start date
end : str, int, date, datetime, Timestamp
... | 91 | 254 | 257 | 511 | import datetime as dt
from pandas import to_datetime
import requests
from pandas_datareader.compat import is_number
class SymbolWarning(UserWarning):
pass
class RemoteDataError(IOError):
pass
def _sanitize_dates(start, end):
FILL_FUNC_BODYdef _init_session(session):
if session is None:
sessi... | import datetime as dt
from pandas import to_datetime
import requests
from pandas_datareader.compat import is_number
class SymbolWarning(UserWarning):
pass
class RemoteDataError(IOError):
pass
def _sanitize_dates(start, end):
"""
Return (timestamp_start, timestamp_end) tuple
if start is None ... | |
39,414 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/av/forex.py | 65,67 | 7,96 | data_key | AVForexReader | 67,69 | 67,69 | class AVForexReader(AlphaVantage):
"""
Returns DataFrame of the Alpha Vantage Foreign Exchange (FX) Exchange Rates
data.
.. versionadded:: 0.7.0
Parameters
----------
symbols : string, array-like object (list, tuple, Series)
Single currency pair (formatted 'FROM/TO') or list of the... | class AVForexReader(AlphaVantage):
"""
Returns DataFrame of the Alpha Vantage Foreign Exchange (FX) Exchange Rates
data.
.. versionadded:: 0.7.0
Parameters
----------
symbols : string, array-like object (list, tuple, Series)
Single currency pair (formatted 'FROM/TO') or list of the... | return "Realtime Currency Exchange Rate"
| return "Realtime Currency Exchange Rate"
| 5 | 823 | 15 | 838 | import pandas as pd
from pandas_datareader._utils import RemoteDataError
from pandas_datareader.av import AlphaVantage
class AVForexReader(AlphaVantage):
"""
Returns DataFrame of the Alpha Vantage Foreign Exchange (FX) Exchange Rates
data.
.. versionadded:: 0.7.0
Parameters
----------
s... | import pandas as pd
from pandas_datareader._utils import RemoteDataError
from pandas_datareader.av import AlphaVantage
class AVForexReader(AlphaVantage):
"""
Returns DataFrame of the Alpha Vantage Foreign Exchange (FX) Exchange Rates
data.
.. versionadded:: 0.7.0
Parameters
----------
s... |
39,415 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/av/sector.py | 33,34 | 7,42 | _read_lines | AVSectorPerformanceReader | 34,42 | 34,42 | class AVSectorPerformanceReader(AlphaVantage):
"""
Returns DataFrame of the Alpha Vantage Sector Performances SECTOR data.
.. versionadded:: 0.7.0
Parameters
----------
symbols : string, array-like object (list, tuple, Series)
Single currency pair (formatted 'FROM/TO') or list of the s... | class AVSectorPerformanceReader(AlphaVantage):
"""
Returns DataFrame of the Alpha Vantage Sector Performances SECTOR data.
.. versionadded:: 0.7.0
Parameters
----------
symbols : string, array-like object (list, tuple, Series)
Single currency pair (formatted 'FROM/TO') or list of the s... | if "Information" in out:
raise RemoteDataError()
else:
out.pop("Meta Data")
df = pd.DataFrame(out)
columns = ["RT", "1D", "5D", "1M", "3M", "YTD", "1Y", "3Y", "5Y", "10Y"]
df.columns = columns
return df
| if "Information" in out:
raise RemoteDataError()
else:
out.pop("Meta Data")
df = pd.DataFrame(out)
columns = ["RT", "1D", "5D", "1M", "3M", "YTD", "1Y", "3Y", "5Y", "10Y"]
df.columns = columns
return df
| 29 | 275 | 104 | 379 | import pandas as pd
from pandas_datareader._utils import RemoteDataError
from pandas_datareader.av import AlphaVantage
class AVSectorPerformanceReader(AlphaVantage):
"""
Returns DataFrame of the Alpha Vantage Sector Performances SECTOR data.
.. versionadded:: 0.7.0
Parameters
----------
sym... | import pandas as pd
from pandas_datareader._utils import RemoteDataError
from pandas_datareader.av import AlphaVantage
class AVSectorPerformanceReader(AlphaVantage):
"""
Returns DataFrame of the Alpha Vantage Sector Performances SECTOR data.
.. versionadded:: 0.7.0
Parameters
----------
sym... |
39,416 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/av/time_series.py | 77,79 | 6,129 | intraday | AVTimeSeriesReader | 79,81 | 79,81 | class AVTimeSeriesReader(AlphaVantage):
"""
Returns DataFrame of the Alpha Vantage Stock Time Series endpoints
.. versionadded:: 0.7.0
Parameters
----------
symbols : string
Single stock symbol (ticker)
start : string, int, date, datetime, Timestamp
Starting date. Parses ma... | class AVTimeSeriesReader(AlphaVantage):
"""
Returns DataFrame of the Alpha Vantage Stock Time Series endpoints
.. versionadded:: 0.7.0
Parameters
----------
symbols : string
Single stock symbol (ticker)
start : string, int, date, datetime, Timestamp
Starting date. Parses ma... | return True if self.function == "TIME_SERIES_INTRADAY" else False
| return True if self.function == "TIME_SERIES_INTRADAY" else False
| 8 | 1,238 | 25 | 1,263 | import datetime as dt
from pandas_datareader.av import AlphaVantage
class AVTimeSeriesReader(AlphaVantage):
"""
Returns DataFrame of the Alpha Vantage Stock Time Series endpoints
.. versionadded:: 0.7.0
Parameters
----------
symbols : string
Single stock symbol (ticker)
start : ... | import datetime as dt
from pandas_datareader.av import AlphaVantage
class AVTimeSeriesReader(AlphaVantage):
"""
Returns DataFrame of the Alpha Vantage Stock Time Series endpoints
.. versionadded:: 0.7.0
Parameters
----------
symbols : string
Single stock symbol (ticker)
start : ... |
39,417 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/bankofcanada.py | 21,23 | 4,36 | params | BankOfCanadaReader | 24,29 | 23,29 | class BankOfCanadaReader(_BaseReader):
"""Get data for the given name from Bank of Canada.
Notes
-----
See `Bank of Canada <https://www.bankofcanada.ca/rates/>`__"""
_URL = "http://www.bankofcanada.ca/valet/observations"
@property
def url(self):
"""API URL"""
if not isinst... | class BankOfCanadaReader(_BaseReader):
"""Get data for the given name from Bank of Canada.
Notes
-----
See `Bank of Canada <https://www.bankofcanada.ca/rates/>`__"""
_URL = "http://www.bankofcanada.ca/valet/observations"
@property
def url(self):
"""API URL"""
if not isinst... | return {
"start_date": self.start.strftime("%Y-%m-%d"),
"end_date": self.end.strftime("%Y-%m-%d"),
}
| """Parameters to use in API calls"""
return {
"start_date": self.start.strftime("%Y-%m-%d"),
"end_date": self.end.strftime("%Y-%m-%d"),
}
| 7 | 243 | 59 | 302 | from pandas_datareader.base import _BaseReader
class BankOfCanadaReader(_BaseReader):
"""Get data for the given name from Bank of Canada.
Notes
-----
See `Bank of Canada <https://www.bankofcanada.ca/rates/>`__"""
_URL = "http://www.bankofcanada.ca/valet/observations"
@property
def url(s... | from pandas_datareader.base import _BaseReader
class BankOfCanadaReader(_BaseReader):
"""Get data for the given name from Bank of Canada.
Notes
-----
See `Bank of Canada <https://www.bankofcanada.ca/rates/>`__"""
_URL = "http://www.bankofcanada.ca/valet/observations"
@property
def url(s... |
39,419 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/econdb.py | 78,79 | 6,117 | read | EcondbReader | 80,117 | 79,117 | class EcondbReader(_BaseReader):
"""
Returns DataFrame of historical stock prices from symbol, over date
range, start to end.
.. versionadded:: 0.5.0
Parameters
----------
symbols : string
Can be in two different formats:
1. 'ticker=<code>' for fetching a single series,
... | class EcondbReader(_BaseReader):
"""
Returns DataFrame of historical stock prices from symbol, over date
range, start to end.
.. versionadded:: 0.5.0
Parameters
----------
symbols : string
Can be in two different formats:
1. 'ticker=<code>' for fetching a single series,
... | results = self.session.get(self.url).json()["results"]
df = pd.DataFrame({"dates": []}).set_index("dates")
if self._show == "labels":
def show_func(x):
return x[x.find(":") + 1 :]
elif self._show == "codes":
def show_func(x):
re... | """read one data from specified URL"""
results = self.session.get(self.url).json()["results"]
df = pd.DataFrame({"dates": []}).set_index("dates")
if self._show == "labels":
def show_func(x):
return x[x.find(":") + 1 :]
elif self._show == "codes":
... | 120 | 770 | 463 | 1,233 | import pandas as pd
from pandas_datareader.base import _BaseReader
class EcondbReader(_BaseReader):
"""
Returns DataFrame of historical stock prices from symbol, over date
range, start to end.
.. versionadded:: 0.5.0
Parameters
----------
symbols : string
Can be in two different... | import pandas as pd
from pandas_datareader.base import _BaseReader
class EcondbReader(_BaseReader):
"""
Returns DataFrame of historical stock prices from symbol, over date
range, start to end.
.. versionadded:: 0.5.0
Parameters
----------
symbols : string
Can be in two different... |
39,420 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/enigma.py | 124,125 | 11,137 | get_dataset_metadata | EnigmaReader | 128,132 | 125,132 | class EnigmaReader(_BaseReader):
"""
Collects current snapshot of Enigma data located at the specified
data set ID and returns a pandas DataFrame.
Parameters
----------
dataset_id : str
Enigma dataset UUID.
api_key : str, optional
Enigma API key. If not provided, the environ... | class EnigmaReader(_BaseReader):
"""
Collects current snapshot of Enigma data located at the specified
data set ID and returns a pandas DataFrame.
Parameters
----------
dataset_id : str
Enigma dataset UUID.
api_key : str, optional
Enigma API key. If not provided, the environ... | url = f"datasets/{dataset_id}?row_limit=0"
response = self._get(url)
return response.json()
| """Get the Dataset Model of this EnigmaReader's dataset
https://docs.public.enigma.com/resources/dataset/index.html
"""
url = f"datasets/{dataset_id}?row_limit=0"
response = self._get(url)
return response.json()
| 8 | 1,321 | 43 | 1,364 | import os
import time
import pandas as pd
from pandas_datareader.base import _BaseReader
from pandas_datareader.compat import StringIO
from pandas_datareader.exceptions import DEP_ERROR_MSG, ImmediateDeprecationError
class EnigmaReader(_BaseReader):
"""
Collects current snapshot of Enigma data located at th... | import os
import time
import pandas as pd
from pandas_datareader.base import _BaseReader
from pandas_datareader.compat import StringIO
from pandas_datareader.exceptions import DEP_ERROR_MSG, ImmediateDeprecationError
class EnigmaReader(_BaseReader):
"""
Collects current snapshot of Enigma data located at th... |
39,421 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/eurostat.py | 12,14 | 7,48 | url | EurostatReader | 15,21 | 14,21 | class EurostatReader(_BaseReader):
"""Get data for the given name from Eurostat."""
_URL = "http://ec.europa.eu/eurostat/SDMX/diss-web/rest"
@property
def url(self):
FILL_FUNC_BODY @property
def dsd_url(self):
"""API DSD URL"""
if not isinstance(self.symbols, str):
r... | class EurostatReader(_BaseReader):
"""Get data for the given name from Eurostat."""
_URL = "http://ec.europa.eu/eurostat/SDMX/diss-web/rest"
@property
def url(self):
"""API URL"""
FILL_FUNC_BODY @property
def dsd_url(self):
"""API DSD URL"""
if not isinstance(self.symbol... | if not isinstance(self.symbols, str):
raise ValueError("data name must be string")
q = "{0}/data/{1}/?startperiod={2}&endperiod={3}"
return q.format(self._URL, self.symbols, self.start.year, self.end.year)
| """API URL"""
if not isinstance(self.symbols, str):
raise ValueError("data name must be string")
q = "{0}/data/{1}/?startperiod={2}&endperiod={3}"
return q.format(self._URL, self.symbols, self.start.year, self.end.year)
| 18 | 322 | 87 | 409 | import pandas as pd
from pandas_datareader.base import _BaseReader
from pandas_datareader.io.sdmx import _read_sdmx_dsd, read_sdmx
class EurostatReader(_BaseReader):
"""Get data for the given name from Eurostat."""
_URL = "http://ec.europa.eu/eurostat/SDMX/diss-web/rest"
@property
def url(self):
FI... | import pandas as pd
from pandas_datareader.base import _BaseReader
from pandas_datareader.io.sdmx import _read_sdmx_dsd, read_sdmx
class EurostatReader(_BaseReader):
"""Get data for the given name from Eurostat."""
_URL = "http://ec.europa.eu/eurostat/SDMX/diss-web/rest"
@property
def url(self):
... |
39,422 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/famafrench.py | 32,33 | 1,166 | _parse_date_famafrench | 33,41 | 33,41 | import datetime as dt
import re
import tempfile
from zipfile import ZipFile
from pandas import read_csv, to_datetime
from pandas_datareader.base import _BaseReader
from pandas_datareader.compat import StringIO
_URL = "http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/"
_URL_PREFIX = "ftp/"
_URL_SUFFIX = "_CSV.z... | import datetime as dt
import re
import tempfile
from zipfile import ZipFile
from pandas import read_csv, to_datetime
from pandas_datareader.base import _BaseReader
from pandas_datareader.compat import StringIO
_URL = "http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/"
_URL_PREFIX = "ftp/"
_URL_SUFFIX = "_CSV.z... | x = x.strip()
try:
return dt.datetime.strptime(x, "%Y%m")
except Exception:
pass
return to_datetime(x)
| x = x.strip()
try:
return dt.datetime.strptime(x, "%Y%m")
except Exception:
pass
return to_datetime(x)
| 12 | 1,512 | 57 | 1,569 | import datetime as dt
import re
import tempfile
from zipfile import ZipFile
from pandas import read_csv, to_datetime
from pandas_datareader.base import _BaseReader
from pandas_datareader.compat import StringIO
_URL = "http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/"
_URL_PREFIX = "ftp/"
_URL_SUFFIX = "_CSV.z... | import datetime as dt
import re
import tempfile
from zipfile import ZipFile
from pandas import read_csv, to_datetime
from pandas_datareader.base import _BaseReader
from pandas_datareader.compat import StringIO
_URL = "http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/"
_URL_PREFIX = "ftp/"
_URL_SUFFIX = "_CSV.z... | |
39,423 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/famafrench.py | 77,78 | 41,166 | _read_one_data | FamaFrenchReader | 78,136 | 78,136 | class FamaFrenchReader(_BaseReader):
"""
Get data for the given name from the Fama/French data library.
For annual and monthly data, index is a pandas.PeriodIndex, otherwise
it's a pandas.DatetimeIndex.
"""
@property
def url(self):
"""API URL"""
return "".join([_URL, _URL_P... | class FamaFrenchReader(_BaseReader):
"""
Get data for the given name from the Fama/French data library.
For annual and monthly data, index is a pandas.PeriodIndex, otherwise
it's a pandas.DatetimeIndex.
"""
@property
def url(self):
"""API URL"""
return "".join([_URL, _URL_P... | params = {
"index_col": 0,
"parse_dates": [0],
"date_parser": _parse_date_famafrench,
}
# headers in these files are not valid
if self.symbols.endswith("_Breakpoints"):
if self.symbols.find("-") > -1:
c = ["<=0", ">0"]
... | params = {
"index_col": 0,
"parse_dates": [0],
"date_parser": _parse_date_famafrench,
}
# headers in these files are not valid
if self.symbols.endswith("_Breakpoints"):
if self.symbols.find("-") > -1:
c = ["<=0", ">0"]
... | 191 | 590 | 732 | 1,322 | import datetime as dt
import re
import tempfile
from zipfile import ZipFile
from pandas import read_csv, to_datetime
from pandas_datareader.base import _BaseReader
from pandas_datareader.compat import StringIO
_URL = "http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/"
_URL_PREFIX = "ftp/"
_URL_SUFFIX = "_CSV.z... | import datetime as dt
import re
import tempfile
from zipfile import ZipFile
from pandas import read_csv, to_datetime
from pandas_datareader.base import _BaseReader
from pandas_datareader.compat import StringIO
_URL = "http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/"
_URL_PREFIX = "ftp/"
_URL_SUFFIX = "_CSV.z... |
39,424 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/fred.py | 31,32 | 7,67 | _read | FredReader | 32,67 | 32,67 | class FredReader(_BaseReader):
"""
Get data for the given name from the St. Louis FED (FRED).
"""
@property
def url(self):
"""API URL"""
return "https://fred.stlouisfed.org/graph/fredgraph.csv"
def read(self):
"""Read data
Returns
-------
data :... | class FredReader(_BaseReader):
"""
Get data for the given name from the St. Louis FED (FRED).
"""
@property
def url(self):
"""API URL"""
return "https://fred.stlouisfed.org/graph/fredgraph.csv"
def read(self):
"""Read data
Returns
-------
data :... | if not is_list_like(self.symbols):
names = [self.symbols]
else:
names = self.symbols
urls = [f"{self.url}?id={n}" for n in names]
def fetch_data(url, name):
"""Utility to fetch data"""
resp = self._read_url_as_StringIO(url)
da... | if not is_list_like(self.symbols):
names = [self.symbols]
else:
names = self.symbols
urls = [f"{self.url}?id={n}" for n in names]
def fetch_data(url, name):
"""Utility to fetch data"""
resp = self._read_url_as_StringIO(url)
da... | 92 | 177 | 356 | 533 | from pandas import concat, read_csv
from pandas_datareader.base import _BaseReader
from pandas_datareader.compat import is_list_like
class FredReader(_BaseReader):
"""
Get data for the given name from the St. Louis FED (FRED).
"""
@property
def url(self):
"""API URL"""
return "ht... | from pandas import concat, read_csv
from pandas_datareader.base import _BaseReader
from pandas_datareader.compat import is_list_like
class FredReader(_BaseReader):
"""
Get data for the given name from the St. Louis FED (FRED).
"""
@property
def url(self):
"""API URL"""
return "ht... |
39,425 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/iex/daily.py | 147,148 | 17,170 | _read_lines | IEXDailyReader | 148,170 | 148,170 | class IEXDailyReader(_DailyBaseReader):
"""
Returns DataFrame of historical stock prices
from symbols, over date range, start to end. To avoid being penalized by
IEX servers, pauses between downloading 'chunks' of symbols can be
specified.
Parameters
----------
symbols : string, array-... | class IEXDailyReader(_DailyBaseReader):
"""
Returns DataFrame of historical stock prices
from symbols, over date range, start to end. To avoid being penalized by
IEX servers, pauses between downloading 'chunks' of symbols can be
specified.
Parameters
----------
symbols : string, array-... | data = out.read()
json_data = json.loads(data)
result = {}
if type(self.symbols) is str:
syms = [self.symbols]
else:
syms = self.symbols
for symbol in syms:
d = json_data.pop(symbol)["chart"]
df = pd.DataFrame(d)
... | data = out.read()
json_data = json.loads(data)
result = {}
if type(self.symbols) is str:
syms = [self.symbols]
else:
syms = self.symbols
for symbol in syms:
d = json_data.pop(symbol)["chart"]
df = pd.DataFrame(d)
... | 68 | 1,221 | 283 | 1,504 | import datetime
import json
import os
from dateutil.relativedelta import relativedelta
import pandas as pd
from pandas_datareader.base import _DailyBaseReader
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://i... | import datetime
import json
import os
from dateutil.relativedelta import relativedelta
import pandas as pd
from pandas_datareader.base import _DailyBaseReader
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://i... |
39,426 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/iex/deep.py | 58,59 | 12,160 | _read_lines | Deep | 71,90 | 59,90 | class Deep(IEX):
"""
Retrieve order book data from IEX
Notes
-----
Real-time depth of book quotations direct from IEX. Returns aggregated
size of resting displayed orders at a price and side. Does not indicate
the size or number of individual orders at any price level. Non-displayed
ord... | class Deep(IEX):
"""
Retrieve order book data from IEX
Notes
-----
Real-time depth of book quotations direct from IEX. Returns aggregated
size of resting displayed orders at a price and side. Does not indicate
the size or number of individual orders at any price level. Non-displayed
ord... |
# Runs appropriate output functions per the service being accessed.
fmap = {
"book": "_pass",
"op-halt-status": "_convert_tstamp",
"security-event": "_convert_tstamp",
"ssr-status": "_convert_tstamp",
"system-event": "_read_system_event",
... | """
IEX depth of book data varies and shouldn't always be returned in a DF
Parameters
----------
out: bytes
The raw output from an HTTP request
Returns
-------
DataFrame
"""
# Runs appropriate output functions per the service... | 45 | 1,194 | 211 | 1,405 | from datetime import datetime
from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://iextrading.com/api-exhibit-a/ for additional information
# and conditions of use
class Deep... | from datetime import datetime
from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://iextrading.com/api-exhibit-a/ for additional information
# and conditions of use
class Deep... |
39,427 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/iex/market.py | 37,38 | 10,40 | _get_params | MarketReader | 38,40 | 38,40 | class MarketReader(IEX):
"""
Near real-time traded volume
Notes
-----
Market data is captured by the IEX system between approximately 7:45 a.m.
and 5:15 p.m. ET.
"""
def __init__(
self, symbols=None, start=None, end=None, retry_count=3, pause=0.1, session=None
):
su... | class MarketReader(IEX):
"""
Near real-time traded volume
Notes
-----
Market data is captured by the IEX system between approximately 7:45 a.m.
and 5:15 p.m. ET.
"""
def __init__(
self, symbols=None, start=None, end=None, retry_count=3, pause=0.1, session=None
):
su... | # Market API does not take any parameters, returning empty dict
return {}
| # Market API does not take any parameters, returning empty dict
return {}
| 13 | 211 | 20 | 231 | from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://iextrading.com/api-exhibit-a/ for additional information
# and conditions of use
class MarketReader(IEX):
"""
Near... | from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://iextrading.com/api-exhibit-a/ for additional information
# and conditions of use
class MarketReader(IEX):
"""
Near... |
39,428 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/iex/ref.py | 37,38 | 10,40 | _get_params | SymbolsReader | 38,40 | 38,40 | class SymbolsReader(IEX):
"""
Symbols available for trading on IEX
Notes
-----
Returns symbols IEX supports for trading. Updated daily as of 7:45 a.m.
ET.
"""
def __init__(
self, symbols=None, start=None, end=None, retry_count=3, pause=0.1, session=None
):
super()._... | class SymbolsReader(IEX):
"""
Symbols available for trading on IEX
Notes
-----
Returns symbols IEX supports for trading. Updated daily as of 7:45 a.m.
ET.
"""
def __init__(
self, symbols=None, start=None, end=None, retry_count=3, pause=0.1, session=None
):
super()._... | # Ref Data API does not take any parameters, returning empty dict
return {}
| # Ref Data API does not take any parameters, returning empty dict
return {}
| 14 | 210 | 21 | 231 | from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://iextrading.com/api-exhibit-a/ for additional information
# and conditions of use
class SymbolsReader(IEX):
"""
Sym... | from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://iextrading.com/api-exhibit-a/ for additional information
# and conditions of use
class SymbolsReader(IEX):
"""
Sym... |
39,429 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/iex/stats.py | 53,54 | 15,69 | read | DailySummaryReader | 60,69 | 54,69 | class DailySummaryReader(IEX):
"""
Daily statistics from IEX for a day or month
"""
def __init__(
self, symbols=None, start=None, end=None, retry_count=3, pause=0.1, session=None
):
import warnings
warnings.warn(
"Daily statistics is not working due to issues wi... | class DailySummaryReader(IEX):
"""
Daily statistics from IEX for a day or month
"""
def __init__(
self, symbols=None, start=None, end=None, retry_count=3, pause=0.1, session=None
):
import warnings
warnings.warn(
"Daily statistics is not working due to issues wi... | tlen = self.end - self.start
dfs = []
for date in (self.start + timedelta(n) for n in range(tlen.days)):
self.curr_date = date
tdf = super().read()
dfs.append(tdf)
return pd.concat(dfs)
| """Unfortunately, IEX's API can only retrieve data one day or one month
at a time. Rather than specifying a date range, we will have to run
the read function for each date provided.
:return: DataFrame
"""
tlen = self.end - self.start
dfs = []
for date in ... | 27 | 348 | 96 | 444 | from datetime import datetime, timedelta
import pandas as pd
from pandas_datareader.exceptions import UnstableAPIWarning
from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://i... | from datetime import datetime, timedelta
import pandas as pd
from pandas_datareader.exceptions import UnstableAPIWarning
from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://i... |
39,430 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/iex/stats.py | 100,101 | 69,132 | read | MonthlySummaryReader | 107,132 | 101,132 | class MonthlySummaryReader(IEX):
"""Monthly statistics from IEX"""
def __init__(
self, symbols=None, start=None, end=None, retry_count=3, pause=0.1, session=None
):
self.curr_date = start
self.date_format = "%Y%m"
super().__init__(
symbols=symbols,
s... | class MonthlySummaryReader(IEX):
"""Monthly statistics from IEX"""
def __init__(
self, symbols=None, start=None, end=None, retry_count=3, pause=0.1, session=None
):
self.curr_date = start
self.date_format = "%Y%m"
super().__init__(
symbols=symbols,
s... | tlen = self.end - self.start
dfs = []
# Build list of all dates within the given range
lrange = [x for x in (self.start + timedelta(n) for n in range(tlen.days))]
mrange = []
for dt in lrange:
if datetime(dt.year, dt.month, 1) not in mrange:
... | """Unfortunately, IEX's API can only retrieve data one day or one month
at a time. Rather than specifying a date range, we will have to run
the read function for each date provided.
:return: DataFrame
"""
tlen = self.end - self.start
dfs = []
# Build l... | 101 | 306 | 282 | 588 | from datetime import datetime, timedelta
import pandas as pd
from pandas_datareader.exceptions import UnstableAPIWarning
from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://i... | from datetime import datetime, timedelta
import pandas as pd
from pandas_datareader.exceptions import UnstableAPIWarning
from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://i... |
39,431 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/iex/stats.py | 195,196 | 159,198 | _get_params | RecentReader | 196,198 | 196,198 | class RecentReader(IEX):
"""Recent trading volume from IEX
Notes
-----
Returns 6 fields for each day:
* date: refers to the trading day.
* volume: refers to executions received from order routed to away
trading centers.
* routedVolume: refers to single counted shares matched ... | class RecentReader(IEX):
"""Recent trading volume from IEX
Notes
-----
Returns 6 fields for each day:
* date: refers to the trading day.
* volume: refers to executions received from order routed to away
trading centers.
* routedVolume: refers to single counted shares matched ... | # Record Stats API does not take any parameters, returning empty dict
return {}
| # Record Stats API does not take any parameters, returning empty dict
return {}
| 14 | 310 | 22 | 332 | from datetime import datetime, timedelta
import pandas as pd
from pandas_datareader.exceptions import UnstableAPIWarning
from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://i... | from datetime import datetime, timedelta
import pandas as pd
from pandas_datareader.exceptions import UnstableAPIWarning
from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://i... |
39,432 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/iex/stats.py | 154,155 | 132,159 | _get_params | RecordsReader | 155,159 | 155,159 | class RecordsReader(IEX):
"""
Total matched volume information from IEX
"""
def __init__(
self, symbols=None, start=None, end=None, retry_count=3, pause=0.1, session=None
):
super().__init__(
symbols=symbols,
start=start,
end=end,
retr... | class RecordsReader(IEX):
"""
Total matched volume information from IEX
"""
def __init__(
self, symbols=None, start=None, end=None, retry_count=3, pause=0.1, session=None
):
super().__init__(
symbols=symbols,
start=start,
end=end,
retr... | # Record Stats API does not take any parameters, returning empty dict
return {}
| # Record Stats API does not take any parameters, returning empty dict
return {}
| 14 | 170 | 26 | 196 | from datetime import datetime, timedelta
import pandas as pd
from pandas_datareader.exceptions import UnstableAPIWarning
from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://i... | from datetime import datetime, timedelta
import pandas as pd
from pandas_datareader.exceptions import UnstableAPIWarning
from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://i... |
39,433 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/iex/tops.py | 61,63 | 38,65 | service | LastReader | 64,65 | 63,65 | class LastReader(IEX):
"""
Information of executions on IEX
Notes
-----
Last provides trade data for executions on IEX. Provides last sale price,
size and time.
"""
# todo: Eventually we'll want to implement WebSockets as an option.
def __init__(
self, symbols=None, start=N... | class LastReader(IEX):
"""
Information of executions on IEX
Notes
-----
Last provides trade data for executions on IEX. Provides last sale price,
size and time.
"""
# todo: Eventually we'll want to implement WebSockets as an option.
def __init__(
self, symbols=None, start=N... | return "tops/last"
| """Service endpoint"""
return "tops/last"
| 2 | 201 | 10 | 211 | from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://iextrading.com/api-exhibit-a/ for additional information
# and conditions of use
class TopsReader(IEX):
"""
Near-r... | from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://iextrading.com/api-exhibit-a/ for additional information
# and conditions of use
class TopsReader(IEX):
"""
Near-r... |
39,434 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/iex/tops.py | 32,34 | 10,38 | service | TopsReader | 35,38 | 34,38 | class TopsReader(IEX):
"""
Near-real time aggregated bid and offer positions
Notes
-----
IEX's aggregated best quoted bid and offer position for all securities
on IEX's displayed limit order book.
"""
def __init__(
self, symbols=None, start=None, end=None, retry_count=3, pause=... | class TopsReader(IEX):
"""
Near-real time aggregated bid and offer positions
Notes
-----
IEX's aggregated best quoted bid and offer position for all securities
on IEX's displayed limit order book.
"""
def __init__(
self, symbols=None, start=None, end=None, retry_count=3, pause=... | return "tops"
| """Service endpoint"""
return "tops"
| 2 | 191 | 12 | 203 | from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://iextrading.com/api-exhibit-a/ for additional information
# and conditions of use
class TopsReader(IEX):
"""
Near-r... | from pandas_datareader.iex import IEX
# Data provided for free by IEX
# Data is furnished in compliance with the guidelines promulgated in the IEX
# API terms of service and manual
# See https://iextrading.com/api-exhibit-a/ for additional information
# and conditions of use
class TopsReader(IEX):
"""
Near-r... |
39,435 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/io/jsdmx.py | 75,76 | 1,117 | _parse_values | 76,98 | 76,98 | # pylint: disable-msg=E1101,W0613,W0603
from collections import OrderedDict
import itertools
import re
import sys
import numpy as np
import pandas as pd
from pandas_datareader.io.util import _read_content
def read_jsdmx(path_or_buf):
"""
Convert a SDMX-JSON string to pandas object
Parameters
----... | # pylint: disable-msg=E1101,W0613,W0603
from collections import OrderedDict
import itertools
import re
import sys
import numpy as np
import pandas as pd
from pandas_datareader.io.util import _read_content
def read_jsdmx(path_or_buf):
"""
Convert a SDMX-JSON string to pandas object
Parameters
----... | size = len(index)
series = dataset["series"]
values = []
# for s_key, s_value in iteritems(series):
for s_key in _get_indexer(columns):
try:
observations = series[s_key]["observations"]
observed = []
for o_key in _get_indexer(index):
try:
... | size = len(index)
series = dataset["series"]
values = []
# for s_key, s_value in iteritems(series):
for s_key in _get_indexer(columns):
try:
observations = series[s_key]["observations"]
observed = []
for o_key in _get_indexer(index):
try:
... | 45 | 883 | 193 | 1,076 | # pylint: disable-msg=E1101,W0613,W0603
from collections import OrderedDict
import itertools
import re
import sys
import numpy as np
import pandas as pd
from pandas_datareader.io.util import _read_content
def read_jsdmx(path_or_buf):
"""
Convert a SDMX-JSON string to pandas object
Parameters
----... | # pylint: disable-msg=E1101,W0613,W0603
from collections import OrderedDict
import itertools
import re
import sys
import numpy as np
import pandas as pd
from pandas_datareader.io.util import _read_content
def read_jsdmx(path_or_buf):
"""
Convert a SDMX-JSON string to pandas object
Parameters
----... | |
39,437 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/io/util.py | 6,7 | 1,30 | _read_content | 10,30 | 7,30 | import os
from pandas_datareader.compat import get_filepath_or_buffer
def _read_content(path_or_buf):
FILL_FUNC_BODY | import os
from pandas_datareader.compat import get_filepath_or_buffer
def _read_content(path_or_buf):
"""
Copied part of internal logic from pandas.io.read_json.
"""
FILL_FUNC_BODY |
filepath_or_buffer = get_filepath_or_buffer(path_or_buf)[0]
if isinstance(filepath_or_buffer, str):
try:
exists = os.path.exists(filepath_or_buffer)
except (TypeError, ValueError):
exists = False
if exists:
with open(filepath_or_buffer) as fh:
... | """
Copied part of internal logic from pandas.io.read_json.
"""
filepath_or_buffer = get_filepath_or_buffer(path_or_buf)[0]
if isinstance(filepath_or_buffer, str):
try:
exists = os.path.exists(filepath_or_buffer)
except (TypeError, ValueError):
exists = Fals... | 41 | 72 | 193 | 265 | import os
from pandas_datareader.compat import get_filepath_or_buffer
def _read_content(path_or_buf):
FILL_FUNC_BODY | import os
from pandas_datareader.compat import get_filepath_or_buffer
def _read_content(path_or_buf):
"""
Copied part of internal logic from pandas.io.read_json.
"""
FILL_FUNC_BODY | |
39,439 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/nasdaq_trader.py | 36,37 | 1,118 | _download_nasdaq_symbols | 40,85 | 37,85 | from ftplib import FTP, all_errors
import time
import warnings
from pandas import read_csv
from pandas_datareader._utils import RemoteDataError
from pandas_datareader.compat import StringIO
_NASDAQ_TICKER_LOC = "/SymbolDirectory/nasdaqtraded.txt"
_NASDAQ_FTP_SERVER = "ftp.nasdaqtrader.com"
_TICKER_DTYPE = [
("Na... | from ftplib import FTP, all_errors
import time
import warnings
from pandas import read_csv
from pandas_datareader._utils import RemoteDataError
from pandas_datareader.compat import StringIO
_NASDAQ_TICKER_LOC = "/SymbolDirectory/nasdaqtraded.txt"
_NASDAQ_FTP_SERVER = "ftp.nasdaqtrader.com"
_TICKER_DTYPE = [
("Na... | try:
ftp_session = FTP(_NASDAQ_FTP_SERVER, timeout=timeout)
ftp_session.login()
except all_errors as err:
raise RemoteDataError(
f"Error connecting to {_NASDAQ_FTP_SERVER!r}: {err}"
) from err
lines = []
try:
ftp_session.retrlines("RETR " + _NASDAQ_TI... | """
@param timeout: the time to wait for the FTP connection
"""
try:
ftp_session = FTP(_NASDAQ_FTP_SERVER, timeout=timeout)
ftp_session.login()
except all_errors as err:
raise RemoteDataError(
f"Error connecting to {_NASDAQ_FTP_SERVER!r}: {err}"
) from err... | 142 | 618 | 502 | 1,120 | from ftplib import FTP, all_errors
import time
import warnings
from pandas import read_csv
from pandas_datareader._utils import RemoteDataError
from pandas_datareader.compat import StringIO
_NASDAQ_TICKER_LOC = "/SymbolDirectory/nasdaqtraded.txt"
_NASDAQ_FTP_SERVER = "ftp.nasdaqtrader.com"
_TICKER_DTYPE = [
("Na... | from ftplib import FTP, all_errors
import time
import warnings
from pandas import read_csv
from pandas_datareader._utils import RemoteDataError
from pandas_datareader.compat import StringIO
_NASDAQ_TICKER_LOC = "/SymbolDirectory/nasdaqtraded.txt"
_NASDAQ_FTP_SERVER = "ftp.nasdaqtrader.com"
_TICKER_DTYPE = [
("Na... | |
39,440 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/oecd.py | 12,14 | 7,37 | url | OECDReader | 15,23 | 14,23 | class OECDReader(_BaseReader):
"""Get data for the given name from OECD."""
_format = "json"
@property
def url(self):
FILL_FUNC_BODY def _read_lines(self, out):
"""read one data from specified URL"""
df = read_jsdmx(out)
try:
idx_name = df.index.name # hack for ... | class OECDReader(_BaseReader):
"""Get data for the given name from OECD."""
_format = "json"
@property
def url(self):
"""API URL"""
FILL_FUNC_BODY def _read_lines(self, out):
"""read one data from specified URL"""
df = read_jsdmx(out)
try:
idx_name = df.i... | url = "https://stats.oecd.org/SDMX-JSON/data"
if not isinstance(self.symbols, str):
raise ValueError("data name must be string")
# API: https://data.oecd.org/api/sdmx-json-documentation/
return f"{url}/{self.symbols}/all/all"
| """API URL"""
url = "https://stats.oecd.org/SDMX-JSON/data"
if not isinstance(self.symbols, str):
raise ValueError("data name must be string")
# API: https://data.oecd.org/api/sdmx-json-documentation/
return f"{url}/{self.symbols}/all/all"
| 18 | 228 | 103 | 331 | import pandas as pd
from pandas_datareader.base import _BaseReader
from pandas_datareader.io import read_jsdmx
class OECDReader(_BaseReader):
"""Get data for the given name from OECD."""
_format = "json"
@property
def url(self):
FILL_FUNC_BODY def _read_lines(self, out):
"""read one data... | import pandas as pd
from pandas_datareader.base import _BaseReader
from pandas_datareader.io import read_jsdmx
class OECDReader(_BaseReader):
"""Get data for the given name from OECD."""
_format = "json"
@property
def url(self):
"""API URL"""
FILL_FUNC_BODY def _read_lines(self, out):
... |
39,441 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/quandl.py | 133,134 | 7,148 | read | QuandlReader | 135,148 | 134,148 | class QuandlReader(_DailyBaseReader):
"""
Returns DataFrame of historical stock prices from symbol, over date
range, start to end.
.. versionadded:: 0.5.0
Parameters
----------
symbols : string
Possible formats:
1. DB/SYM: The Quandl 'codes': DB is the database name,
... | class QuandlReader(_DailyBaseReader):
"""
Returns DataFrame of historical stock prices from symbol, over date
range, start to end.
.. versionadded:: 0.5.0
Parameters
----------
symbols : string
Possible formats:
1. DB/SYM: The Quandl 'codes': DB is the database name,
... | df = super().read()
df.rename(
columns=lambda n: n.replace(" ", "")
.replace(".", "")
.replace("/", "")
.replace("%", "")
.replace("(", "")
.replace(")", "")
.replace("'", "")
.replace("-", ""),
i... | """Read data"""
df = super().read()
df.rename(
columns=lambda n: n.replace(" ", "")
.replace(".", "")
.replace("/", "")
.replace("%", "")
.replace("(", "")
.replace(")", "")
.replace("'", "")
.replace... | 27 | 1,584 | 115 | 1,699 | import os
import re
from pandas_datareader.base import _DailyBaseReader
class QuandlReader(_DailyBaseReader):
"""
Returns DataFrame of historical stock prices from symbol, over date
range, start to end.
.. versionadded:: 0.5.0
Parameters
----------
symbols : string
Possible form... | import os
import re
from pandas_datareader.base import _DailyBaseReader
class QuandlReader(_DailyBaseReader):
"""
Returns DataFrame of historical stock prices from symbol, over date
range, start to end.
.. versionadded:: 0.5.0
Parameters
----------
symbols : string
Possible form... |
39,442 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/stooq.py | 41,42 | 4,69 | _get_params | StooqDailyReader | 42,69 | 42,69 | class StooqDailyReader(_DailyBaseReader):
"""
Returns DataFrame/dict of Dataframes of historical stock prices from
symbols, over date range, start to end.
Parameters
----------
symbols : string, array-like object (list, tuple, Series), or DataFrame
Single stock symbol (ticker), array-l... | class StooqDailyReader(_DailyBaseReader):
"""
Returns DataFrame/dict of Dataframes of historical stock prices from
symbols, over date range, start to end.
Parameters
----------
symbols : string, array-like object (list, tuple, Series), or DataFrame
Single stock symbol (ticker), array-l... | symbol_parts = symbol.split(".")
if not symbol.startswith("^"):
if len(symbol_parts) == 1:
symbol = ".".join([symbol, country])
elif symbol_parts[1].lower() == "pl":
symbol = symbol_parts[0]
else:
if symbol_parts[1].lowe... | symbol_parts = symbol.split(".")
if not symbol.startswith("^"):
if len(symbol_parts) == 1:
symbol = ".".join([symbol, country])
elif symbol_parts[1].lower() == "pl":
symbol = symbol_parts[0]
else:
if symbol_parts[1].lowe... | 56 | 403 | 254 | 657 | from pandas_datareader.base import _DailyBaseReader
class StooqDailyReader(_DailyBaseReader):
"""
Returns DataFrame/dict of Dataframes of historical stock prices from
symbols, over date range, start to end.
Parameters
----------
symbols : string, array-like object (list, tuple, Series), or D... | from pandas_datareader.base import _DailyBaseReader
class StooqDailyReader(_DailyBaseReader):
"""
Returns DataFrame/dict of Dataframes of historical stock prices from
symbols, over date range, start to end.
Parameters
----------
symbols : string, array-like object (list, tuple, Series), or D... |
39,444 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/tiingo.py | 218,219 | 135,237 | _read_lines | TiingoDailyReader | 219,225 | 219,225 | class TiingoDailyReader(_BaseReader):
"""
Historical daily data from Tiingo on equities, ETFs and mutual funds
Parameters
----------
symbols : {str, List[str]}
String symbol or list of symbols
start : string, int, date, datetime, Timestamp
Starting date, timestamp. Parses many d... | class TiingoDailyReader(_BaseReader):
"""
Historical daily data from Tiingo on equities, ETFs and mutual funds
Parameters
----------
symbols : {str, List[str]}
String symbol or list of symbols
start : string, int, date, datetime, Timestamp
Starting date, timestamp. Parses many d... | df = pd.DataFrame(out)
df["symbol"] = self._symbol
df["date"] = pd.to_datetime(df["date"])
df = df.set_index(["symbol", "date"])
return df
| df = pd.DataFrame(out)
df["symbol"] = self._symbol
df["date"] = pd.to_datetime(df["date"])
df = df.set_index(["symbol", "date"])
return df
| 15 | 930 | 69 | 999 | import os
import pandas as pd
from pandas_datareader.base import _BaseReader
def get_tiingo_symbols():
"""
Get the set of stock symbols supported by Tiingo
Returns
-------
symbols : DataFrame
DataFrame with symbols (ticker), exchange, asset type, currency and
start and end dates... | import os
import pandas as pd
from pandas_datareader.base import _BaseReader
def get_tiingo_symbols():
"""
Get the set of stock symbols supported by Tiingo
Returns
-------
symbols : DataFrame
DataFrame with symbols (ticker), exchange, asset type, currency and
start and end dates... |
39,445 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/tiingo.py | 107,108 | 26,135 | _read_one_data | TiingoIEXHistoricalReader | 109,116 | 108,116 | class TiingoIEXHistoricalReader(_BaseReader):
"""
Historical data from Tiingo on equities, ETFs and mutual funds,
with re-sampling capability. This query is limited to the last
1,000 bars based in the endDate. So the startDate is moved if
it goes past the limit.
Parameters
----------
sy... | class TiingoIEXHistoricalReader(_BaseReader):
"""
Historical data from Tiingo on equities, ETFs and mutual funds,
with re-sampling capability. This query is limited to the last
1,000 bars based in the endDate. So the startDate is moved if
it goes past the limit.
Parameters
----------
sy... | headers = {
"Content-Type": "application/json",
"Authorization": "Token " + self.api_key,
}
out = self._get_response(url, params=params, headers=headers).json()
return self._read_lines(out)
| """read one data from specified URL"""
headers = {
"Content-Type": "application/json",
"Authorization": "Token " + self.api_key,
}
out = self._get_response(url, params=params, headers=headers).json()
return self._read_lines(out)
| 18 | 1,032 | 77 | 1,109 | import os
import pandas as pd
from pandas_datareader.base import _BaseReader
def get_tiingo_symbols():
"""
Get the set of stock symbols supported by Tiingo
Returns
-------
symbols : DataFrame
DataFrame with symbols (ticker), exchange, asset type, currency and
start and end dates... | import os
import pandas as pd
from pandas_datareader.base import _BaseReader
def get_tiingo_symbols():
"""
Get the set of stock symbols supported by Tiingo
Returns
-------
symbols : DataFrame
DataFrame with symbols (ticker), exchange, asset type, currency and
start and end dates... |
39,446 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/tiingo.py | 289,290 | 237,295 | _read_lines | TiingoMetaDataReader | 290,295 | 290,295 | class TiingoMetaDataReader(TiingoDailyReader):
"""
Read metadata about symbols from Tiingo
Parameters
----------
symbols : {str, List[str]}
String symbol or list of symbols
start : string, int, date, datetime, Timestamp
Not used.
end : string, int, date, datetime, Timestamp
... | class TiingoMetaDataReader(TiingoDailyReader):
"""
Read metadata about symbols from Tiingo
Parameters
----------
symbols : {str, List[str]}
String symbol or list of symbols
start : string, int, date, datetime, Timestamp
Not used.
end : string, int, date, datetime, Timestamp
... | s = pd.Series(out)
s.name = self._symbol
return s
| s = pd.Series(out)
s.name = self._symbol
return s
| 8 | 437 | 31 | 468 | import os
import pandas as pd
from pandas_datareader.base import _BaseReader
def get_tiingo_symbols():
"""
Get the set of stock symbols supported by Tiingo
Returns
-------
symbols : DataFrame
DataFrame with symbols (ticker), exchange, asset type, currency and
start and end dates... | import os
import pandas as pd
from pandas_datareader.base import _BaseReader
def get_tiingo_symbols():
"""
Get the set of stock symbols supported by Tiingo
Returns
-------
symbols : DataFrame
DataFrame with symbols (ticker), exchange, asset type, currency and
start and end dates... |
39,447 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/tiingo.py | 325,327 | 295,328 | params | TiingoQuoteReader | 327,328 | 327,328 | class TiingoQuoteReader(TiingoDailyReader):
"""
Read quotes (latest prices) from Tiingo
Parameters
----------
symbols : {str, List[str]}
String symbol or list of symbols
start : string, int, date, datetime, Timestamp
Not used.
end : string, int, date, datetime, Timestamp
... | class TiingoQuoteReader(TiingoDailyReader):
"""
Read quotes (latest prices) from Tiingo
Parameters
----------
symbols : {str, List[str]}
String symbol or list of symbols
start : string, int, date, datetime, Timestamp
Not used.
end : string, int, date, datetime, Timestamp
... | return None
| return None
| 2 | 277 | 5 | 282 | import os
import pandas as pd
from pandas_datareader.base import _BaseReader
def get_tiingo_symbols():
"""
Get the set of stock symbols supported by Tiingo
Returns
-------
symbols : DataFrame
DataFrame with symbols (ticker), exchange, asset type, currency and
start and end dates... | import os
import pandas as pd
from pandas_datareader.base import _BaseReader
def get_tiingo_symbols():
"""
Get the set of stock symbols supported by Tiingo
Returns
-------
symbols : DataFrame
DataFrame with symbols (ticker), exchange, asset type, currency and
start and end dates... |
39,448 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/tsp.py | 92,94 | 4,101 | _sanitize_response | TSPReader | 97,101 | 94,101 | class TSPReader(_BaseReader):
"""
Returns DataFrame of historical TSP fund prices from symbols, over date
range, start to end.
Parameters
----------
symbols : str, array-like object (list, tuple, Series), or DataFrame
Single stock symbol (ticker), array-like object of symbols or
... | class TSPReader(_BaseReader):
"""
Returns DataFrame of historical TSP fund prices from symbols, over date
range, start to end.
Parameters
----------
symbols : str, array-like object (list, tuple, Series), or DataFrame
Single stock symbol (ticker), array-like object of symbols or
... | text = response.text.strip()
if text[-1] == ",":
return text[0:-1]
return text
| """
Clean up the response string
"""
text = response.text.strip()
if text[-1] == ",":
return text[0:-1]
return text
| 11 | 809 | 38 | 847 | from pandas_datareader.base import _BaseReader
class TSPReader(_BaseReader):
"""
Returns DataFrame of historical TSP fund prices from symbols, over date
range, start to end.
Parameters
----------
symbols : str, array-like object (list, tuple, Series), or DataFrame
Single stock symbol... | from pandas_datareader.base import _BaseReader
class TSPReader(_BaseReader):
"""
Returns DataFrame of historical TSP fund prices from symbols, over date
range, start to end.
Parameters
----------
symbols : str, array-like object (list, tuple, Series), or DataFrame
Single stock symbol... |
39,449 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/yahoo/actions.py | 30,31 | 1,62 | _get_one_action | 31,52 | 31,52 | import pandas as pd
from pandas import DataFrame, MultiIndex
from pandas_datareader.yahoo.daily import YahooDailyReader
class YahooActionReader(YahooDailyReader):
"""
Returns DataFrame of historical corporate actions (dividends and stock
splits) from symbols, over date range, start to end. All dates in t... | import pandas as pd
from pandas import DataFrame, MultiIndex
from pandas_datareader.yahoo.daily import YahooDailyReader
class YahooActionReader(YahooDailyReader):
"""
Returns DataFrame of historical corporate actions (dividends and stock
splits) from symbols, over date range, start to end. All dates in t... | actions = DataFrame(columns=["action", "value"])
if "Dividends" in data.columns:
# Add a label column so we can combine our two DFs
dividends = DataFrame(data["Dividends"]).dropna()
dividends["action"] = "DIVIDEND"
dividends = dividends.rename(columns={"Dividends": "value"})
... | actions = DataFrame(columns=["action", "value"])
if "Dividends" in data.columns:
# Add a label column so we can combine our two DFs
dividends = DataFrame(data["Dividends"]).dropna()
dividends["action"] = "DIVIDEND"
dividends = dividends.rename(columns={"Dividends": "value"})
... | 76 | 345 | 285 | 630 | import pandas as pd
from pandas import DataFrame, MultiIndex
from pandas_datareader.yahoo.daily import YahooDailyReader
class YahooActionReader(YahooDailyReader):
"""
Returns DataFrame of historical corporate actions (dividends and stock
splits) from symbols, over date range, start to end. All dates in t... | import pandas as pd
from pandas import DataFrame, MultiIndex
from pandas_datareader.yahoo.daily import YahooDailyReader
class YahooActionReader(YahooDailyReader):
"""
Returns DataFrame of historical corporate actions (dividends and stock
splits) from symbols, over date range, start to end. All dates in t... | |
39,450 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/yahoo/actions.py | 25,27 | 7,30 | get_actions | YahooActionReader | 27,30 | 27,30 | class YahooActionReader(YahooDailyReader):
"""
Returns DataFrame of historical corporate actions (dividends and stock
splits) from symbols, over date range, start to end. All dates in the
resulting DataFrame correspond with dividend and stock split ex-dates.
"""
def read(self):
data = s... | class YahooActionReader(YahooDailyReader):
"""
Returns DataFrame of historical corporate actions (dividends and stock
splits) from symbols, over date range, start to end. All dates in the
resulting DataFrame correspond with dividend and stock split ex-dates.
"""
def read(self):
data = s... | return True
| return True
| 2 | 199 | 9 | 208 | import pandas as pd
from pandas import DataFrame, MultiIndex
from pandas_datareader.yahoo.daily import YahooDailyReader
class YahooActionReader(YahooDailyReader):
"""
Returns DataFrame of historical corporate actions (dividends and stock
splits) from symbols, over date range, start to end. All dates in t... | import pandas as pd
from pandas import DataFrame, MultiIndex
from pandas_datareader.yahoo.daily import YahooDailyReader
class YahooActionReader(YahooDailyReader):
"""
Returns DataFrame of historical corporate actions (dividends and stock
splits) from symbols, over date range, start to end. All dates in t... |
39,451 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/yahoo/actions.py | 53,54 | 52,58 | read | YahooDivReader | 54,58 | 54,58 | class YahooDivReader(YahooActionReader):
def read(self):
FILL_FUNC_BODY | class YahooDivReader(YahooActionReader):
def read(self):
FILL_FUNC_BODY | data = super().read()
return data[data["action"] == "DIVIDEND"]
| data = super().read()
return data[data["action"] == "DIVIDEND"]
| 7 | 30 | 30 | 60 | import pandas as pd
from pandas import DataFrame, MultiIndex
from pandas_datareader.yahoo.daily import YahooDailyReader
class YahooActionReader(YahooDailyReader):
"""
Returns DataFrame of historical corporate actions (dividends and stock
splits) from symbols, over date range, start to end. All dates in t... | import pandas as pd
from pandas import DataFrame, MultiIndex
from pandas_datareader.yahoo.daily import YahooDailyReader
class YahooActionReader(YahooDailyReader):
"""
Returns DataFrame of historical corporate actions (dividends and stock
splits) from symbols, over date range, start to end. All dates in t... |
39,452 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/yahoo/actions.py | 59,60 | 58,62 | read | YahooSplitReader | 60,62 | 60,62 | class YahooSplitReader(YahooActionReader):
def read(self):
FILL_FUNC_BODY | class YahooSplitReader(YahooActionReader):
def read(self):
FILL_FUNC_BODY | data = super().read()
return data[data["action"] == "SPLIT"]
| data = super().read()
return data[data["action"] == "SPLIT"]
| 7 | 30 | 25 | 55 | import pandas as pd
from pandas import DataFrame, MultiIndex
from pandas_datareader.yahoo.daily import YahooDailyReader
class YahooActionReader(YahooDailyReader):
"""
Returns DataFrame of historical corporate actions (dividends and stock
splits) from symbols, over date range, start to end. All dates in t... | import pandas as pd
from pandas import DataFrame, MultiIndex
from pandas_datareader.yahoo.daily import YahooDailyReader
class YahooActionReader(YahooDailyReader):
"""
Returns DataFrame of historical corporate actions (dividends and stock
splits) from symbols, over date range, start to end. All dates in t... |
39,453 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/yahoo/components.py | 9,10 | 1,61 | _get_data | 30,61 | 10,61 | from pandas import DataFrame
from pandas.io.common import urlopen
from pandas_datareader.exceptions import DEP_ERROR_MSG, ImmediateDeprecationError
_URL = "http://download.finance.yahoo.com/d/quotes.csv?"
def _get_data(idx_sym): # pragma: no cover
FILL_FUNC_BODY | from pandas import DataFrame
from pandas.io.common import urlopen
from pandas_datareader.exceptions import DEP_ERROR_MSG, ImmediateDeprecationError
_URL = "http://download.finance.yahoo.com/d/quotes.csv?"
def _get_data(idx_sym): # pragma: no cover
"""
Returns DataFrame containing list of component informat... | raise ImmediateDeprecationError(DEP_ERROR_MSG.format("Yahoo Components"))
stats = "snx"
# URL of form:
# http://download.finance.yahoo.com/d/quotes.csv?s=@%5EIXIC&f=snxl1d1t1c1ohgv
url = _URL + "s={0}&f={1}&e=.csv&h={2}"
idx_mod = idx_sym.replace("^", "@%5E")
url_str = url.format(idx_mod, s... | """
Returns DataFrame containing list of component information for
index represented in idx_sym from yahoo. Includes component symbol
(ticker), exchange, and name.
Parameters
----------
idx_sym : str
Stock index symbol
Examples:
'^DJI' (Dow Jones Industrial Average)
... | 100 | 250 | 441 | 691 | from pandas import DataFrame
from pandas.io.common import urlopen
from pandas_datareader.exceptions import DEP_ERROR_MSG, ImmediateDeprecationError
_URL = "http://download.finance.yahoo.com/d/quotes.csv?"
def _get_data(idx_sym): # pragma: no cover
FILL_FUNC_BODY | from pandas import DataFrame
from pandas.io.common import urlopen
from pandas_datareader.exceptions import DEP_ERROR_MSG, ImmediateDeprecationError
_URL = "http://download.finance.yahoo.com/d/quotes.csv?"
def _get_data(idx_sym): # pragma: no cover
"""
Returns DataFrame containing list of component informat... | |
39,456 | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader | /home/hieuvd/dung_repo/raw/stars_02/pydata_pandas-datareader/pandas-datareader/pandas_datareader/yahoo/fx.py | 56,57 | 11,113 | read | YahooFXReader | 58,79 | 57,79 | class YahooFXReader(YahooDailyReader):
"""
Returns DataFrame of historical prices for currencies
Parameters
----------
symbols : string, array-like object (list, tuple, Series), or DataFrame
Single stock symbol (ticker), array-like object of symbols or
DataFrame with index containin... | class YahooFXReader(YahooDailyReader):
"""
Returns DataFrame of historical prices for currencies
Parameters
----------
symbols : string, array-like object (list, tuple, Series), or DataFrame
Single stock symbol (ticker), array-like object of symbols or
DataFrame with index containin... | try:
# If a single symbol, (e.g., 'GOOG')
if isinstance(self.symbols, (str, int)):
df = self._read_one_data(self.symbols)
# Or multiple symbols, (e.g., ['GOOG', 'AAPL', 'MSFT'])
elif isinstance(self.symbols, DataFrame):
df = self._... | """Read data"""
try:
# If a single symbol, (e.g., 'GOOG')
if isinstance(self.symbols, (str, int)):
df = self._read_one_data(self.symbols)
# Or multiple symbols, (e.g., ['GOOG', 'AAPL', 'MSFT'])
elif isinstance(self.symbols, DataFrame):
... | 52 | 985 | 235 | 1,220 | import json
import time
import warnings
from pandas import DataFrame, Series, concat, to_datetime
from pandas_datareader._utils import RemoteDataError, SymbolWarning
from pandas_datareader.yahoo.daily import YahooDailyReader
class YahooFXReader(YahooDailyReader):
"""
Returns DataFrame of historical prices f... | import json
import time
import warnings
from pandas import DataFrame, Series, concat, to_datetime
from pandas_datareader._utils import RemoteDataError, SymbolWarning
from pandas_datareader.yahoo.daily import YahooDailyReader
class YahooFXReader(YahooDailyReader):
"""
Returns DataFrame of historical prices f... |
39,479 | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter/setup.py | 7,8 | 1,61 | local_scheme | 10,12 | 8,12 | from setuptools import setup, find_packages
with open("README") as f:
long_description = f.read()
def local_scheme(version):
FILL_FUNC_BODYsetup(name='twitter',
description="An API and command-line toolset for Twitter (twitter.com)",
long_description=long_description,
long_description_content_t... | from setuptools import setup, find_packages
with open("README") as f:
long_description = f.read()
def local_scheme(version):
"""Skip the local version (eg. +xyz of 0.6.1.dev4+gdf99fe2)
to be able to upload to Test PyPI"""
FILL_FUNC_BODYsetup(name='twitter',
description="An API and command-line tool... | return ""
| """Skip the local version (eg. +xyz of 0.6.1.dev4+gdf99fe2)
to be able to upload to Test PyPI"""
return ""
| 2 | 776 | 7 | 783 | from setuptools import setup, find_packages
with open("README") as f:
long_description = f.read()
def local_scheme(version):
FILL_FUNC_BODYsetup(name='twitter',
description="An API and command-line toolset for Twitter (twitter.com)",
long_description=long_description,
long_description_content_t... | from setuptools import setup, find_packages
with open("README") as f:
long_description = f.read()
def local_scheme(version):
"""Skip the local version (eg. +xyz of 0.6.1.dev4+gdf99fe2)
to be able to upload to Test PyPI"""
FILL_FUNC_BODYsetup(name='twitter',
description="An API and command-line tool... | |
39,480 | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter/twitter/ansi.py | 101,102 | 1,103 | cmdColourNamed | 102,103 | 102,103 | """
Support for ANSI colours in command-line client.
.. data:: ESC
ansi escape character
.. data:: RESET
ansi reset colour (ansi value)
.. data:: COLOURS_NAMED
dict of colour names mapped to their ansi value
.. data:: COLOURS_MIDS
A list of ansi values for Mid Spectrum Colours
"""
import itertools
... | """
Support for ANSI colours in command-line client.
.. data:: ESC
ansi escape character
.. data:: RESET
ansi reset colour (ansi value)
.. data:: COLOURS_NAMED
dict of colour names mapped to their ansi value
.. data:: COLOURS_MIDS
A list of ansi values for Mid Spectrum Colours
"""
import itertools
... | return AnsiCmd(False).cmdColourNamed(colour)
| return AnsiCmd(False).cmdColourNamed(colour)
| 2 | 876 | 18 | 894 | """
Support for ANSI colours in command-line client.
.. data:: ESC
ansi escape character
.. data:: RESET
ansi reset colour (ansi value)
.. data:: COLOURS_NAMED
dict of colour names mapped to their ansi value
.. data:: COLOURS_MIDS
A list of ansi values for Mid Spectrum Colours
"""
import itertools
... | """
Support for ANSI colours in command-line client.
.. data:: ESC
ansi escape character
.. data:: RESET
ansi reset colour (ansi value)
.. data:: COLOURS_NAMED
dict of colour names mapped to their ansi value
.. data:: COLOURS_MIDS
A list of ansi values for Mid Spectrum Colours
"""
import itertools
... | |
39,481 | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter/twitter/ansi.py | 82,83 | 54,94 | cmdBold | AnsiCmd | 83,88 | 83,88 | class AnsiCmd(object):
def __init__(self, forceAnsi):
self.forceAnsi = forceAnsi
def cmdReset(self):
''' Returns the ansi cmd colour for a RESET '''
if sys.stdout.isatty() or self.forceAnsi:
return ESC + "[0m"
else:
return ""
def cmdColour(self, colo... | class AnsiCmd(object):
def __init__(self, forceAnsi):
self.forceAnsi = forceAnsi
def cmdReset(self):
''' Returns the ansi cmd colour for a RESET '''
if sys.stdout.isatty() or self.forceAnsi:
return ESC + "[0m"
else:
return ""
def cmdColour(self, colo... | if sys.stdout.isatty() or self.forceAnsi:
return ESC + "[1m"
else:
return ""
| if sys.stdout.isatty() or self.forceAnsi:
return ESC + "[1m"
else:
return ""
| 11 | 327 | 43 | 370 | """
Support for ANSI colours in command-line client.
.. data:: ESC
ansi escape character
.. data:: RESET
ansi reset colour (ansi value)
.. data:: COLOURS_NAMED
dict of colour names mapped to their ansi value
.. data:: COLOURS_MIDS
A list of ansi values for Mid Spectrum Colours
"""
import itertools
... | """
Support for ANSI colours in command-line client.
.. data:: ESC
ansi escape character
.. data:: RESET
ansi reset colour (ansi value)
.. data:: COLOURS_NAMED
dict of colour names mapped to their ansi value
.. data:: COLOURS_MIDS
A list of ansi values for Mid Spectrum Colours
"""
import itertools
... |
39,482 | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter/twitter/ansi.py | 45,46 | 36,54 | colourFor | ColourMap | 50,54 | 46,54 | class ColourMap(object):
'''
Object that allows for mapping strings to ansi colour values.
'''
def __init__(self, colors=COLOURS_MIDS):
''' uses the list of ansi `colors` values to initialize the map '''
self._cmap = {}
self._colourIter = itertools.cycle(colors)
def colourFo... | class ColourMap(object):
'''
Object that allows for mapping strings to ansi colour values.
'''
def __init__(self, colors=COLOURS_MIDS):
''' uses the list of ansi `colors` values to initialize the map '''
self._cmap = {}
self._colourIter = itertools.cycle(colors)
def colourFo... | if string not in self._cmap:
self._cmap[string] = next(self._colourIter)
return self._cmap[string]
| '''
Returns an ansi colour value given a `string`.
The same ansi colour value is always returned for the same string
'''
if string not in self._cmap:
self._cmap[string] = next(self._colourIter)
return self._cmap[string]
| 10 | 145 | 44 | 189 | """
Support for ANSI colours in command-line client.
.. data:: ESC
ansi escape character
.. data:: RESET
ansi reset colour (ansi value)
.. data:: COLOURS_NAMED
dict of colour names mapped to their ansi value
.. data:: COLOURS_MIDS
A list of ansi values for Mid Spectrum Colours
"""
import itertools
... | """
Support for ANSI colours in command-line client.
.. data:: ESC
ansi escape character
.. data:: RESET
ansi reset colour (ansi value)
.. data:: COLOURS_NAMED
dict of colour names mapped to their ansi value
.. data:: COLOURS_MIDS
A list of ansi values for Mid Spectrum Colours
"""
import itertools
... |
39,483 | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter/twitter/auth.py | 20,21 | 9,26 | generate_headers | Auth | 23,26 | 21,26 | class Auth(object):
"""
ABC for Authenticator objects.
"""
def encode_params(self, base_url, method, params):
"""Encodes parameters for a request suitable for including in a URL
or POST body. This method may also add new params to the request
if required by the authentication s... | class Auth(object):
"""
ABC for Authenticator objects.
"""
def encode_params(self, base_url, method, params):
"""Encodes parameters for a request suitable for including in a URL
or POST body. This method may also add new params to the request
if required by the authentication s... | raise NotImplementedError()
| """Generates headers which should be added to the request if required
by the authentication scheme in use."""
raise NotImplementedError()
| 2 | 135 | 14 | 149 | try:
import urllib.parse as urllib_parse
from base64 import encodebytes
except ImportError:
import urllib as urllib_parse
from base64 import encodestring as encodebytes
class Auth(object):
"""
ABC for Authenticator objects.
"""
def encode_params(self, base_url, method, params):
... | try:
import urllib.parse as urllib_parse
from base64 import encodebytes
except ImportError:
import urllib as urllib_parse
from base64 import encodestring as encodebytes
class Auth(object):
"""
ABC for Authenticator objects.
"""
def encode_params(self, base_url, method, params):
... |
39,484 | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter/twitter/auth.py | 57,58 | 47,61 | generate_headers | NoAuth | 58,61 | 58,61 | class NoAuth(Auth):
"""
No authentication authenticator.
"""
def __init__(self):
pass
def encode_params(self, base_url, method, params):
return urllib_parse.urlencode(params)
def generate_headers(self):
FILL_FUNC_BODY | class NoAuth(Auth):
"""
No authentication authenticator.
"""
def __init__(self):
pass
def encode_params(self, base_url, method, params):
return urllib_parse.urlencode(params)
def generate_headers(self):
FILL_FUNC_BODY | return {}
| return {}
| 2 | 83 | 9 | 92 | try:
import urllib.parse as urllib_parse
from base64 import encodebytes
except ImportError:
import urllib as urllib_parse
from base64 import encodestring as encodebytes
class Auth(object):
"""
ABC for Authenticator objects.
"""
def encode_params(self, base_url, method, params):
... | try:
import urllib.parse as urllib_parse
from base64 import encodebytes
except ImportError:
import urllib as urllib_parse
from base64 import encodestring as encodebytes
class Auth(object):
"""
ABC for Authenticator objects.
"""
def encode_params(self, base_url, method, params):
... |
39,485 | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter/twitter/auth.py | 40,41 | 26,47 | generate_headers | UserPassAuth | 41,47 | 41,47 | class UserPassAuth(Auth):
"""
Basic auth authentication using email/username and
password. Deprecated.
"""
def __init__(self, username, password):
self.username = username
self.password = password
def encode_params(self, base_url, method, params):
# We could consider aut... | class UserPassAuth(Auth):
"""
Basic auth authentication using email/username and
password. Deprecated.
"""
def __init__(self, username, password):
self.username = username
self.password = password
def encode_params(self, base_url, method, params):
# We could consider aut... | return {b"Authorization": b"Basic " + encodebytes(
("%s:%s" %(self.username, self.password))
.encode('utf8')).strip(b'\n')
}
| return {b"Authorization": b"Basic " + encodebytes(
("%s:%s" %(self.username, self.password))
.encode('utf8')).strip(b'\n')
}
| 11 | 129 | 62 | 191 | try:
import urllib.parse as urllib_parse
from base64 import encodebytes
except ImportError:
import urllib as urllib_parse
from base64 import encodestring as encodebytes
class Auth(object):
"""
ABC for Authenticator objects.
"""
def encode_params(self, base_url, method, params):
... | try:
import urllib.parse as urllib_parse
from base64 import encodebytes
except ImportError:
import urllib as urllib_parse
from base64 import encodestring as encodebytes
class Auth(object):
"""
ABC for Authenticator objects.
"""
def encode_params(self, base_url, method, params):
... |
39,486 | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter/twitter/logger.py | 70,71 | 1,108 | main | 71,108 | 71,108 | """
twitter-log - Twitter Logger/Archiver
USAGE:
twitter-log <screen_name> [max_id]
DESCRIPTION:
Produce a complete archive in text form of a user's tweets. The
archive format is:
screen_name <tweet_id>
Date: <tweet_time>
[In-Reply-To: a_tweet_id]
Tweet text possibl... | """
twitter-log - Twitter Logger/Archiver
USAGE:
twitter-log <screen_name> [max_id]
DESCRIPTION:
Produce a complete archive in text form of a user's tweets. The
archive format is:
screen_name <tweet_id>
Date: <tweet_time>
[In-Reply-To: a_tweet_id]
Tweet text possibl... | if not args:
print(__doc__)
return 1
if not os.path.exists(OAUTH_FILENAME):
oauth_dance(
"the Python Twitter Logger", CONSUMER_KEY, CONSUMER_SECRET,
OAUTH_FILENAME)
oauth_token, oauth_token_secret = read_token_file(OAUTH_FILENAME)
twitter = Twitter(
... | if not args:
print(__doc__)
return 1
if not os.path.exists(OAUTH_FILENAME):
oauth_dance(
"the Python Twitter Logger", CONSUMER_KEY, CONSUMER_SECRET,
OAUTH_FILENAME)
oauth_token, oauth_token_secret = read_token_file(OAUTH_FILENAME)
twitter = Twitter(
... | 98 | 696 | 410 | 1,106 | """
twitter-log - Twitter Logger/Archiver
USAGE:
twitter-log <screen_name> [max_id]
DESCRIPTION:
Produce a complete archive in text form of a user's tweets. The
archive format is:
screen_name <tweet_id>
Date: <tweet_time>
[In-Reply-To: a_tweet_id]
Tweet text possibl... | """
twitter-log - Twitter Logger/Archiver
USAGE:
twitter-log <screen_name> [max_id]
DESCRIPTION:
Produce a complete archive in text form of a user's tweets. The
archive format is:
screen_name <tweet_id>
Date: <tweet_time>
[In-Reply-To: a_tweet_id]
Tweet text possibl... | |
39,487 | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter/twitter/oauth2.py | 36,37 | 1,94 | write_bearer_token_file | 40,44 | 37,44 | """
Twitter only supports the application-only flow of OAuth2 for certain
API endpoints. This OAuth2 authenticator only supports the application-only
flow right now.
To authenticate with OAuth2, visit the Twitter developer page and create a new
application:
https://dev.twitter.com/apps/new
This will get you a CO... | """
Twitter only supports the application-only flow of OAuth2 for certain
API endpoints. This OAuth2 authenticator only supports the application-only
flow right now.
To authenticate with OAuth2, visit the Twitter developer page and create a new
application:
https://dev.twitter.com/apps/new
This will get you a CO... | oauth_file = open(filename, 'w')
print(oauth2_bearer_token, file=oauth_file)
oauth_file.close()
| """
Write a token file to hold the oauth2 bearer token.
"""
oauth_file = open(filename, 'w')
print(oauth2_bearer_token, file=oauth_file)
oauth_file.close()
| 7 | 819 | 48 | 867 | """
Twitter only supports the application-only flow of OAuth2 for certain
API endpoints. This OAuth2 authenticator only supports the application-only
flow right now.
To authenticate with OAuth2, visit the Twitter developer page and create a new
application:
https://dev.twitter.com/apps/new
This will get you a CO... | """
Twitter only supports the application-only flow of OAuth2 for certain
API endpoints. This OAuth2 authenticator only supports the application-only
flow right now.
To authenticate with OAuth2, visit the Twitter developer page and create a new
application:
https://dev.twitter.com/apps/new
This will get you a CO... | |
39,488 | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter/twitter/oauth2.py | 76,77 | 53,94 | generate_headers | OAuth2 | 77,94 | 77,94 | class OAuth2(Auth):
"""
An OAuth2 application-only authenticator.
"""
def __init__(self, consumer_key=None, consumer_secret=None,
bearer_token=None):
"""
Create an authenticator. You can supply consumer_key and
consumer_secret if you are requesting a bearer_token... | class OAuth2(Auth):
"""
An OAuth2 application-only authenticator.
"""
def __init__(self, consumer_key=None, consumer_secret=None,
bearer_token=None):
"""
Create an authenticator. You can supply consumer_key and
consumer_secret if you are requesting a bearer_token... | if self.bearer_token:
headers = {
'Authorization': 'Bearer {0}'.format(
self.bearer_token).encode('utf8')
}
else:
headers = {
'Content-Type': (b'application/x-www-form-urlencoded;'
b... | if self.bearer_token:
headers = {
'Authorization': 'Bearer {0}'.format(
self.bearer_token).encode('utf8')
}
else:
headers = {
'Content-Type': (b'application/x-www-form-urlencoded;'
b... | 28 | 247 | 187 | 434 | """
Twitter only supports the application-only flow of OAuth2 for certain
API endpoints. This OAuth2 authenticator only supports the application-only
flow right now.
To authenticate with OAuth2, visit the Twitter developer page and create a new
application:
https://dev.twitter.com/apps/new
This will get you a CO... | """
Twitter only supports the application-only flow of OAuth2 for certain
API endpoints. This OAuth2 authenticator only supports the application-only
flow right now.
To authenticate with OAuth2, visit the Twitter developer page and create a new
application:
https://dev.twitter.com/apps/new
This will get you a CO... |
39,489 | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter/twitter/stream_example.py | 15,16 | 1,80 | parse_arguments | 16,38 | 16,38 | """
Example program for the Stream API. This prints public status messages
from the "sample" stream as fast as possible. Use -h for help.
"""
from __future__ import print_function
import argparse
from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup
from twitter.oauth import OAuth
from twitter.... | """
Example program for the Stream API. This prints public status messages
from the "sample" stream as fast as possible. Use -h for help.
"""
from __future__ import print_function
import argparse
from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup
from twitter.oauth import OAuth
from twitter.... |
parser = argparse.ArgumentParser(description=__doc__ or "")
parser.add_argument('-t', '--token', required=True,
help='The Twitter Access Token.')
parser.add_argument('-ts', '--token-secret', required=True,
help='The Twitter Access Token Secret.')
parser... |
parser = argparse.ArgumentParser(description=__doc__ or "")
parser.add_argument('-t', '--token', required=True,
help='The Twitter Access Token.')
parser.add_argument('-ts', '--token-secret', required=True,
help='The Twitter Access Token Secret.')
parser... | 64 | 502 | 318 | 820 | """
Example program for the Stream API. This prints public status messages
from the "sample" stream as fast as possible. Use -h for help.
"""
from __future__ import print_function
import argparse
from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup
from twitter.oauth import OAuth
from twitter.... | """
Example program for the Stream API. This prints public status messages
from the "sample" stream as fast as possible. Use -h for help.
"""
from __future__ import print_function
import argparse
from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup
from twitter.oauth import OAuth
from twitter.... | |
39,490 | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter/twitter/timezones.py | 40,41 | 27,45 | dst | FixedOffset | 41,45 | 41,45 | class FixedOffset(tzinfo):
"""Fixed offset in minutes east from UTC."""
def __init__(self, offset, name):
self.__offset = timedelta(minutes = offset)
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(... | class FixedOffset(tzinfo):
"""Fixed offset in minutes east from UTC."""
def __init__(self, offset, name):
self.__offset = timedelta(minutes = offset)
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(... | return ZERO
# A class capturing the platform's idea of local time.
| return ZERO
# A class capturing the platform's idea of local time.
| 12 | 112 | 27 | 139 | # Retrieved from http://docs.python.org/2/library/datetime.html on 2013-05-24
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
# A UTC class.
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC... | # Retrieved from http://docs.python.org/2/library/datetime.html on 2013-05-24
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
# A UTC class.
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC... |
39,491 | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter/twitter/timezones.py | 72,73 | 55,80 | _isdst | LocalTimezone | 73,80 | 73,80 | class LocalTimezone(tzinfo):
def utcoffset(self, dt):
if self._isdst(dt):
return DSTOFFSET
else:
return STDOFFSET
def dst(self, dt):
if self._isdst(dt):
return DSTDIFF
else:
return ZERO
def tzname(self, dt):
return _t... | class LocalTimezone(tzinfo):
def utcoffset(self, dt):
if self._isdst(dt):
return DSTOFFSET
else:
return STDOFFSET
def dst(self, dt):
if self._isdst(dt):
return DSTDIFF
else:
return ZERO
def tzname(self, dt):
return _t... | tt = (dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
dt.weekday(), 0, 0)
stamp = _time.mktime(tt)
tt = _time.localtime(stamp)
return tt.tm_isdst > 0
| tt = (dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
dt.weekday(), 0, 0)
stamp = _time.mktime(tt)
tt = _time.localtime(stamp)
return tt.tm_isdst > 0
| 21 | 142 | 93 | 235 | # Retrieved from http://docs.python.org/2/library/datetime.html on 2013-05-24
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
# A UTC class.
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC... | # Retrieved from http://docs.python.org/2/library/datetime.html on 2013-05-24
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
# A UTC class.
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC... |
39,492 | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter | /home/hieuvd/dung_repo/raw/stars_02/python-twitter-tools_twitter/twitter/twitter/timezones.py | 15,16 | 9,21 | tzname | UTC | 16,18 | 16,18 | class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
FILL_FUNC_BODY def dst(self, dt):
return ZERO
| class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
FILL_FUNC_BODY def dst(self, dt):
return ZERO
| return "UTC"
| return "UTC"
| 2 | 71 | 10 | 81 | # Retrieved from http://docs.python.org/2/library/datetime.html on 2013-05-24
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
# A UTC class.
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
FILL_FUNC_BODY d... | # Retrieved from http://docs.python.org/2/library/datetime.html on 2013-05-24
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
# A UTC class.
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
FILL_FUNC_BODY d... |
39,494 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/mixtral-moe/model.py | 152,153 | 135,187 | load_hook | Attention | 153,159 | 153,159 | class Attention(nn.Module):
def __init__(self, config: ModelArgs):
super().__init__()
assert config.dim % config.n_head == 0
total_head_dim = (config.n_head + 2 * config.n_local_heads) * config.head_dim
# key, query, value projections for all heads, but in a batch
self.wqkv ... | class Attention(nn.Module):
def __init__(self, config: ModelArgs):
super().__init__()
assert config.dim % config.n_head == 0
total_head_dim = (config.n_head + 2 * config.n_local_heads) * config.head_dim
# key, query, value projections for all heads, but in a batch
self.wqkv ... | if prefix + "wq.weight" in state_dict:
wq = state_dict.pop(prefix + "wq.weight")
wk = state_dict.pop(prefix + "wk.weight")
wv = state_dict.pop(prefix + "wv.weight")
state_dict[prefix + "wqkv.weight"] = torch.cat([wq, wk, wv])
| if prefix + "wq.weight" in state_dict:
wq = state_dict.pop(prefix + "wq.weight")
wk = state_dict.pop(prefix + "wk.weight")
wv = state_dict.pop(prefix + "wv.weight")
state_dict[prefix + "wqkv.weight"] = torch.cat([wq, wk, wv])
| 28 | 725 | 111 | 836 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... |
39,495 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/mixtral-moe/model.py | 194,195 | 187,204 | forward | ConditionalFeedForward | 195,204 | 195,204 | class ConditionalFeedForward(nn.Module):
def __init__(self, config):
super().__init__()
self.w1 = nn.Parameter(torch.empty(config.num_experts, config.intermediate_size, config.dim))
self.w2 = nn.Parameter(torch.empty(config.num_experts, config.dim, config.intermediate_size))
self.w3 ... | class ConditionalFeedForward(nn.Module):
def __init__(self, config):
super().__init__()
self.w1 = nn.Parameter(torch.empty(config.num_experts, config.intermediate_size, config.dim))
self.w2 = nn.Parameter(torch.empty(config.num_experts, config.dim, config.intermediate_size))
self.w3 ... | w1_weights = self.w1[expert_indices] # [T, A, D, D]
w3_weights = self.w3[expert_indices] # [T, A, D, D]
w2_weights = self.w2[expert_indices] # [T, A, D, D]
x1 = F.silu(torch.einsum('ti,taoi -> tao', x, w1_weights))
x3 = torch.einsum('ti, taoi -> tao', x, w3_weights)
expe... | w1_weights = self.w1[expert_indices] # [T, A, D, D]
w3_weights = self.w3[expert_indices] # [T, A, D, D]
w2_weights = self.w2[expert_indices] # [T, A, D, D]
x1 = F.silu(torch.einsum('ti,taoi -> tao', x, w1_weights))
x3 = torch.einsum('ti, taoi -> tao', x, w3_weights)
expe... | 51 | 171 | 204 | 375 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... |
39,496 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/mixtral-moe/model.py | 65,66 | 58,76 | update | KVCache | 66,76 | 66,76 | class KVCache(nn.Module):
def __init__(self, max_batch_size, max_seq_length, n_heads, head_dim, dtype=torch.bfloat16):
super().__init__()
cache_shape = (max_batch_size, n_heads, max_seq_length, head_dim)
self.register_buffer('k_cache', torch.zeros(cache_shape, dtype=dtype))
self.regi... | class KVCache(nn.Module):
def __init__(self, max_batch_size, max_seq_length, n_heads, head_dim, dtype=torch.bfloat16):
super().__init__()
cache_shape = (max_batch_size, n_heads, max_seq_length, head_dim)
self.register_buffer('k_cache', torch.zeros(cache_shape, dtype=dtype))
self.regi... | # input_pos: [S], k_val: [B, H, S, D]
assert input_pos.shape[0] == k_val.shape[2]
k_out = self.k_cache
v_out = self.v_cache
k_out[:, :, input_pos] = k_val
v_out[:, :, input_pos] = v_val
return k_out, v_out
| # input_pos: [S], k_val: [B, H, S, D]
assert input_pos.shape[0] == k_val.shape[2]
k_out = self.k_cache
v_out = self.v_cache
k_out[:, :, input_pos] = k_val
v_out[:, :, input_pos] = v_val
return k_out, v_out
| 31 | 173 | 122 | 295 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... |
39,497 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/mixtral-moe/model.py | 211,212 | 204,223 | forward | MOEFeedForward | 212,223 | 212,223 | class MOEFeedForward(nn.Module):
def __init__(self, config) -> None:
super().__init__()
self.gate = nn.Linear(config.dim, config.num_experts, bias=False)
self.cond_ffn = ConditionalFeedForward(config)
self.dim = config.dim
self.num_activated_experts = config.num_activated_exp... | class MOEFeedForward(nn.Module):
def __init__(self, config) -> None:
super().__init__()
self.gate = nn.Linear(config.dim, config.num_experts, bias=False)
self.cond_ffn = ConditionalFeedForward(config)
self.dim = config.dim
self.num_activated_experts = config.num_activated_exp... | x = x.view(-1, self.dim)
# T = num_tokens, E = num_experts, D = hidden dim, A = activated experts
# x: [T, D]
scores = self.gate(x) # [T, E]
expert_weights = F.softmax(scores, dim=-1)
expert_weights, expert_indices = torch.topk(expert_weights, self.num_activated_experts, ... | x = x.view(-1, self.dim)
# T = num_tokens, E = num_experts, D = hidden dim, A = activated experts
# x: [T, D]
scores = self.gate(x) # [T, E]
expert_weights = F.softmax(scores, dim=-1)
expert_weights, expert_indices = torch.topk(expert_weights, self.num_activated_experts, ... | 61 | 134 | 228 | 362 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... |
39,498 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/mixtral-moe/model.py | 44,46 | 20,54 | from_name | ModelArgs | 46,54 | 46,54 | @dataclass
class ModelArgs:
block_size: int = 2048
vocab_size: int = 32000
n_layer: int = 32
n_head: int = 32
dim: int = 4096
intermediate_size: int = None
n_local_heads: int = -1
head_dim: int = 64
rope_base: float = 10000
norm_eps: float = 1e-5
num_experts: int = 8
num_... | @dataclass
class ModelArgs:
block_size: int = 2048
vocab_size: int = 32000
n_layer: int = 32
n_head: int = 32
dim: int = 4096
intermediate_size: int = None
n_local_heads: int = -1
head_dim: int = 64
rope_base: float = 10000
norm_eps: float = 1e-5
num_experts: int = 8
num_... | if name in transformer_configs:
return cls(**transformer_configs[name])
# fuzzy search
config = [config for config in transformer_configs if config in str(name).upper() or config in str(name)]
assert len(config) == 1, name
return cls(**transformer_configs[config[0]])
... | if name in transformer_configs:
return cls(**transformer_configs[name])
# fuzzy search
config = [config for config in transformer_configs if config in str(name).upper() or config in str(name)]
assert len(config) == 1, name
return cls(**transformer_configs[config[0]])
... | 31 | 297 | 100 | 397 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... |
39,499 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/mixtral-moe/model.py | 229,230 | 223,237 | _norm | RMSNorm | 230,232 | 230,232 | class RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-5):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def _norm(self, x):
FILL_FUNC_BODY def forward(self, x: Tensor) -> Tensor:
output = self._norm(x.float()).type_as(x)
... | class RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-5):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def _norm(self, x):
FILL_FUNC_BODY def forward(self, x: Tensor) -> Tensor:
output = self._norm(x.float()).type_as(x)
... | return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
| return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
| 10 | 132 | 38 | 170 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... |
39,500 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/mixtral-moe/model.py | 91,92 | 76,121 | setup_caches | Transformer | 92,104 | 92,104 | class Transformer(nn.Module):
def __init__(self, config: ModelArgs) -> None:
super().__init__()
self.config = config
self.tok_embeddings = nn.Embedding(config.vocab_size, config.dim)
self.layers = nn.ModuleList(TransformerBlock(config) for _ in range(config.n_layer))
self.no... | class Transformer(nn.Module):
def __init__(self, config: ModelArgs) -> None:
super().__init__()
self.config = config
self.tok_embeddings = nn.Embedding(config.vocab_size, config.dim)
self.layers = nn.ModuleList(TransformerBlock(config) for _ in range(config.n_layer))
self.no... | if self.max_seq_length >= max_seq_length and self.max_batch_size >= max_batch_size:
return
head_dim = self.config.dim // self.config.n_head
max_seq_length = find_multiple(max_seq_length, 8)
self.max_seq_length = max_seq_length
self.max_batch_size = max_batch_size
... | if self.max_seq_length >= max_seq_length and self.max_batch_size >= max_batch_size:
return
head_dim = self.config.dim // self.config.n_head
max_seq_length = find_multiple(max_seq_length, 8)
self.max_seq_length = max_seq_length
self.max_batch_size = max_batch_size
... | 46 | 445 | 267 | 712 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... |
39,501 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/mixtral-moe/model.py | 129,130 | 121,135 | forward | TransformerBlock | 130,135 | 130,135 | class TransformerBlock(nn.Module):
def __init__(self, config: ModelArgs) -> None:
super().__init__()
self.attention = Attention(config)
self.block_sparse_moe = MOEFeedForward(config)
self.ffn_norm = RMSNorm(config.dim, config.norm_eps)
self.attention_norm = RMSNorm(config.dim... | class TransformerBlock(nn.Module):
def __init__(self, config: ModelArgs) -> None:
super().__init__()
self.attention = Attention(config)
self.block_sparse_moe = MOEFeedForward(config)
self.ffn_norm = RMSNorm(config.dim, config.norm_eps)
self.attention_norm = RMSNorm(config.dim... | h = x + self.attention(self.attention_norm(x), freqs_cis, mask, input_pos)
out = h + self.block_sparse_moe(self.ffn_norm(h))
return out
| h = x + self.attention(self.attention_norm(x), freqs_cis, mask, input_pos)
out = h + self.block_sparse_moe(self.ffn_norm(h))
return out
| 15 | 161 | 67 | 228 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... |
39,503 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/mixtral-moe/quantize.py | 135,136 | 121,145 | forward | ConditionalFeedForwardBit8 | 136,145 | 136,145 | class ConditionalFeedForwardBit8(nn.Module):
def __init__(self, num_experts, intermediate_size, dim, target_dtype):
super().__init__()
self.target_dtype = target_dtype
self.register_buffer("w1", torch.empty(num_experts, intermediate_size, dim, dtype=target_dtype))
self.register_buf... | class ConditionalFeedForwardBit8(nn.Module):
def __init__(self, num_experts, intermediate_size, dim, target_dtype):
super().__init__()
self.target_dtype = target_dtype
self.register_buffer("w1", torch.empty(num_experts, intermediate_size, dim, dtype=target_dtype))
self.register_buf... | w1_weights = self.w1.to(x.dtype)[expert_indices] # [T, A, D, D]
w3_weights = self.w3.to(x.dtype)[expert_indices] # [T, A, D, D]
w2_weights = self.w2.to(x.dtype)[expert_indices]
x1 = F.silu(torch.einsum('ti,taoi -> tao', x, w1_weights) * self.scales1[expert_indices].to(x.dtype))
x... | w1_weights = self.w1.to(x.dtype)[expert_indices] # [T, A, D, D]
w3_weights = self.w3.to(x.dtype)[expert_indices] # [T, A, D, D]
w2_weights = self.w2.to(x.dtype)[expert_indices]
x1 = F.silu(torch.einsum('ti,taoi -> tao', x, w1_weights) * self.scales1[expert_indices].to(x.dtype))
x... | 57 | 304 | 285 | 589 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import time
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F
from model import... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import time
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F
from model import... |
39,504 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/mixtral-moe/quantize.py | 117,118 | 101,121 | forward | WeightOnlyBit8Linear | 118,121 | 118,121 | class WeightOnlyBit8Linear(torch.nn.Module):
__constants__ = ['in_features', 'out_features']
in_features: int
out_features: int
weight: torch.Tensor
def __init__(self, in_features: int, out_features: int, bias: bool = True,
device=None, dtype=None, target_dtype=None) -> None:
... | class WeightOnlyBit8Linear(torch.nn.Module):
__constants__ = ['in_features', 'out_features']
in_features: int
out_features: int
weight: torch.Tensor
def __init__(self, in_features: int, out_features: int, bias: bool = True,
device=None, dtype=None, target_dtype=None) -> None:
... | return F.linear(input, self.weight.to(dtype=input.dtype)) * self.scales
| return F.linear(input, self.weight.to(dtype=input.dtype)) * self.scales
| 5 | 259 | 33 | 292 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import time
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F
from model import... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import time
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F
from model import... |
39,505 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/mixtral-moe/quantize.py | 69,71 | 64,101 | create_quantized_state_dict | WeightOnlyBit8QuantHandler | 71,96 | 71,96 | class WeightOnlyBit8QuantHandler:
def __init__(self, mod, target_dtype):
self.mod = mod
self.target_dtype = target_dtype
@torch.no_grad()
def create_quantized_state_dict(self):
FILL_FUNC_BODY def convert_for_runtime(self):
replace_linear_weight_only_bit8_per_channel(self.mod, sel... | class WeightOnlyBit8QuantHandler:
def __init__(self, mod, target_dtype):
self.mod = mod
self.target_dtype = target_dtype
@torch.no_grad()
def create_quantized_state_dict(self):
FILL_FUNC_BODY def convert_for_runtime(self):
replace_linear_weight_only_bit8_per_channel(self.mod, sel... | cur_state_dict = self.mod.state_dict()
for fqn, mod in self.mod.named_modules():
if isinstance(mod, torch.nn.Linear) and not fqn.endswith(".gate"):
int8_weight, scales, _ = dynamically_quantize_per_channel(mod.weight.float(), -128, 127, self.target_dtype)
cur_... | cur_state_dict = self.mod.state_dict()
for fqn, mod in self.mod.named_modules():
if isinstance(mod, torch.nn.Linear) and not fqn.endswith(".gate"):
int8_weight, scales, _ = dynamically_quantize_per_channel(mod.weight.float(), -128, 127, self.target_dtype)
cur_... | 88 | 126 | 484 | 610 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import time
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F
from model import... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import time
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F
from model import... |
39,506 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/mixtral-moe/tp.py | 114,115 | 1,148 | _apply_tp_attn | 115,134 | 115,134 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
from typing import List, Optional
import torch
import torch.distributed as dist
from torch import nn
from torch.... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
from typing import List, Optional
import torch
import torch.distributed as dist
from torch import nn
from torch.... | assert hasattr(attn, "wqkv")
assert hasattr(attn, "wo")
kv_size = attn.n_local_heads * attn.head_dim
_apply_tp_linear(attn.wqkv, "colwise", [attn.dim, kv_size, kv_size])
_apply_tp_linear(attn.wo, "rowwise")
# overwrite
world_size = _get_world_size()
assert attn.n_head % world_size == 0... | assert hasattr(attn, "wqkv")
assert hasattr(attn, "wo")
kv_size = attn.n_local_heads * attn.head_dim
_apply_tp_linear(attn.wqkv, "colwise", [attn.dim, kv_size, kv_size])
_apply_tp_linear(attn.wo, "rowwise")
# overwrite
world_size = _get_world_size()
assert attn.n_head % world_size == 0... | 63 | 1,583 | 303 | 1,886 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
from typing import List, Optional
import torch
import torch.distributed as dist
from torch import nn
from torch.... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
from typing import List, Optional
import torch
import torch.distributed as dist
from torch import nn
from torch.... | |
39,508 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/model.py | 178,179 | 154,206 | forward | Attention | 179,206 | 179,206 | class Attention(nn.Module):
def __init__(self, config: ModelArgs):
super().__init__()
assert config.dim % config.n_head == 0
total_head_dim = (config.n_head + 2 * config.n_local_heads) * config.head_dim
# key, query, value projections for all heads, but in a batch
self.wqkv ... | class Attention(nn.Module):
def __init__(self, config: ModelArgs):
super().__init__()
assert config.dim % config.n_head == 0
total_head_dim = (config.n_head + 2 * config.n_local_heads) * config.head_dim
# key, query, value projections for all heads, but in a batch
self.wqkv ... | bsz, seqlen, _ = x.shape
kv_size = self.n_local_heads * self.head_dim
q, k, v = self.wqkv(x).split([self.dim, kv_size, kv_size], dim=-1)
q = q.view(bsz, seqlen, self.n_head, self.head_dim)
k = k.view(bsz, seqlen, self.n_local_heads, self.head_dim)
v = v.view(bsz, seqlen... | bsz, seqlen, _ = x.shape
kv_size = self.n_local_heads * self.head_dim
q, k, v = self.wqkv(x).split([self.dim, kv_size, kv_size], dim=-1)
q = q.view(bsz, seqlen, self.n_head, self.head_dim)
k = k.view(bsz, seqlen, self.n_local_heads, self.head_dim)
v = v.view(bsz, seqlen... | 96 | 411 | 446 | 857 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... |
39,509 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/model.py | 213,214 | 206,217 | forward | FeedForward | 214,217 | 214,217 | class FeedForward(nn.Module):
def __init__(self, config: ModelArgs) -> None:
super().__init__()
self.w1 = nn.Linear(config.dim, config.intermediate_size, bias=False)
self.w3 = nn.Linear(config.dim, config.intermediate_size, bias=False)
self.w2 = nn.Linear(config.intermediate_size, co... | class FeedForward(nn.Module):
def __init__(self, config: ModelArgs) -> None:
super().__init__()
self.w1 = nn.Linear(config.dim, config.intermediate_size, bias=False)
self.w3 = nn.Linear(config.dim, config.intermediate_size, bias=False)
self.w2 = nn.Linear(config.intermediate_size, co... | return self.w2(F.silu(self.w1(x)) * self.w3(x))
| return self.w2(F.silu(self.w1(x)) * self.w3(x))
| 4 | 144 | 33 | 177 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... |
39,510 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/model.py | 78,79 | 71,89 | update | KVCache | 79,89 | 79,89 | class KVCache(nn.Module):
def __init__(self, max_batch_size, max_seq_length, n_heads, head_dim, dtype=torch.bfloat16):
super().__init__()
cache_shape = (max_batch_size, n_heads, max_seq_length, head_dim)
self.register_buffer('k_cache', torch.zeros(cache_shape, dtype=dtype))
self.regi... | class KVCache(nn.Module):
def __init__(self, max_batch_size, max_seq_length, n_heads, head_dim, dtype=torch.bfloat16):
super().__init__()
cache_shape = (max_batch_size, n_heads, max_seq_length, head_dim)
self.register_buffer('k_cache', torch.zeros(cache_shape, dtype=dtype))
self.regi... | # input_pos: [S], k_val: [B, H, S, D]
assert input_pos.shape[0] == k_val.shape[2]
k_out = self.k_cache
v_out = self.v_cache
k_out[:, :, input_pos] = k_val
v_out[:, :, input_pos] = v_val
return k_out, v_out
| # input_pos: [S], k_val: [B, H, S, D]
assert input_pos.shape[0] == k_val.shape[2]
k_out = self.k_cache
v_out = self.v_cache
k_out[:, :, input_pos] = k_val
v_out[:, :, input_pos] = v_val
return k_out, v_out
| 31 | 173 | 122 | 295 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... |
39,511 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/model.py | 42,44 | 20,58 | from_name | ModelArgs | 44,58 | 44,58 | @dataclass
class ModelArgs:
block_size: int = 2048
vocab_size: int = 32000
n_layer: int = 32
n_head: int = 32
dim: int = 4096
intermediate_size: int = None
n_local_heads: int = -1
head_dim: int = 64
rope_base: float = 10000
norm_eps: float = 1e-5
def __post_init__(self):
... | @dataclass
class ModelArgs:
block_size: int = 2048
vocab_size: int = 32000
n_layer: int = 32
n_head: int = 32
dim: int = 4096
intermediate_size: int = None
n_local_heads: int = -1
head_dim: int = 64
rope_base: float = 10000
norm_eps: float = 1e-5
def __post_init__(self):
... | if name in transformer_configs:
return cls(**transformer_configs[name])
# fuzzy search
config = [config for config in transformer_configs if config in str(name).upper() or config in str(name)]
# We may have two or more configs matched (e.g. "7B" and "Mistral-7B"). Find the b... | if name in transformer_configs:
return cls(**transformer_configs[name])
# fuzzy search
config = [config for config in transformer_configs if config in str(name).upper() or config in str(name)]
# We may have two or more configs matched (e.g. "7B" and "Mistral-7B"). Find the b... | 72 | 274 | 199 | 473 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... |
39,512 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/model.py | 223,224 | 217,231 | _norm | RMSNorm | 224,226 | 224,226 | class RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-5):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def _norm(self, x):
FILL_FUNC_BODY def forward(self, x: Tensor) -> Tensor:
output = self._norm(x.float()).type_as(x)
... | class RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-5):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def _norm(self, x):
FILL_FUNC_BODY def forward(self, x: Tensor) -> Tensor:
output = self._norm(x.float()).type_as(x)
... | return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
| return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
| 10 | 132 | 38 | 170 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... |
39,513 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/model.py | 123,124 | 89,140 | forward | Transformer | 124,135 | 124,135 | class Transformer(nn.Module):
def __init__(self, config: ModelArgs) -> None:
super().__init__()
self.config = config
self.tok_embeddings = nn.Embedding(config.vocab_size, config.dim)
self.layers = nn.ModuleList(TransformerBlock(config) for _ in range(config.n_layer))
self.no... | class Transformer(nn.Module):
def __init__(self, config: ModelArgs) -> None:
super().__init__()
self.config = config
self.tok_embeddings = nn.Embedding(config.vocab_size, config.dim)
self.layers = nn.ModuleList(TransformerBlock(config) for _ in range(config.n_layer))
self.no... | assert self.freqs_cis is not None, "Caches must be initialized first"
mask = self.causal_mask[None, None, input_pos]
freqs_cis = self.freqs_cis[input_pos]
x = self.tok_embeddings(idx)
for i, layer in enumerate(self.layers):
x = layer(x, input_pos, freqs_cis, mask)
... | assert self.freqs_cis is not None, "Caches must be initialized first"
mask = self.causal_mask[None, None, input_pos]
freqs_cis = self.freqs_cis[input_pos]
x = self.tok_embeddings(idx)
for i, layer in enumerate(self.layers):
x = layer(x, input_pos, freqs_cis, mask)
... | 40 | 660 | 152 | 812 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... |
39,514 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/model.py | 148,149 | 140,154 | forward | TransformerBlock | 149,154 | 149,154 | class TransformerBlock(nn.Module):
def __init__(self, config: ModelArgs) -> None:
super().__init__()
self.attention = Attention(config)
self.feed_forward = FeedForward(config)
self.ffn_norm = RMSNorm(config.dim, config.norm_eps)
self.attention_norm = RMSNorm(config.dim, confi... | class TransformerBlock(nn.Module):
def __init__(self, config: ModelArgs) -> None:
super().__init__()
self.attention = Attention(config)
self.feed_forward = FeedForward(config)
self.ffn_norm = RMSNorm(config.dim, config.norm_eps)
self.attention_norm = RMSNorm(config.dim, confi... | h = x + self.attention(self.attention_norm(x), freqs_cis, mask, input_pos)
out = h + self.feed_forward(self.ffn_norm(h))
return out
| h = x + self.attention(self.attention_norm(x), freqs_cis, mask, input_pos)
out = h + self.feed_forward(self.ffn_norm(h))
return out
| 15 | 155 | 63 | 218 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
... |
39,516 | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast | /home/hieuvd/dung_repo/raw/stars_02/pytorch-labs_gpt-fast/gpt-fast/tp.py | 54,55 | 1,157 | _apply_tp_linear | 55,110 | 55,110 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
from typing import List, Optional
import torch
import torch.distributed as dist
from torch import nn
if os.uname... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
from typing import List, Optional
import torch
import torch.distributed as dist
from torch import nn
if os.uname... | rank = _get_rank()
world_size = _get_world_size()
# Linear's weight matrix is transposed, and is of shape
# (linear.out_features, linear.in_features)
dim_lookup = {
"colwise": (0, "out_features"),
"rowwise": (1, "in_features")
}
assert style in dim_lookup
shard_dim, size... | rank = _get_rank()
world_size = _get_world_size()
# Linear's weight matrix is transposed, and is of shape
# (linear.out_features, linear.in_features)
dim_lookup = {
"colwise": (0, "out_features"),
"rowwise": (1, "in_features")
}
assert style in dim_lookup
shard_dim, size... | 205 | 1,122 | 839 | 1,961 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
from typing import List, Optional
import torch
import torch.distributed as dist
from torch import nn
if os.uname... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
from typing import List, Optional
import torch
import torch.distributed as dist
from torch import nn
if os.uname... | |
39,517 | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/demos/bokeh_app.py | 35,36 | 1,62 | main | 36,60 | 36,60 | from bokeh.io import output_notebook
from bokeh.io import show
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, Slider
from bokeh.plotting import figure
from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature
from pywebio import start_server
from pywebio.output import *
... | from bokeh.io import output_notebook
from bokeh.io import show
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, Slider
from bokeh.plotting import figure
from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature
from pywebio import start_server
from pywebio.output import *
... | output_notebook(verbose=False, notebook_type='pywebio')
if 'zh' in session_info.user_language:
put_markdown("""# Bokeh Applications in PyWebIO
[Bokeh Applications](https://docs.bokeh.org/en/latest/docs/user_guide/server.html) 支持向图表的添加按钮、输入框等交互组件,并向组件添加Python回调,从而创建可以与Python代码交互的可视化图表。
... | output_notebook(verbose=False, notebook_type='pywebio')
if 'zh' in session_info.user_language:
put_markdown("""# Bokeh Applications in PyWebIO
[Bokeh Applications](https://docs.bokeh.org/en/latest/docs/user_guide/server.html) 支持向图表的添加按钮、输入框等交互组件,并向组件添加Python回调,从而创建可以与Python代码交互的可视化图表。
... | 114 | 412 | 473 | 885 | from bokeh.io import output_notebook
from bokeh.io import show
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, Slider
from bokeh.plotting import figure
from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature
from pywebio import start_server
from pywebio.output import *
... | from bokeh.io import output_notebook
from bokeh.io import show
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, Slider
from bokeh.plotting import figure
from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature
from pywebio import start_server
from pywebio.output import *
... | |
39,518 | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/demos/chat_room.py | 36,37 | 1,77 | main | 41,75 | 37,75 | import asyncio
from pywebio import start_server
from pywebio.input import *
from pywebio.output import *
from pywebio.session import defer_call, info as session_info, run_async
MAX_MESSAGES_CNT = 10 ** 4
chat_msgs = [] # The chat message history. The item is (name, message content)
online_users = set()
def t(eng,... | import asyncio
from pywebio import start_server
from pywebio.input import *
from pywebio.output import *
from pywebio.session import defer_call, info as session_info, run_async
MAX_MESSAGES_CNT = 10 ** 4
chat_msgs = [] # The chat message history. The item is (name, message content)
online_users = set()
def t(eng,... | global chat_msgs
put_markdown(t("## PyWebIO chat room\nWelcome to the chat room, you can chat with all the people currently online. You can open this page in multiple tabs of your browser to simulate a multi-user environment. This application uses less than 90 lines of code, the source code is [here](https://g... | """PyWebIO chat room
You can chat with everyone currently online.
"""
global chat_msgs
put_markdown(t("## PyWebIO chat room\nWelcome to the chat room, you can chat with all the people currently online. You can open this page in multiple tabs of your browser to simulate a multi-user environment. Th... | 213 | 415 | 831 | 1,246 | import asyncio
from pywebio import start_server
from pywebio.input import *
from pywebio.output import *
from pywebio.session import defer_call, info as session_info, run_async
MAX_MESSAGES_CNT = 10 ** 4
chat_msgs = [] # The chat message history. The item is (name, message content)
online_users = set()
def t(eng,... | import asyncio
from pywebio import start_server
from pywebio.input import *
from pywebio.output import *
from pywebio.session import defer_call, info as session_info, run_async
MAX_MESSAGES_CNT = 10 ** 4
chat_msgs = [] # The chat message history. The item is (name, message content)
online_users = set()
def t(eng,... | |
39,519 | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/demos/doc_demo.py | 130,131 | 1,153 | get_app | 135,150 | 131,150 | """
Run the example code in the documentation online
"""
import base64
from functools import partial
from os import path, listdir
from pywebio import start_server
from pywebio.platform import config
from pywebio.session import local as session_local, info as session_info
import pywebio_battery
#######################... | """
Run the example code in the documentation online
"""
import base64
from functools import partial
from os import path, listdir
from pywebio import start_server
from pywebio.platform import config
from pywebio.session import local as session_local, info as session_info
import pywebio_battery
#######################... | app = {}
try:
demos = listdir(path.join(here_dir, 'doc_demos'))
except Exception:
demos = []
for name in demos:
code = open(path.join(here_dir, 'doc_demos', name)).read()
title, code = code.split('\n\n', 1)
app[name] = partial(handle_code, code=code, title=title)... | """PyWebIO demos from document
Run the demos from the document online.
"""
app = {}
try:
demos = listdir(path.join(here_dir, 'doc_demos'))
except Exception:
demos = []
for name in demos:
code = open(path.join(here_dir, 'doc_demos', name)).read()
title, code ... | 38 | 1,228 | 157 | 1,385 | """
Run the example code in the documentation online
"""
import base64
from functools import partial
from os import path, listdir
from pywebio import start_server
from pywebio.platform import config
from pywebio.session import local as session_local, info as session_info
import pywebio_battery
#######################... | """
Run the example code in the documentation online
"""
import base64
from functools import partial
from os import path, listdir
from pywebio import start_server
from pywebio.platform import config
from pywebio.session import local as session_local, info as session_info
import pywebio_battery
#######################... | |
39,520 | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/demos/gomoku_game.py | 14,15 | 1,95 | winner | 15,27 | 15,27 | import time
from pywebio import session, start_server
from pywebio.output import *
goboard_size = 15
# -1 -> none, 0 -> black, 1 -> white
goboard = [
[-1] * goboard_size
for _ in range(goboard_size)
]
def winner(): # return winner piece, return None if no winner
FILL_FUNC_BODYsession_id = 0 # auto... | import time
from pywebio import session, start_server
from pywebio.output import *
goboard_size = 15
# -1 -> none, 0 -> black, 1 -> white
goboard = [
[-1] * goboard_size
for _ in range(goboard_size)
]
def winner(): # return winner piece, return None if no winner
FILL_FUNC_BODYsession_id = 0 # auto... | for x in range(2, goboard_size - 2):
for y in range(2, goboard_size - 2):
# check if (x,y) is the win center
if goboard[x][y] != -1 and any([
all(goboard[x][y] == goboard[m][n] for m, n in [(x - 2, y), (x - 1, y), (x + 1, y), (x + 2, y)]),
all(goboard[... | for x in range(2, goboard_size - 2):
for y in range(2, goboard_size - 2):
# check if (x,y) is the win center
if goboard[x][y] != -1 and any([
all(goboard[x][y] == goboard[m][n] for m, n in [(x - 2, y), (x - 1, y), (x + 1, y), (x + 2, y)]),
all(goboard[... | 140 | 1,036 | 353 | 1,389 | import time
from pywebio import session, start_server
from pywebio.output import *
goboard_size = 15
# -1 -> none, 0 -> black, 1 -> white
goboard = [
[-1] * goboard_size
for _ in range(goboard_size)
]
def winner(): # return winner piece, return None if no winner
FILL_FUNC_BODYsession_id = 0 # auto... | import time
from pywebio import session, start_server
from pywebio.output import *
goboard_size = 15
# -1 -> none, 0 -> black, 1 -> white
goboard = [
[-1] * goboard_size
for _ in range(goboard_size)
]
def winner(): # return winner piece, return None if no winner
FILL_FUNC_BODYsession_id = 0 # auto... | |
39,522 | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/demos/set_env_demo.py | 14,15 | 1,59 | main | 16,57 | 15,57 | from pywebio import start_server
from pywebio.input import *
from pywebio.output import *
from pywebio.session import *
import datetime
import asyncio
def t(eng, chinese):
"""return English or Chinese text according to the user's browser language"""
return chinese if 'zh' in info.user_language else eng
asyn... | from pywebio import start_server
from pywebio.input import *
from pywebio.output import *
from pywebio.session import *
import datetime
import asyncio
def t(eng, chinese):
"""return English or Chinese text according to the user's browser language"""
return chinese if 'zh' in info.user_language else eng
asyn... |
set_scope('time')
put_markdown(t('> Can be used to observe the animation effect of the `output_animation` setting',
'> 可用于观察 `output_animation` 项的动画效果'))
put_markdown('---')
async def bg_task():
while 1:
with use_scope('time', clear=True):
put_tex... | """`pywebio.session.set_env()` demo"""
set_scope('time')
put_markdown(t('> Can be used to observe the animation effect of the `output_animation` setting',
'> 可用于观察 `output_animation` 项的动画效果'))
put_markdown('---')
async def bg_task():
while 1:
with use_scope('... | 141 | 153 | 547 | 700 | from pywebio import start_server
from pywebio.input import *
from pywebio.output import *
from pywebio.session import *
import datetime
import asyncio
def t(eng, chinese):
"""return English or Chinese text according to the user's browser language"""
return chinese if 'zh' in info.user_language else eng
asyn... | from pywebio import start_server
from pywebio.input import *
from pywebio.output import *
from pywebio.session import *
import datetime
import asyncio
def t(eng, chinese):
"""return English or Chinese text according to the user's browser language"""
return chinese if 'zh' in info.user_language else eng
asyn... | |
39,524 | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/demos/wordle.py | 28,29 | 1,111 | on_key_press | 29,83 | 29,83 | import time
from pywebio import start_server, config
from pywebio.output import *
from pywebio.session import run_js, local as session_local
TODAY_WORD = 'PYWEBIO' # need to be uppercase
MAX_TRY = 6
WORD_LEN = len(TODAY_WORD)
CSS = """
.pywebio {padding-top: 0} .markdown-body table {display:table; width:250px; mar... | import time
from pywebio import start_server, config
from pywebio.output import *
from pywebio.session import run_js, local as session_local
TODAY_WORD = 'PYWEBIO' # need to be uppercase
MAX_TRY = 6
WORD_LEN = len(TODAY_WORD)
CSS = """
.pywebio {padding-top: 0} .markdown-body table {display:table; width:250px; mar... | if session_local.curr_row >= MAX_TRY or session_local.game_pass:
return
if char == '◀':
session_local.curr_word = session_local.curr_word[:-1]
return clear(f's-{session_local.curr_row}-{len(session_local.curr_word)}')
# show the char in grid
with use_scope(f's-{session_local.cu... | if session_local.curr_row >= MAX_TRY or session_local.game_pass:
return
if char == '◀':
session_local.curr_word = session_local.curr_word[:-1]
return clear(f's-{session_local.curr_row}-{len(session_local.curr_word)}')
# show the char in grid
with use_scope(f's-{session_local.cu... | 154 | 746 | 915 | 1,661 | import time
from pywebio import start_server, config
from pywebio.output import *
from pywebio.session import run_js, local as session_local
TODAY_WORD = 'PYWEBIO' # need to be uppercase
MAX_TRY = 6
WORD_LEN = len(TODAY_WORD)
CSS = """
.pywebio {padding-top: 0} .markdown-body table {display:table; width:250px; mar... | import time
from pywebio import start_server, config
from pywebio.output import *
from pywebio.session import run_js, local as session_local
TODAY_WORD = 'PYWEBIO' # need to be uppercase
MAX_TRY = 6
WORD_LEN = len(TODAY_WORD)
CSS = """
.pywebio {padding-top: 0} .markdown-body table {display:table; width:250px; mar... | |
39,525 | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/docs/_ext/codeblock.py | 75,76 | 1,84 | setup | 76,84 | 76,84 | import os
from docutils.parsers.rst import directives
from sphinx.directives.code import CodeBlock
import hashlib
class ExportableCodeBlock(CodeBlock):
option_spec = {
'summary': directives.unchanged,
'name': directives.unchanged,
}
names = set()
@staticmethod
def md5(str_data):... | import os
from docutils.parsers.rst import directives
from sphinx.directives.code import CodeBlock
import hashlib
class ExportableCodeBlock(CodeBlock):
option_spec = {
'summary': directives.unchanged,
'name': directives.unchanged,
}
names = set()
@staticmethod
def md5(str_data):... | app.add_directive("exportable-codeblock", ExportableCodeBlock)
app.add_js_file('pywebio.js')
return {
'version': '0.1',
'parallel_read_safe': True,
'parallel_write_safe': True,
}
| app.add_directive("exportable-codeblock", ExportableCodeBlock)
app.add_js_file('pywebio.js')
return {
'version': '0.1',
'parallel_read_safe': True,
'parallel_write_safe': True,
}
| 12 | 699 | 85 | 784 | import os
from docutils.parsers.rst import directives
from sphinx.directives.code import CodeBlock
import hashlib
class ExportableCodeBlock(CodeBlock):
option_spec = {
'summary': directives.unchanged,
'name': directives.unchanged,
}
names = set()
@staticmethod
def md5(str_data):... | import os
from docutils.parsers.rst import directives
from sphinx.directives.code import CodeBlock
import hashlib
class ExportableCodeBlock(CodeBlock):
option_spec = {
'summary': directives.unchanged,
'name': directives.unchanged,
}
names = set()
@staticmethod
def md5(str_data):... | |
39,526 | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/docs/_ext/codeblock.py | 22,23 | 8,75 | run | ExportableCodeBlock | 23,75 | 23,75 | class ExportableCodeBlock(CodeBlock):
option_spec = {
'summary': directives.unchanged,
'name': directives.unchanged,
}
names = set()
@staticmethod
def md5(str_data):
t = hashlib.md5()
t.update(str_data.encode('utf-8'))
return t.hexdigest()
def run(self)... | class ExportableCodeBlock(CodeBlock):
option_spec = {
'summary': directives.unchanged,
'name': directives.unchanged,
}
names = set()
@staticmethod
def md5(str_data):
t = hashlib.md5()
t.update(str_data.encode('utf-8'))
return t.hexdigest()
def run(self)... | if self.env.app.builder.name == 'gettext':
return super().run()
code_save_path = os.environ.get('CODE_EXPORT_PATH')
caption = self.options.get('summary', '')
if code_save_path and not os.path.exists(code_save_path):
os.mkdir(code_save_path)
code_id = se... | if self.env.app.builder.name == 'gettext':
return super().run()
code_save_path = os.environ.get('CODE_EXPORT_PATH')
caption = self.options.get('summary', '')
if code_save_path and not os.path.exists(code_save_path):
os.mkdir(code_save_path)
code_id = se... | 124 | 119 | 589 | 708 | import os
from docutils.parsers.rst import directives
from sphinx.directives.code import CodeBlock
import hashlib
class ExportableCodeBlock(CodeBlock):
option_spec = {
'summary': directives.unchanged,
'name': directives.unchanged,
}
names = set()
@staticmethod
def md5(str_data):... | import os
from docutils.parsers.rst import directives
from sphinx.directives.code import CodeBlock
import hashlib
class ExportableCodeBlock(CodeBlock):
option_spec = {
'summary': directives.unchanged,
'name': directives.unchanged,
}
names = set()
@staticmethod
def md5(str_data):... |
39,527 | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/docs/conf.py | 77,78 | 1,100 | setup | 79,85 | 78,85 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# Ensur... | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# Ensur... | app.add_css_file('pywebio.css')
# from docutils.parsers.rst.directives.admonitions import Note
# app.add_directive('collapse', Note)
# -- Extension configuration -------------------------------------------------
| """Configure Sphinx"""
app.add_css_file('pywebio.css')
# from docutils.parsers.rst.directives.admonitions import Note
# app.add_directive('collapse', Note)
# -- Extension configuration -------------------------------------------------
| 14 | 888 | 68 | 956 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# Ensur... | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# Ensur... | |
39,530 | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/pin.py | 271,272 | 268,301 | use_strict | Pin_ | 276,278 | 272,278 | class Pin_:
_strict = False
def use_strict(self):
FILL_FUNC_BODY def __getattr__(self, name: str):
"""__getattr__ is only invoked if the attribute wasn't found the usual ways"""
if name.startswith('__'):
raise AttributeError('Pin object has no attribute %r' % name)
return... | class Pin_:
_strict = False
def use_strict(self):
"""
Enable strict mode for getting pin widget value.
An AssertionError will be raised when try to get value of pin widgets that are currently not in the page.
"""
FILL_FUNC_BODY def __getattr__(self, name: str):
"""__g... | object.__setattr__(self, '_strict', True)
| """
Enable strict mode for getting pin widget value.
An AssertionError will be raised when try to get value of pin widgets that are currently not in the page.
"""
object.__setattr__(self, '_strict', True)
| 3 | 349 | 17 | 366 | """
``pywebio.pin`` --- Persistent input
===========================================================================
*pin == Persistent input == Pinning input widget to the page*
Overview
------------------
As you already know, the input function of PyWebIO is blocking
and the input form will be destroyed after succ... | """
``pywebio.pin`` --- Persistent input
===========================================================================
*pin == Persistent input == Pinning input widget to the page*
Overview
------------------
As you already know, the input function of PyWebIO is blocking
and the input form will be destroyed after succ... |
39,532 | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/adaptor/http.py | 54,55 | 27,92 | request_body | HttpContext | 60,62 | 55,62 | class HttpContext:
"""一次Http请求的上下文, 不同的后端框架需要根据框架提供的方法实现本类的方法
The context of an Http request"""
backend_name = '' # 当前使用的Web框架名
def request_obj(self):
"""返回当前请求对象
Return the current request object"""
pass
def request_method(self) -> str:
"""返回当前请求的方法,大写
R... | class HttpContext:
"""一次Http请求的上下文, 不同的后端框架需要根据框架提供的方法实现本类的方法
The context of an Http request"""
backend_name = '' # 当前使用的Web框架名
def request_obj(self):
"""返回当前请求对象
Return the current request object"""
pass
def request_method(self) -> str:
"""返回当前请求的方法,大写
R... | return b''
| """返回当前请求的body数据
Returns the data of the current request body
:return: bytes/bytearray
"""
return b''
| 2 | 520 | 8 | 528 | """
本模块提供基于Http轮训的后端通用类和函数
.. attention::
PyWebIO 的会话状态保存在进程内,基于HTTP的会话不支持多进程部署的后端服务
比如使用 ``uWSGI`` 部署后端服务,并使用 ``--processes n`` 选项设置了多进程;
或者使用 ``nginx`` 等反向代理将流量负载到多个后端副本上。
"""
import asyncio
import fnmatch
import json
import logging
import threading
import time
from contextlib import contextmanager
from... | """
本模块提供基于Http轮训的后端通用类和函数
.. attention::
PyWebIO 的会话状态保存在进程内,基于HTTP的会话不支持多进程部署的后端服务
比如使用 ``uWSGI`` 部署后端服务,并使用 ``--processes n`` 选项设置了多进程;
或者使用 ``nginx`` 等反向代理将流量负载到多个后端副本上。
"""
import asyncio
import fnmatch
import json
import logging
import threading
import time
from contextlib import contextmanager
from... |
39,534 | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/adaptor/http.py | 125,126 | 96,147 | get_response | ReliableTransport | 130,147 | 126,147 | class ReliableTransport:
def __init__(self, session: Session, message_window: int = 4):
self.session = session
self.messages = deque()
self.window_size = message_window
self.min_msg_id = 0 # the id of the first message in the window
self.finished_event_id = -1 # the id of t... | class ReliableTransport:
def __init__(self, session: Session, message_window: int = 4):
self.session = session
self.messages = deque()
self.window_size = message_window
self.min_msg_id = 0 # the id of the first message in the window
self.finished_event_id = -1 # the id of t... | while ack >= self.min_msg_id and self.messages:
self.messages.popleft()
self.min_msg_id += 1
if len(self.messages) < self.window_size:
msgs = self.session.get_task_commands()
if msgs:
self.messages.append(msgs)
return dict(
... | """
ack num is the number of messages that the client has received.
response is a list of messages that the client should receive, along with their min id `seq`.
"""
while ack >= self.min_msg_id and self.messages:
self.messages.popleft()
self.min_msg_id +=... | 35 | 359 | 163 | 522 | """
本模块提供基于Http轮训的后端通用类和函数
.. attention::
PyWebIO 的会话状态保存在进程内,基于HTTP的会话不支持多进程部署的后端服务
比如使用 ``uWSGI`` 部署后端服务,并使用 ``--processes n`` 选项设置了多进程;
或者使用 ``nginx`` 等反向代理将流量负载到多个后端副本上。
"""
import asyncio
import fnmatch
import json
import logging
import threading
import time
from contextlib import contextmanager
from... | """
本模块提供基于Http轮训的后端通用类和函数
.. attention::
PyWebIO 的会话状态保存在进程内,基于HTTP的会话不支持多进程部署的后端服务
比如使用 ``uWSGI`` 部署后端服务,并使用 ``--processes n`` 选项设置了多进程;
或者使用 ``nginx`` 等反向代理将流量负载到多个后端副本上。
"""
import asyncio
import fnmatch
import json
import logging
import threading
import time
from contextlib import contextmanager
from... |
39,536 | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/adaptor/ws.py | 90,92 | 77,99 | closed | WebSocketConnection | 92,94 | 92,94 | class WebSocketConnection(abc.ABC):
@abc.abstractmethod
def get_query_argument(self, name) -> typing.Optional[str]:
pass
@abc.abstractmethod
def make_session_info(self) -> dict:
pass
@abc.abstractmethod
def write_message(self, message: dict):
pass
@abc.abstractmeth... | class WebSocketConnection(abc.ABC):
@abc.abstractmethod
def get_query_argument(self, name) -> typing.Optional[str]:
pass
@abc.abstractmethod
def make_session_info(self) -> dict:
pass
@abc.abstractmethod
def write_message(self, message: dict):
pass
@abc.abstractmeth... | return False
| return False
| 2 | 145 | 7 | 152 | import abc
import asyncio
import json
import logging
import time
import typing
from typing import Dict, Optional
from ...session import CoroutineBasedSession, Session, ThreadBasedSession
from ...utils import LRUDict, iscoroutinefunction, isgeneratorfunction, random_str
from ..utils import deserialize_binary_event
log... | import abc
import asyncio
import json
import logging
import time
import typing
from typing import Dict, Optional
from ...session import CoroutineBasedSession, Session, ThreadBasedSession
from ...utils import LRUDict, iscoroutinefunction, isgeneratorfunction, random_str
from ..utils import deserialize_binary_event
log... |
39,537 | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/adaptor/ws.py | 141,142 | 99,214 | _init_session | WebSocketHandler | 142,157 | 142,157 | class WebSocketHandler:
"""
hold by one connection,
share one session with multiple connection in session lifetime, but one conn at a time
"""
session_id: Optional[str] = None
session: Optional[Session] = None # the session that current connection attaches
connection: WebSocketConnection
... | class WebSocketHandler:
"""
hold by one connection,
share one session with multiple connection in session lifetime, but one conn at a time
"""
session_id: Optional[str] = None
session: Optional[Session] = None # the session that current connection attaches
connection: WebSocketConnection
... | session_info = self.connection.make_session_info()
self.session_id = random_str(24)
if iscoroutinefunction(application) or isgeneratorfunction(application):
self.session = CoroutineBasedSession(
application, session_info=session_info,
on_task_command=... | session_info = self.connection.make_session_info()
self.session_id = random_str(24)
if iscoroutinefunction(application) or isgeneratorfunction(application):
self.session = CoroutineBasedSession(
application, session_info=session_info,
on_task_command=... | 26 | 1,221 | 194 | 1,415 | import abc
import asyncio
import json
import logging
import time
import typing
from typing import Dict, Optional
from ...session import CoroutineBasedSession, Session, ThreadBasedSession
from ...utils import LRUDict, iscoroutinefunction, isgeneratorfunction, random_str
from ..utils import deserialize_binary_event
log... | import abc
import asyncio
import json
import logging
import time
import typing
from typing import Dict, Optional
from ...session import CoroutineBasedSession, Session, ThreadBasedSession
from ...utils import LRUDict, iscoroutinefunction, isgeneratorfunction, random_str
from ..utils import deserialize_binary_event
log... |
39,539 | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/aiohttp.py | 55,56 | 45,74 | make_session_info | WebSocketConnection | 56,63 | 56,63 | class WebSocketConnection(ws_adaptor.WebSocketConnection):
def __init__(self, ws: web.WebSocketResponse, http: web.Request, ioloop):
self.ws = ws
self.http = http
self.ioloop = ioloop
def get_query_argument(self, name) -> typing.Optional[str]:
return self.http.query.getone(name... | class WebSocketConnection(ws_adaptor.WebSocketConnection):
def __init__(self, ws: web.WebSocketResponse, http: web.Request, ioloop):
self.ws = ws
self.http = http
self.ioloop = ioloop
def get_query_argument(self, name) -> typing.Optional[str]:
return self.http.query.getone(name... | session_info = get_session_info_from_headers(self.http.headers)
session_info['user_ip'] = self.http.remote
session_info['request'] = self.http
session_info['backend'] = 'aiohttp'
session_info['protocol'] = 'websocket'
return session_info
| session_info = get_session_info_from_headers(self.http.headers)
session_info['user_ip'] = self.http.remote
session_info['request'] = self.http
session_info['backend'] = 'aiohttp'
session_info['protocol'] = 'websocket'
return session_info
| 17 | 231 | 93 | 324 | import asyncio
import fnmatch
import json
import logging
import os
import typing
from functools import partial
from urllib.parse import urlparse
from aiohttp import web
from . import page
from .adaptor import ws as ws_adaptor
from .page import make_applications, render_page
from .remote_access import start_remote_acc... | import asyncio
import fnmatch
import json
import logging
import os
import typing
from functools import partial
from urllib.parse import urlparse
from aiohttp import web
from . import page
from .adaptor import ws as ws_adaptor
from .page import make_applications, render_page
from .remote_access import start_remote_acc... |
39,540 | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/bokeh.py | 158,159 | 1,167 | try_install_bokeh_hook | 160,167 | 159,167 | import asyncio
import re
from collections.abc import Sequence
from pywebio.output import *
from pywebio.session import get_info
requirejs_config_tpl = """
<script type="text/javascript">
require.config({
paths: {
"bokeh": "https://cdn.bokeh.org/bokeh/release/bokeh-__version__.min",
"bokeh-widgets"... | import asyncio
import re
from collections.abc import Sequence
from pywebio.output import *
from pywebio.session import get_info
requirejs_config_tpl = """
<script type="text/javascript">
require.config({
paths: {
"bokeh": "https://cdn.bokeh.org/bokeh/release/bokeh-__version__.min",
"bokeh-widgets"... | try:
from bokeh.io import install_notebook_hook
except ImportError:
return False
install_notebook_hook('pywebio', load_notebook, show_doc, show_app)
return True
| """尝试安装bokeh支持"""
try:
from bokeh.io import install_notebook_hook
except ImportError:
return False
install_notebook_hook('pywebio', load_notebook, show_doc, show_app)
return True
| 15 | 1,712 | 67 | 1,779 | import asyncio
import re
from collections.abc import Sequence
from pywebio.output import *
from pywebio.session import get_info
requirejs_config_tpl = """
<script type="text/javascript">
require.config({
paths: {
"bokeh": "https://cdn.bokeh.org/bokeh/release/bokeh-__version__.min",
"bokeh-widgets"... | import asyncio
import re
from collections.abc import Sequence
from pywebio.output import *
from pywebio.session import get_info
requirejs_config_tpl = """
<script type="text/javascript">
require.config({
paths: {
"bokeh": "https://cdn.bokeh.org/bokeh/release/bokeh-__version__.min",
"bokeh-widgets"... | |
39,542 | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO | /home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/django.py | 49,50 | 19,75 | set_status | DjangoHttpContext | 51,53 | 50,53 | class DjangoHttpContext(HttpContext):
backend_name = 'django'
def __init__(self, request: HttpRequest):
self.request = request
self.response = HttpResponse()
def request_obj(self):
"""返回当前请求对象"""
return self.request
def request_method(self):
"""返回当前请求的方法,大写"""
... | class DjangoHttpContext(HttpContext):
backend_name = 'django'
def __init__(self, request: HttpRequest):
self.request = request
self.response = HttpResponse()
def request_obj(self):
"""返回当前请求对象"""
return self.request
def request_method(self):
"""返回当前请求的方法,大写"""
... | self.response.status_code = status
| """为当前响应设置http status"""
self.response.status_code = status
| 3 | 474 | 14 | 488 | import json
import logging
import os
import threading
from django.http import HttpResponse, HttpRequest
from . import page
from ..session import Session
from .adaptor.http import HttpContext, HttpHandler, run_event_loop
from .remote_access import start_remote_access_service
from .page import make_applications
from .u... | import json
import logging
import os
import threading
from django.http import HttpResponse, HttpRequest
from . import page
from ..session import Session
from .adaptor.http import HttpContext, HttpHandler, run_event_loop
from .remote_access import start_remote_access_service
from .page import make_applications
from .u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.