id
int64
1
6.07M
name
stringlengths
1
295
code
stringlengths
12
426k
language
stringclasses
1 value
source_file
stringlengths
5
202
start_line
int64
1
158k
end_line
int64
1
158k
repo
dict
4,901
cursor_left
def cursor_left(self, n=1): n = min(n, self.cursor.x) self.cursor.x -= n
python
wandb/sdk/lib/redirect.py
217
219
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,902
cursor_right
def cursor_right(self, n=1): self.cursor.x += n
python
wandb/sdk/lib/redirect.py
221
222
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,903
carriage_return
def carriage_return(self): self.cursor.x = 0
python
wandb/sdk/lib/redirect.py
224
225
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,904
cursor_postion
def cursor_postion(self, line, column): self.cursor.x = min(column, 1) - 1 self.cursor.y = min(line, 1) - 1
python
wandb/sdk/lib/redirect.py
227
229
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,905
cursor_column
def cursor_column(self, column): self.cursor.x = min(column, 1) - 1
python
wandb/sdk/lib/redirect.py
231
232
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,906
cursor_line
def cursor_line(self, line): self.cursor.y = min(line, 1) - 1
python
wandb/sdk/lib/redirect.py
234
235
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,907
linefeed
def linefeed(self): self.cursor_down() self.carriage_return()
python
wandb/sdk/lib/redirect.py
237
239
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,908
_get_line_len
def _get_line_len(self, n): if n not in self.buffer: return 0 line = self.buffer[n] if not line: return 0 n = max(line.keys()) for i in range(n, -1, -1): if line[i] != _defchar: return i + 1 return 0
python
wandb/sdk/lib/redirect.py
241
251
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,909
num_lines
def num_lines(self): if self._num_lines is not None: return self._num_lines ret = 0 if self.buffer: n = max(self.buffer.keys()) for i in range(n, -1, -1): if self._get_line_len(i): ret = i + 1 break self._num_lines = ret return ret
python
wandb/sdk/lib/redirect.py
254
265
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,910
display
def display(self): return [ [self.buffer[i][j].data for j in range(self._get_line_len(i))] for i in range(self.num_lines) ]
python
wandb/sdk/lib/redirect.py
267
271
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,911
erase_screen
def erase_screen(self, mode=0): if mode == 0: for i in range(self.cursor.y + 1, self.num_lines): if i in self.buffer: del self.buffer[i] self.erase_line(mode) if mode == 1: for i in range(self.cursor.y): if i in self.buffer: del self.buffer[i] self.erase_line(mode) elif mode == 2 or mode == 3: self.buffer.clear()
python
wandb/sdk/lib/redirect.py
273
285
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,912
erase_line
def erase_line(self, mode=0): curr_line = self.buffer[self.cursor.y] if mode == 0: for i in range(self.cursor.x, self._get_line_len(self.cursor.y)): if i in curr_line: del curr_line[i] elif mode == 1: for i in range(self.cursor.x + 1): if i in curr_line: del curr_line[i] else: curr_line.clear()
python
wandb/sdk/lib/redirect.py
287
298
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,913
insert_lines
def insert_lines(self, n=1): for i in range(self.num_lines - 1, self.cursor.y, -1): self.buffer[i + n] = self.buffer[i] for i in range(self.cursor.y + 1, self.cursor.y + 1 + n): if i in self.buffer: del self.buffer[i]
python
wandb/sdk/lib/redirect.py
300
305
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,914
_write_plain_text
def _write_plain_text(self, plain_text): self.buffer[self.cursor.y].update( [ (self.cursor.x + i, self.cursor.char.copy(data=c)) for i, c in enumerate(plain_text) ] ) self.cursor.x += len(plain_text)
python
wandb/sdk/lib/redirect.py
307
314
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,915
_write_text
def _write_text(self, text): prev_end = 0 for match in SEP_RE.finditer(text): start, end = match.span() self._write_plain_text(text[prev_end:start]) prev_end = end c = match.group() if c == "\n": self.linefeed() elif c == "\r": self.carriage_return() elif c == "\b": self.cursor_left() else: continue self._write_plain_text(text[prev_end:])
python
wandb/sdk/lib/redirect.py
316
331
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,916
_remove_osc
def _remove_osc(self, text): return re.sub(ANSI_OSC_RE, "", text)
python
wandb/sdk/lib/redirect.py
333
334
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,917
write
def write(self, data): self._num_lines = None # invalidate cache data = self._remove_osc(data) prev_end = 0 for match in ANSI_CSI_RE.finditer(data): start, end = match.span() text = data[prev_end:start] csi = data[start:end] prev_end = end self._write_text(text) self._handle_csi(csi, *match.groups()) self._write_text(data[prev_end:])
python
wandb/sdk/lib/redirect.py
336
347
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,918
_handle_csi
def _handle_csi(self, csi, params, command): try: if command == "m": p = params.split(";")[0] if not p: p = "0" if p in ANSI_FG: self.cursor.char.fg = p elif p in ANSI_BG: self.cursor.char.bg = p elif p == ANSI_RESET: self.cursor.char.reset() elif p in ANSI_STYLES: style = ANSI_STYLES[p] off = style.startswith("/") if off: style = style[1:] self.cursor.char[style] = not off else: abcd = { "A": "cursor_up", "B": "cursor_down", "C": "cursor_right", "D": "cursor_left", } cursor_fn = abcd.get(command) if cursor_fn: getattr(self, cursor_fn)(int(params) if params else 1) elif command == "J": p = params.split(";")[0] p = int(p) if p else 0 self.erase_screen(p) elif command == "K": p = params.split(";")[0] p = int(p) if p else 0 self.erase_line(p) elif command == "L": p = int(params) if params else 1 self.insert_lines(p) elif command in "Hf": p = params.split(";") if len(p) == 2: p = (int(p[0]), int(p[1])) elif len(p) == 1: p = (int(p[0]), 1) else: p = (1, 1) self.cursor_postion(*p) except Exception: pass
python
wandb/sdk/lib/redirect.py
349
398
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,919
_get_line
def _get_line(self, n): line = self.buffer[n] line_len = self._get_line_len(n) # We have to loop through each character in the line and check if foreground, background and # other attributes (italics, bold, underline, etc) of the ith character are different from those of the # (i-1)th character. If different, the appropriate ascii character for switching the color/attribute # should be appended to the output string before appending the actual character. This loop and subsequent # checks can be expensive, especially because 99% of terminal output use default colors and formatting. Even # in outputs that do contain colors and styles, its unlikely that they will change on a per character basis. # So instead we create a character list without any ascii codes (`out`), and a list of all the foregrounds # in the line (`fgs`) on which we call np.diff() and np.where() to find the indices where the foreground change, # and insert the ascii characters in the output list (`out`) on those indices. All of this is the done ony if # there are more than 1 foreground color in the line in the first place (`if len(set(fgs)) > 1 else None`). # Same logic is repeated for background colors and other attributes. out = [line[i].data for i in range(line_len)] # for dynamic insert using original indices idxs = np.arange(line_len) insert = lambda i, c: (out.insert(idxs[i], c), idxs[i:].__iadd__(1)) # noqa fgs = [int(_defchar.fg)] + [int(line[i].fg) for i in range(line_len)] [ insert(i, _get_char(line[int(i)].fg)) for i in np.where(np.diff(fgs))[0] ] if len(set(fgs)) > 1 else None bgs = [int(_defchar.bg)] + [int(line[i].bg) for i in range(line_len)] [ insert(i, _get_char(line[int(i)].bg)) for i in np.where(np.diff(bgs))[0] ] if len(set(bgs)) > 1 else None attrs = { k: [False] + [line[i][k] for i in range(line_len)] for k in Char.__slots__[3:] } [ [ insert(i, _get_char(ANSI_STYLES_REV[k if line[int(i)][k] else "/" + k])) for i in np.where(np.diff(v))[0] ] for k, v in attrs.items() if any(v) ] return "".join(out)
python
wandb/sdk/lib/redirect.py
400
442
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,920
read
def read(self): num_lines = self.num_lines if self._prev_num_lines is None: ret = os.linesep.join(map(self._get_line, range(num_lines))) if ret: ret += os.linesep else: return ret else: curr_line = self._get_line(self._prev_num_lines - 1) if curr_line == self._prev_last_line: if num_lines == self._prev_num_lines: return "" ret = ( os.linesep.join( map(self._get_line, range(self._prev_num_lines, num_lines)) ) + os.linesep ) else: ret = ( "\r" + os.linesep.join( map(self._get_line, range(self._prev_num_lines - 1, num_lines)) ) + os.linesep ) if num_lines > self._MAX_LINES: shift = num_lines - self._MAX_LINES for i in range(shift, num_lines): self.buffer[i - shift] = self.buffer[i] for i in range(self._MAX_LINES, max(self.buffer.keys())): if i in self.buffer: del self.buffer[i] self.cursor.y -= min(self.cursor.y, shift) self._num_lines = num_lines = self._MAX_LINES self._prev_num_lines = num_lines self._prev_last_line = self._get_line(num_lines - 1) return ret
python
wandb/sdk/lib/redirect.py
444
482
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,921
__init__
def __init__(self, src, cbs=()): """# Arguments. `src`: Source stream to be redirected. "stdout" or "stderr". `cbs`: tuple/list of callbacks. Each callback should take exactly 1 argument (bytes). """ assert hasattr(sys, src) self.src = src self.cbs = cbs
python
wandb/sdk/lib/redirect.py
489
498
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,922
src_stream
def src_stream(self): return getattr(sys, "__%s__" % self.src)
python
wandb/sdk/lib/redirect.py
501
502
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,923
src_fd
def src_fd(self): return self.src_stream.fileno()
python
wandb/sdk/lib/redirect.py
505
506
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,924
src_wrapped_stream
def src_wrapped_stream(self): return getattr(sys, self.src)
python
wandb/sdk/lib/redirect.py
509
510
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,925
save
def save(self): pass
python
wandb/sdk/lib/redirect.py
512
513
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,926
install
def install(self): curr_redirect = _redirects.get(self.src) if curr_redirect and curr_redirect != self: curr_redirect.uninstall() _redirects[self.src] = self
python
wandb/sdk/lib/redirect.py
515
519
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,927
uninstall
def uninstall(self): if _redirects[self.src] != self: return _redirects[self.src] = None
python
wandb/sdk/lib/redirect.py
521
524
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,928
__init__
def __init__(self, src, cbs=()): super().__init__(src=src, cbs=cbs) self._installed = False self._emulator = TerminalEmulator()
python
wandb/sdk/lib/redirect.py
530
533
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,929
_emulator_write
def _emulator_write(self): while True: if self._queue.empty(): if self._stopped.is_set(): return time.sleep(0.5) continue data = [] while not self._queue.empty(): data.append(self._queue.get()) if self._stopped.is_set() and sum(map(len, data)) > 100000: wandb.termlog("Terminal output too large. Logging without processing.") self.flush() [self.flush(line.encode("utf-8")) for line in data] return try: self._emulator.write("".join(data)) except Exception: pass
python
wandb/sdk/lib/redirect.py
535
553
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,930
_callback
def _callback(self): while not (self._stopped.is_set() and self._queue.empty()): self.flush() time.sleep(_MIN_CALLBACK_INTERVAL)
python
wandb/sdk/lib/redirect.py
555
558
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,931
install
def install(self): super().install() if self._installed: return stream = self.src_wrapped_stream old_write = stream.write self._prev_callback_timestamp = time.time() self._old_write = old_write def write(data): self._old_write(data) self._queue.put(data) stream.write = write self._queue = queue.Queue() self._stopped = threading.Event() self._emulator_write_thread = threading.Thread(target=self._emulator_write) self._emulator_write_thread.daemon = True self._emulator_write_thread.start() if not wandb.run or wandb.run._settings.mode == "online": self._callback_thread = threading.Thread(target=self._callback) self._callback_thread.daemon = True self._callback_thread.start() self._installed = True
python
wandb/sdk/lib/redirect.py
560
586
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,932
write
def write(data): self._old_write(data) self._queue.put(data)
python
wandb/sdk/lib/redirect.py
569
571
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,933
flush
def flush(self, data=None): if data is None: try: data = self._emulator.read().encode("utf-8") except Exception: pass if data: for cb in self.cbs: try: cb(data) except Exception: pass # TODO(frz)
python
wandb/sdk/lib/redirect.py
588
599
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,934
uninstall
def uninstall(self): if not self._installed: return self.src_wrapped_stream.write = self._old_write self._stopped.set() self._emulator_write_thread.join(timeout=5) if self._emulator_write_thread.is_alive(): wandb.termlog(f"Processing terminal output ({self.src})...") self._emulator_write_thread.join() wandb.termlog("Done.") self.flush() self._installed = False super().uninstall()
python
wandb/sdk/lib/redirect.py
601
615
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,935
__init__
def __init__(self, src, cbs=()): super().__init__(src=src, cbs=cbs) self._installed = False
python
wandb/sdk/lib/redirect.py
624
626
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,936
save
def save(self): stream = self.src_wrapped_stream self._old_write = stream.write
python
wandb/sdk/lib/redirect.py
628
630
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,937
install
def install(self): super().install() if self._installed: return stream = self.src_wrapped_stream self._prev_callback_timestamp = time.time() def write(data): self._old_write(data) for cb in self.cbs: try: cb(data) except Exception: # TODO: Figure out why this was needed and log or error out appropriately # it might have been strange terminals? maybe shutdown cases? pass stream.write = write self._installed = True
python
wandb/sdk/lib/redirect.py
632
650
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,938
write
def write(data): self._old_write(data) for cb in self.cbs: try: cb(data) except Exception: # TODO: Figure out why this was needed and log or error out appropriately # it might have been strange terminals? maybe shutdown cases? pass
python
wandb/sdk/lib/redirect.py
639
647
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,939
uninstall
def uninstall(self): if not self._installed: return self.src_wrapped_stream.write = self._old_write self._installed = False super().uninstall()
python
wandb/sdk/lib/redirect.py
652
657
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,940
__init__
def __init__(self): self._fds = set()
python
wandb/sdk/lib/redirect.py
661
662
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,941
_register
def _register(self): old_handler = signal.signal(signal.SIGWINCH, lambda *_: None) def handler(signum, frame): if callable(old_handler): old_handler(signum, frame) self.handle_window_size_change() signal.signal(signal.SIGWINCH, handler) self._old_handler = old_handler
python
wandb/sdk/lib/redirect.py
664
673
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,942
handler
def handler(signum, frame): if callable(old_handler): old_handler(signum, frame) self.handle_window_size_change()
python
wandb/sdk/lib/redirect.py
667
670
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,943
_unregister
def _unregister(self): signal.signal(signal.SIGWINCH, self._old_handler)
python
wandb/sdk/lib/redirect.py
675
676
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,944
add_fd
def add_fd(self, fd): if not self._fds: self._register() self._fds.add(fd) self.handle_window_size_change()
python
wandb/sdk/lib/redirect.py
678
682
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,945
remove_fd
def remove_fd(self, fd): if fd in self._fds: self._fds.remove(fd) if not self._fds: self._unregister()
python
wandb/sdk/lib/redirect.py
684
688
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,946
handle_window_size_change
def handle_window_size_change(self): try: win_size = fcntl.ioctl(0, termios.TIOCGWINSZ, "\0" * 8) rows, cols, xpix, ypix = struct.unpack("HHHH", win_size) # Note: IOError not subclass of OSError in python 2.x except OSError: # eg. in MPI we can't do this. return if cols == 0: return win_size = struct.pack("HHHH", rows, cols, xpix, ypix) for fd in self._fds: fcntl.ioctl(fd, termios.TIOCSWINSZ, win_size)
python
wandb/sdk/lib/redirect.py
690
701
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,947
__init__
def __init__(self, src, cbs=()): super().__init__(src=src, cbs=cbs) self._installed = False self._emulator = TerminalEmulator()
python
wandb/sdk/lib/redirect.py
710
713
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,948
_pipe
def _pipe(self): if pty: r, w = pty.openpty() else: r, w = os.pipe() return r, w
python
wandb/sdk/lib/redirect.py
715
720
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,949
install
def install(self): super().install() if self._installed: return self._pipe_read_fd, self._pipe_write_fd = self._pipe() if os.isatty(self._pipe_read_fd): _WSCH.add_fd(self._pipe_read_fd) self._orig_src_fd = os.dup(self.src_fd) self._orig_src = os.fdopen(self._orig_src_fd, "wb", 0) os.dup2(self._pipe_write_fd, self.src_fd) self._installed = True self._queue = queue.Queue() self._stopped = threading.Event() self._pipe_relay_thread = threading.Thread(target=self._pipe_relay) self._pipe_relay_thread.daemon = True self._pipe_relay_thread.start() self._emulator_write_thread = threading.Thread(target=self._emulator_write) self._emulator_write_thread.daemon = True self._emulator_write_thread.start() if not wandb.run or wandb.run._settings.mode == "online": self._callback_thread = threading.Thread(target=self._callback) self._callback_thread.daemon = True self._callback_thread.start()
python
wandb/sdk/lib/redirect.py
722
744
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,950
uninstall
def uninstall(self): if not self._installed: return self._installed = False # If the user printed a very long string (millions of chars) right before wandb.finish(), # it will take a while for it to reach pipe relay. 1 second is enough time for ~5 million chars. time.sleep(1) self._stopped.set() os.dup2(self._orig_src_fd, self.src_fd) os.write(self._pipe_write_fd, _LAST_WRITE_TOKEN) self._pipe_relay_thread.join() os.close(self._pipe_read_fd) os.close(self._pipe_write_fd) t = threading.Thread( target=self.src_wrapped_stream.flush ) # Calling flush() from the current thread does not flush the buffer instantly. t.start() t.join(timeout=10) self._emulator_write_thread.join(timeout=5) if self._emulator_write_thread.is_alive(): wandb.termlog(f"Processing terminal output ({self.src})...") self._emulator_write_thread.join() wandb.termlog("Done.") self.flush() _WSCH.remove_fd(self._pipe_read_fd) super().uninstall()
python
wandb/sdk/lib/redirect.py
746
774
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,951
flush
def flush(self, data=None): if data is None: try: data = self._emulator.read().encode("utf-8") except Exception: pass if data: for cb in self.cbs: try: cb(data) except Exception: pass # TODO(frz)
python
wandb/sdk/lib/redirect.py
776
787
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,952
_callback
def _callback(self): while not self._stopped.is_set(): self.flush() time.sleep(_MIN_CALLBACK_INTERVAL)
python
wandb/sdk/lib/redirect.py
789
792
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,953
_pipe_relay
def _pipe_relay(self): while True: try: brk = False data = os.read(self._pipe_read_fd, 4096) if self._stopped.is_set(): if _LAST_WRITE_TOKEN not in data: # _LAST_WRITE_TOKEN could have gotten split up at the 4096 border n = len(_LAST_WRITE_TOKEN) while n and data[-n:] != _LAST_WRITE_TOKEN[:n]: n -= 1 if n: data += os.read( self._pipe_read_fd, len(_LAST_WRITE_TOKEN) - n ) if _LAST_WRITE_TOKEN in data: data = data.replace(_LAST_WRITE_TOKEN, b"") brk = True i = self._orig_src.write(data) if i is not None: # python 3 w/ unbuffered i/o: we need to keep writing while i < len(data): i += self._orig_src.write(data[i:]) self._queue.put(data) if brk: return except OSError: return
python
wandb/sdk/lib/redirect.py
794
820
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,954
_emulator_write
def _emulator_write(self): while True: if self._queue.empty(): if self._stopped.is_set(): return time.sleep(0.5) continue data = [] while not self._queue.empty(): data.append(self._queue.get()) if self._stopped.is_set() and sum(map(len, data)) > 100000: wandb.termlog("Terminal output too large. Logging without processing.") self.flush() [self.flush(line) for line in data] return try: self._emulator.write(b"".join(data).decode("utf-8")) except Exception: pass
python
wandb/sdk/lib/redirect.py
822
840
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,955
__init__
def __init__(self, name: str, destination: Optional[Any] = None) -> None: self._name = name if destination is not None: self.__doc__ = destination.__doc__
python
wandb/sdk/lib/preinit.py
7
11
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,956
__getitem__
def __getitem__(self, key: str) -> None: raise wandb.Error(f"You must call wandb.init() before {self._name}[{key!r}]")
python
wandb/sdk/lib/preinit.py
13
14
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,957
__setitem__
def __setitem__(self, key: str, value: Any) -> Any: raise wandb.Error(f"You must call wandb.init() before {self._name}[{key!r}]")
python
wandb/sdk/lib/preinit.py
16
17
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,958
__setattr__
def __setattr__(self, key: str, value: Any) -> Any: if not key.startswith("_"): raise wandb.Error(f"You must call wandb.init() before {self._name}.{key}") else: return object.__setattr__(self, key, value)
python
wandb/sdk/lib/preinit.py
19
23
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,959
__getattr__
def __getattr__(self, key: str) -> Any: if not key.startswith("_"): raise wandb.Error(f"You must call wandb.init() before {self._name}.{key}") else: raise AttributeError
python
wandb/sdk/lib/preinit.py
25
29
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,960
PreInitCallable
def PreInitCallable( # noqa: N802 name: str, destination: Optional[Any] = None ) -> Callable: def preinit_wrapper(*args: Any, **kwargs: Any) -> Any: raise wandb.Error(f"You must call wandb.init() before {name}()") preinit_wrapper.__name__ = str(name) if destination: preinit_wrapper.__wrapped__ = destination # type: ignore preinit_wrapper.__doc__ = destination.__doc__ return preinit_wrapper
python
wandb/sdk/lib/preinit.py
32
42
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,961
preinit_wrapper
def preinit_wrapper(*args: Any, **kwargs: Any) -> Any: raise wandb.Error(f"You must call wandb.init() before {name}()")
python
wandb/sdk/lib/preinit.py
35
36
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,962
split_files
def split_files( files: Dict[str, Any], max_bytes: int = 10 * 1024 * 1024 ) -> Iterable[Dict[str, Dict]]: """Split a file's dict (see `files` arg) into smaller dicts. Each smaller dict will have at most `MAX_BYTES` size. This method is used in `FileStreamAPI._send()` to limit the size of post requests sent to wandb server. Arguments: files (dict): `dict` of form {file_name: {'content': ".....", 'offset': 0}} The key `file_name` can also be mapped to a List [{"offset": int, "content": str}] `max_bytes`: max size for chunk in bytes """ current_volume: Dict[str, Dict] = {} current_size = 0 def _str_size(x): return len(x) if isinstance(x, bytes) else len(x.encode("utf-8")) def _file_size(file): size = file.get("_size") if size is None: size = sum(map(_str_size, file["content"])) file["_size"] = size return size def _split_file(file, num_lines): offset = file["offset"] content = file["content"] name = file["name"] f1 = {"offset": offset, "content": content[:num_lines], "name": name} f2 = { "offset": offset + num_lines, "content": content[num_lines:], "name": name, } return f1, f2 def _num_lines_from_num_bytes(file, num_bytes): size = 0 num_lines = 0 content = file["content"] while num_lines < len(content): size += _str_size(content[num_lines]) if size > num_bytes: break num_lines += 1 return num_lines files_stack = [] for k, v in files.items(): if isinstance(v, list): for item in v: files_stack.append( {"name": k, "offset": item["offset"], "content": item["content"]} ) else: files_stack.append( {"name": k, "offset": v["offset"], "content": v["content"]} ) while files_stack: f = files_stack.pop() if f["name"] in current_volume: files_stack.append(f) yield current_volume current_volume = {} current_size = 0 continue # For each file, we have to do 1 of 4 things: # - Add the file as such to the current volume if possible. # - Split the file and add the first part to the current volume and push the second part back onto the stack. # - If that's not possible, check if current volume is empty: # - If empty, add first line of file to current volume and push rest onto stack (This volume will exceed MAX_MB). # - If not, push file back to stack and yield current volume. fsize = _file_size(f) rem = max_bytes - current_size if fsize <= rem: current_volume[f["name"]] = { "offset": f["offset"], "content": f["content"], } current_size += fsize else: num_lines = _num_lines_from_num_bytes(f, rem) if not num_lines and not current_volume: num_lines = 1 if num_lines: f1, f2 = _split_file(f, num_lines) current_volume[f1["name"]] = { "offset": f1["offset"], "content": f1["content"], } files_stack.append(f2) yield current_volume current_volume = {} current_size = 0 continue else: files_stack.append(f) yield current_volume current_volume = {} current_size = 0 continue if current_size >= max_bytes: yield current_volume current_volume = {} current_size = 0 continue if current_volume: yield current_volume
python
wandb/sdk/lib/file_stream_utils.py
5
118
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,963
_str_size
def _str_size(x): return len(x) if isinstance(x, bytes) else len(x.encode("utf-8"))
python
wandb/sdk/lib/file_stream_utils.py
23
24
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,964
_file_size
def _file_size(file): size = file.get("_size") if size is None: size = sum(map(_str_size, file["content"])) file["_size"] = size return size
python
wandb/sdk/lib/file_stream_utils.py
26
31
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,965
_split_file
def _split_file(file, num_lines): offset = file["offset"] content = file["content"] name = file["name"] f1 = {"offset": offset, "content": content[:num_lines], "name": name} f2 = { "offset": offset + num_lines, "content": content[num_lines:], "name": name, } return f1, f2
python
wandb/sdk/lib/file_stream_utils.py
33
43
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,966
_num_lines_from_num_bytes
def _num_lines_from_num_bytes(file, num_bytes): size = 0 num_lines = 0 content = file["content"] while num_lines < len(content): size += _str_size(content[num_lines]) if size > num_bytes: break num_lines += 1 return num_lines
python
wandb/sdk/lib/file_stream_utils.py
45
54
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,967
is_wandb_file
def is_wandb_file(name: str) -> bool: return ( name.startswith("wandb") or name == METADATA_FNAME or name == CONFIG_FNAME or name == REQUIREMENTS_FNAME or name == OUTPUT_FNAME or name == DIFF_FNAME or name == CONDA_ENVIRONMENTS_FNAME )
python
wandb/sdk/lib/filenames.py
19
28
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,968
filtered_dir
def filtered_dir( root: str, include_fn: Callable[[str], bool], exclude_fn: Callable[[str], bool] ) -> Generator[str, None, None]: """Simple generator to walk a directory.""" for dirpath, _, files in os.walk(root): for fname in files: file_path = os.path.join(dirpath, fname) if include_fn(file_path) and not exclude_fn(file_path): yield file_path
python
wandb/sdk/lib/filenames.py
31
39
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,969
exclude_wandb_fn
def exclude_wandb_fn(path: str) -> bool: return any(os.sep + wandb_dir + os.sep in path for wandb_dir in WANDB_DIRS)
python
wandb/sdk/lib/filenames.py
42
43
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,970
mkdir_exists_ok
def mkdir_exists_ok(dir_name: StrPath) -> None: """Create `dir_name` and any parent directories if they don't exist. Raises: FileExistsError: if `dir_name` exists and is not a directory. PermissionError: if `dir_name` is not writable. """ try: os.makedirs(dir_name, exist_ok=True) except FileExistsError as e: raise FileExistsError(f"{dir_name!s} exists and is not a directory") from e except PermissionError as e: raise PermissionError(f"{dir_name!s} is not writable") from e
python
wandb/sdk/lib/filesystem.py
17
29
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,971
__init__
def __init__(self, f: BinaryIO) -> None: self.lock = threading.Lock() self.f = f
python
wandb/sdk/lib/filesystem.py
35
37
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,972
write
def write(self, *args, **kargs) -> None: # type: ignore self.lock.acquire() try: self.f.write(*args, **kargs) self.f.flush() finally: self.lock.release()
python
wandb/sdk/lib/filesystem.py
39
45
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,973
close
def close(self) -> None: self.lock.acquire() # wait for pending writes try: self.f.close() finally: self.lock.release()
python
wandb/sdk/lib/filesystem.py
47
52
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,974
__init__
def __init__(self, f: BinaryIO) -> None: super().__init__(f=f) self._buff = b""
python
wandb/sdk/lib/filesystem.py
56
58
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,975
write
def write(self, data) -> None: # type: ignore lines = re.split(b"\r\n|\n", data) ret = [] # type: ignore for line in lines: if line[:1] == b"\r": if ret: ret.pop() elif self._buff: self._buff = b"" line = line.split(b"\r")[-1] if line: ret.append(line) if self._buff: ret.insert(0, self._buff) if ret: self._buff = ret.pop() super().write(b"\n".join(ret) + b"\n")
python
wandb/sdk/lib/filesystem.py
60
76
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,976
close
def close(self) -> None: if self._buff: super().write(self._buff) super().close()
python
wandb/sdk/lib/filesystem.py
78
81
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,977
copy_or_overwrite_changed
def copy_or_overwrite_changed(source_path: StrPath, target_path: StrPath) -> StrPath: """Copy source_path to target_path, unless it already exists with the same mtime. We liberally add write permissions to deal with the case of multiple users needing to share the same cache or run directory. Args: source_path: The path to the file to copy. target_path: The path to copy the file to. Returns: The path to the copied file (which may be different from target_path). """ return_type = type(target_path) if platform.system() == "Windows": head, tail = os.path.splitdrive(str(target_path)) if ":" in tail: logger.warning("Replacing ':' in %s with '-'", tail) target_path = os.path.join(head, tail.replace(":", "-")) need_copy = ( not os.path.isfile(target_path) or os.stat(source_path).st_mtime != os.stat(target_path).st_mtime ) permissions_plus_write = os.stat(source_path).st_mode | WRITE_PERMISSIONS if need_copy: mkdir_exists_ok(os.path.dirname(target_path)) try: # Use copy2 to preserve file metadata (including modified time). shutil.copy2(source_path, target_path) except PermissionError: # If the file is read-only try to make it writable. try: os.chmod(target_path, permissions_plus_write) shutil.copy2(source_path, target_path) except PermissionError as e: raise PermissionError("Unable to overwrite '{target_path!s}'") from e # Prevent future permissions issues by universal write permissions now. os.chmod(target_path, permissions_plus_write) return return_type(target_path) # type: ignore # 'os.PathLike' is abstract.
python
wandb/sdk/lib/filesystem.py
84
126
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,978
synchronized
def synchronized(lock: "threading.RLock") -> Callable: def decorator(func: Callable) -> Callable: @functools.wraps(func) def new_func(*args: Any, **kwargs: Any) -> Any: with lock: return func(*args, **kwargs) return new_func return decorator
python
wandb/sdk/lib/import_hooks.py
18
27
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,979
decorator
def decorator(func: Callable) -> Callable: @functools.wraps(func) def new_func(*args: Any, **kwargs: Any) -> Any: with lock: return func(*args, **kwargs) return new_func
python
wandb/sdk/lib/import_hooks.py
19
25
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,980
new_func
def new_func(*args: Any, **kwargs: Any) -> Any: with lock: return func(*args, **kwargs)
python
wandb/sdk/lib/import_hooks.py
21
23
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,981
_create_import_hook_from_string
def _create_import_hook_from_string(name: str) -> Any: def import_hook(module: Any) -> Any: module_name, function = name.split(":") attrs = function.split(".") __import__(module_name) callback = sys.modules[module_name] for attr in attrs: callback = getattr(callback, attr) return callback(module) # type: ignore return import_hook
python
wandb/sdk/lib/import_hooks.py
48
58
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,982
import_hook
def import_hook(module: Any) -> Any: module_name, function = name.split(":") attrs = function.split(".") __import__(module_name) callback = sys.modules[module_name] for attr in attrs: callback = getattr(callback, attr) return callback(module) # type: ignore
python
wandb/sdk/lib/import_hooks.py
49
56
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,983
register_post_import_hook
def register_post_import_hook(hook: Callable, hook_id: str, name: str) -> None: # Create a deferred import hook if hook is a string name rather than # a callable function. if isinstance(hook, (str,)): hook = _create_import_hook_from_string(hook) # type: ignore # Automatically install the import hook finder if it has not already # been installed. global _post_import_hooks_init if not _post_import_hooks_init: _post_import_hooks_init = True sys.meta_path.insert(0, ImportHookFinder()) # type: ignore # Determine if any prior registration of a post import hook for # the target modules has occurred and act appropriately. hooks = _post_import_hooks.get(name) if hooks is None: # No prior registration of post import hooks for the target # module. We need to check whether the module has already been # imported. If it has we fire the hook immediately and add an # empty list to the registry to indicate that the module has # already been imported and hooks have fired. Otherwise add # the post import hook to the registry. module = sys.modules.get(name) if module is not None: _post_import_hooks[name] = {} if hook: # type: ignore hook(module) else: _post_import_hooks[name] = {hook_id: hook} elif hooks == {}: # A prior registration of post import hooks for the target # module was done and the hooks already fired. Fire the hook # immediately. module = sys.modules.get(name) if module is not None: if hook: # type: ignore hook(module) else: # A prior registration of port post hooks for the target # module was done but the module has not yet been imported. _post_import_hooks[name].update({hook_id: hook})
python
wandb/sdk/lib/import_hooks.py
62
116
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,984
unregister_post_import_hook
def unregister_post_import_hook(name: str, hook_id: Optional[str]) -> None: # Remove the import hook if it has been registered. hooks = _post_import_hooks.get(name) if hooks is not None: if hook_id is not None: hooks.pop(hook_id, None) if not hooks: del _post_import_hooks[name] else: del _post_import_hooks[name]
python
wandb/sdk/lib/import_hooks.py
120
131
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,985
unregister_all_post_import_hooks
def unregister_all_post_import_hooks() -> None: _post_import_hooks.clear()
python
wandb/sdk/lib/import_hooks.py
135
136
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,986
_create_import_hook_from_entrypoint
def _create_import_hook_from_entrypoint(entrypoint: Any) -> Callable: def import_hook(module: Any) -> Any: __import__(entrypoint.module_name) callback = sys.modules[entrypoint.module_name] for attr in entrypoint.attrs: callback = getattr(callback, attr) return callback(module) # type: ignore return import_hook
python
wandb/sdk/lib/import_hooks.py
142
150
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,987
import_hook
def import_hook(module: Any) -> Any: __import__(entrypoint.module_name) callback = sys.modules[entrypoint.module_name] for attr in entrypoint.attrs: callback = getattr(callback, attr) return callback(module) # type: ignore
python
wandb/sdk/lib/import_hooks.py
143
148
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,988
discover_post_import_hooks
def discover_post_import_hooks(group: Any) -> None: try: import pkg_resources except ImportError: return for entrypoint in pkg_resources.iter_entry_points(group=group): callback = _create_import_hook_from_entrypoint(entrypoint) register_post_import_hook(callback, entrypoint.name)
python
wandb/sdk/lib/import_hooks.py
153
161
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,989
notify_module_loaded
def notify_module_loaded(module: Any) -> None: name = getattr(module, "__name__", None) hooks = _post_import_hooks.get(name) if hooks: _post_import_hooks[name] = {} for hook in hooks.values(): if hook: hook(module)
python
wandb/sdk/lib/import_hooks.py
171
179
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,990
__init__
def __init__(self, loader: Any) -> None: self.loader = loader
python
wandb/sdk/lib/import_hooks.py
189
190
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,991
load_module
def load_module(self, fullname: str) -> Any: module = self.loader.load_module(fullname) notify_module_loaded(module) return module
python
wandb/sdk/lib/import_hooks.py
192
196
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,992
__init__
def __init__(self) -> None: self.in_progress: Dict = {}
python
wandb/sdk/lib/import_hooks.py
200
201
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,993
find_module
def find_module( # type: ignore self, fullname: str, path: Optional[str] = None, ) -> Optional["_ImportHookChainedLoader"]: # If the module being imported is not one we have registered # post import hooks for, we can return immediately. We will # take no further part in the importing of this module. if fullname not in _post_import_hooks: return None # When we are interested in a specific module, we will call back # into the import system a second time to defer to the import # finder that is supposed to handle the importing of the module. # We set an in progress flag for the target module so that on # the second time through we don't trigger another call back # into the import system and cause a infinite loop. if fullname in self.in_progress: return None self.in_progress[fullname] = True # Now call back into the import system again. try: # For Python 3 we need to use find_spec().loader # from the importlib.util module. It doesn't actually # import the target module and only finds the # loader. If a loader is found, we need to return # our own loader which will then in turn call the # real loader to import the module and invoke the # post import hooks. try: import importlib.util loader = importlib.util.find_spec(fullname).loader # type: ignore except (ImportError, AttributeError): loader = importlib.find_loader(fullname, path) if loader: return _ImportHookChainedLoader(loader) finally: del self.in_progress[fullname]
python
wandb/sdk/lib/import_hooks.py
204
248
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,994
_echo
def _echo(prompt: str) -> None: sys.stdout.write(prompt) sys.stdout.flush()
python
wandb/sdk/lib/timed_input.py
17
19
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,995
_posix_timed_input
def _posix_timed_input(prompt: str, timeout: float) -> str: _echo(prompt) sel = selectors.DefaultSelector() sel.register(sys.stdin, selectors.EVENT_READ, data=sys.stdin.readline) events = sel.select(timeout=timeout) for key, _ in events: input_callback = key.data input_data: str = input_callback() if not input_data: # end-of-file - treat as timeout raise TimeoutError return input_data.rstrip(LF) _echo(LF) termios.tcflush(sys.stdin, termios.TCIFLUSH) raise TimeoutError
python
wandb/sdk/lib/timed_input.py
22
37
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,996
_windows_timed_input
def _windows_timed_input(prompt: str, timeout: float) -> str: interval = 0.1 _echo(prompt) begin = time.monotonic() end = begin + timeout line = "" while time.monotonic() < end: if msvcrt.kbhit(): # type: ignore[attr-defined] c = msvcrt.getwche() # type: ignore[attr-defined] if c in (CR, LF): _echo(CRLF) return line if c == "\003": raise KeyboardInterrupt if c == "\b": line = line[:-1] cover = SP * len(prompt + line + SP) _echo("".join([CR, cover, CR, prompt, line])) else: line += c time.sleep(interval) _echo(CRLF) raise TimeoutError
python
wandb/sdk/lib/timed_input.py
40
65
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,997
_jupyter_timed_input
def _jupyter_timed_input(prompt: str, timeout: float) -> str: clear = True try: from IPython.core.display import clear_output # type: ignore except ImportError: clear = False wandb.termwarn( "Unable to clear output, can't import clear_output from ipython.core" ) _echo(prompt) user_inp = None event = threading.Event() def get_input() -> None: nonlocal user_inp raw = input() if event.is_set(): return user_inp = raw t = threading.Thread(target=get_input) t.start() t.join(timeout) event.set() if user_inp: return user_inp if clear: clear_output() raise TimeoutError
python
wandb/sdk/lib/timed_input.py
68
98
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,998
get_input
def get_input() -> None: nonlocal user_inp raw = input() if event.is_set(): return user_inp = raw
python
wandb/sdk/lib/timed_input.py
83
88
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,999
timed_input
def timed_input( prompt: str, timeout: float, show_timeout: bool = True, jupyter: bool = False ) -> str: """Behaves like builtin `input()` but adds timeout. Args: prompt (str): Prompt to output to stdout. timeout (float): Timeout to wait for input. show_timeout (bool): Show timeout in prompt jupyter (bool): If True, use jupyter specific code. Raises: TimeoutError: exception raised if timeout occurred. """ if show_timeout: prompt = f"{prompt}({timeout:.0f} second timeout) " if jupyter: return _jupyter_timed_input(prompt=prompt, timeout=timeout) return _timed_input(prompt=prompt, timeout=timeout)
python
wandb/sdk/lib/timed_input.py
101
120
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
5,000
__init__
def __init__( self, run: Optional["wandb_run.Run"] = None, obj: Optional[TelemetryRecord] = None, ) -> None: self._run = run or wandb.run self._obj = obj or TelemetryRecord()
python
wandb/sdk/lib/telemetry.py
23
29
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }