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
901
_filter_timestamps
def _filter_timestamps(tar_info: "tarfile.TarInfo") -> Optional["tarfile.TarInfo"]: tar_info.mtime = 0 return tar_info if custom_filter is None else custom_filter(tar_info)
python
wandb/util.py
335
337
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
902
_user_args_to_dict
def _user_args_to_dict(arguments: List[str]) -> Dict[str, Union[str, bool]]: user_dict = dict() value: Union[str, bool] name: str i = 0 while i < len(arguments): arg = arguments[i] split = arg.split("=", maxsplit=1) # flag arguments don't require a value -> set to True if spe...
python
wandb/util.py
354
381
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
903
is_tf_tensor
def is_tf_tensor(obj: Any) -> bool: import tensorflow # type: ignore return isinstance(obj, tensorflow.Tensor)
python
wandb/util.py
384
387
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
904
is_tf_tensor_typename
def is_tf_tensor_typename(typename: str) -> bool: return typename.startswith("tensorflow.") and ( "Tensor" in typename or "Variable" in typename )
python
wandb/util.py
390
393
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
905
is_tf_eager_tensor_typename
def is_tf_eager_tensor_typename(typename: str) -> bool: return typename.startswith("tensorflow.") and ("EagerTensor" in typename)
python
wandb/util.py
396
397
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
906
is_pytorch_tensor
def is_pytorch_tensor(obj: Any) -> bool: import torch # type: ignore return isinstance(obj, torch.Tensor)
python
wandb/util.py
400
403
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
907
is_pytorch_tensor_typename
def is_pytorch_tensor_typename(typename: str) -> bool: return typename.startswith("torch.") and ( "Tensor" in typename or "Variable" in typename )
python
wandb/util.py
406
409
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
908
is_jax_tensor_typename
def is_jax_tensor_typename(typename: str) -> bool: return typename.startswith("jaxlib.") and "Array" in typename
python
wandb/util.py
412
413
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
909
get_jax_tensor
def get_jax_tensor(obj: Any) -> Optional[Any]: import jax # type: ignore return jax.device_get(obj)
python
wandb/util.py
416
419
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
910
is_fastai_tensor_typename
def is_fastai_tensor_typename(typename: str) -> bool: return typename.startswith("fastai.") and ("Tensor" in typename)
python
wandb/util.py
422
423
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
911
is_pandas_data_frame_typename
def is_pandas_data_frame_typename(typename: str) -> bool: return typename.startswith("pandas.") and "DataFrame" in typename
python
wandb/util.py
426
427
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
912
is_matplotlib_typename
def is_matplotlib_typename(typename: str) -> bool: return typename.startswith("matplotlib.")
python
wandb/util.py
430
431
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
913
is_plotly_typename
def is_plotly_typename(typename: str) -> bool: return typename.startswith("plotly.")
python
wandb/util.py
434
435
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
914
is_plotly_figure_typename
def is_plotly_figure_typename(typename: str) -> bool: return typename.startswith("plotly.") and typename.endswith(".Figure")
python
wandb/util.py
438
439
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
915
is_numpy_array
def is_numpy_array(obj: Any) -> bool: return np and isinstance(obj, np.ndarray)
python
wandb/util.py
442
443
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
916
is_pandas_data_frame
def is_pandas_data_frame(obj: Any) -> bool: return is_pandas_data_frame_typename(get_full_typename(obj))
python
wandb/util.py
446
447
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
917
ensure_matplotlib_figure
def ensure_matplotlib_figure(obj: Any) -> Any: """Extract the current figure from a matplotlib object. Return the object itself if it's a figure. Raises ValueError if the object can't be converted. """ import matplotlib # type: ignore from matplotlib.figure import Figure # type: ignore #...
python
wandb/util.py
450
495
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
918
is_frame_like
def is_frame_like(self: Any) -> bool: """Return True if directly on axes frame. This is useful for determining if a spine is the edge of an old style MPL plot. If so, this function will return True. """ position = self._position or ("outward", 0.0) if isinstance(position...
python
wandb/util.py
463
481
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
919
matplotlib_to_plotly
def matplotlib_to_plotly(obj: Any) -> Any: obj = ensure_matplotlib_figure(obj) tools = get_module( "plotly.tools", required=( "plotly is required to log interactive plots, install with: " "`pip install plotly` or convert the plot to an image with `wandb.Image(plt)`" ...
python
wandb/util.py
498
507
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
920
matplotlib_contains_images
def matplotlib_contains_images(obj: Any) -> bool: obj = ensure_matplotlib_figure(obj) return any(len(ax.images) > 0 for ax in obj.axes)
python
wandb/util.py
510
512
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
921
_numpy_generic_convert
def _numpy_generic_convert(obj: Any) -> Any: obj = obj.item() if isinstance(obj, float) and math.isnan(obj): obj = None elif isinstance(obj, np.generic) and ( obj.dtype.kind == "f" or obj.dtype == "bfloat16" ): # obj is a numpy float with precision greater than that of native pyt...
python
wandb/util.py
515
528
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
922
_find_all_matching_keys
def _find_all_matching_keys( d: Dict, match_fn: Callable[[Any], bool], visited: Optional[Set[int]] = None, key_path: Tuple[Any, ...] = (), ) -> Generator[Tuple[Tuple[Any, ...], Any], None, None]: """Recursively find all keys that satisfies a match function. Args: d: The dict to search. ...
python
wandb/util.py
531
562
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
923
_sanitize_numpy_keys
def _sanitize_numpy_keys(d: Dict) -> Tuple[Dict, bool]: np_keys = list(_find_all_matching_keys(d, lambda k: isinstance(k, np.generic))) if not np_keys: return d, False for key_path, key in np_keys: ptr = d for k in key_path: ptr = ptr[k] ptr[_numpy_generic_convert...
python
wandb/util.py
565
574
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
924
json_friendly
def json_friendly( # noqa: C901 obj: Any, ) -> Union[Tuple[Any, bool], Tuple[Union[None, str, float], bool]]: """Convert an object into something that's more becoming of JSON.""" converted = True typename = get_full_typename(obj) if is_tf_eager_tensor_typename(typename): obj = obj.numpy() ...
python
wandb/util.py
577
639
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
925
json_friendly_val
def json_friendly_val(val: Any) -> Any: """Make any value (including dict, slice, sequence, etc) JSON friendly.""" converted: Union[dict, list] if isinstance(val, dict): converted = {} for key, value in val.items(): converted[key] = json_friendly_val(value) return convert...
python
wandb/util.py
642
664
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
926
alias_is_version_index
def alias_is_version_index(alias: str) -> bool: return len(alias) >= 2 and alias[0] == "v" and alias[1:].isnumeric()
python
wandb/util.py
667
668
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
927
convert_plots
def convert_plots(obj: Any) -> Any: if is_matplotlib_typename(get_full_typename(obj)): tools = get_module( "plotly.tools", required=( "plotly is required to log interactive plots, install with: " "`pip install plotly` or convert the plot to an image wi...
python
wandb/util.py
671
685
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
928
maybe_compress_history
def maybe_compress_history(obj: Any) -> Tuple[Any, bool]: if np and isinstance(obj, np.ndarray) and obj.size > 32: return wandb.Histogram(obj, num_bins=32).to_json(), True else: return obj, False
python
wandb/util.py
688
692
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
929
maybe_compress_summary
def maybe_compress_summary(obj: Any, h5_typename: str) -> Tuple[Any, bool]: if np and isinstance(obj, np.ndarray) and obj.size > 32: return ( { "_type": h5_typename, # may not be ndarray "var": np.var(obj).item(), "mean": np.mean(obj).item(), ...
python
wandb/util.py
695
713
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
930
launch_browser
def launch_browser(attempt_launch_browser: bool = True) -> bool: """Decide if we should launch a browser.""" _display_variables = ["DISPLAY", "WAYLAND_DISPLAY", "MIR_SOCKET"] _webbrowser_names_blocklist = ["www-browser", "lynx", "links", "elinks", "w3m"] import webbrowser launch_browser = attempt_...
python
wandb/util.py
716
736
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
931
generate_id
def generate_id(length: int = 8) -> str: # Do not use this; use wandb.sdk.lib.runid.generate_id instead. # This is kept only for legacy code. return runid.generate_id(length)
python
wandb/util.py
739
742
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
932
parse_tfjob_config
def parse_tfjob_config() -> Any: """Attempt to parse TFJob config, returning False if it can't find it.""" if os.getenv("TF_CONFIG"): try: return json.loads(os.environ["TF_CONFIG"]) except ValueError: return False else: return False
python
wandb/util.py
745
753
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
933
default
def default(self, obj: Any) -> Any: if hasattr(obj, "json_encode"): return obj.json_encode() # if hasattr(obj, 'to_json'): # return obj.to_json() tmp_obj, converted = json_friendly(obj) if converted: return tmp_obj return json.JSONEncoder.defau...
python
wandb/util.py
759
767
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
934
default
def default(self, obj: Any) -> Any: tmp_obj, converted = json_friendly(obj) tmp_obj, compressed = maybe_compress_summary(tmp_obj, get_h5_typename(obj)) if converted: return tmp_obj return json.JSONEncoder.default(self, tmp_obj)
python
wandb/util.py
773
778
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
935
default
def default(self, obj: Any) -> Any: obj, converted = json_friendly(obj) obj, compressed = maybe_compress_history(obj) if converted: return obj return json.JSONEncoder.default(self, obj)
python
wandb/util.py
787
792
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
936
default
def default(self, obj: Any) -> Any: if is_numpy_array(obj): return obj.tolist() elif np and isinstance(obj, np.generic): obj = obj.item() return json.JSONEncoder.default(self, obj)
python
wandb/util.py
801
806
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
937
json_dump_safer
def json_dump_safer(obj: Any, fp: IO[str], **kwargs: Any) -> None: """Convert obj to json, with some extra encodable types.""" return json.dump(obj, fp, cls=WandBJSONEncoder, **kwargs)
python
wandb/util.py
809
811
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
938
json_dumps_safer
def json_dumps_safer(obj: Any, **kwargs: Any) -> str: """Convert obj to json, with some extra encodable types.""" return json.dumps(obj, cls=WandBJSONEncoder, **kwargs)
python
wandb/util.py
814
816
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
939
json_dump_uncompressed
def json_dump_uncompressed(obj: Any, fp: IO[str], **kwargs: Any) -> None: """Convert obj to json, with some extra encodable types.""" return json.dump(obj, fp, cls=JSONEncoderUncompressed, **kwargs)
python
wandb/util.py
820
822
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
940
json_dumps_safer_history
def json_dumps_safer_history(obj: Any, **kwargs: Any) -> str: """Convert obj to json, with some extra encodable types, including histograms.""" return json.dumps(obj, cls=WandBHistoryJSONEncoder, **kwargs)
python
wandb/util.py
825
827
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
941
make_json_if_not_number
def make_json_if_not_number( v: Union[int, float, str, Mapping, Sequence] ) -> Union[int, float, str]: """If v is not a basic type convert it to json.""" if isinstance(v, (float, int)): return v return json_dumps_safer(v)
python
wandb/util.py
830
836
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
942
make_safe_for_json
def make_safe_for_json(obj: Any) -> Any: """Replace invalid json floats with strings. Also converts to lists and dicts.""" if isinstance(obj, Mapping): return {k: make_safe_for_json(v) for k, v in obj.items()} elif isinstance(obj, str): # str's are Sequence, so we need to short-circuit ...
python
wandb/util.py
839
856
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
943
no_retry_4xx
def no_retry_4xx(e: Exception) -> bool: if not isinstance(e, requests.HTTPError): return True if not (400 <= e.response.status_code < 500) or e.response.status_code == 429: return True body = json.loads(e.response.content) raise UsageError(body["errors"][0]["message"])
python
wandb/util.py
859
865
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
944
no_retry_auth
def no_retry_auth(e: Any) -> bool: if hasattr(e, "exception"): e = e.exception if not isinstance(e, requests.HTTPError): return True if e.response is None: return True # Don't retry bad request errors; raise immediately if e.response.status_code in (400, 409): return ...
python
wandb/util.py
868
897
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
945
check_retry_conflict
def check_retry_conflict(e: Any) -> Optional[bool]: """Check if the exception is a conflict type so it can be retried. Returns: True - Should retry this operation False - Should not retry this operation None - No decision, let someone else decide """ if hasattr(e, "exception"): ...
python
wandb/util.py
900
913
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
946
check_retry_conflict_or_gone
def check_retry_conflict_or_gone(e: Any) -> Optional[bool]: """Check if the exception is a conflict or gone type, so it can be retried or not. Returns: True - Should retry this operation False - Should not retry this operation None - No decision, let someone else decide """ if h...
python
wandb/util.py
916
931
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
947
make_check_retry_fn
def make_check_retry_fn( fallback_retry_fn: CheckRetryFnType, check_fn: Callable[[Exception], Optional[bool]], check_timedelta: Optional[timedelta] = None, ) -> CheckRetryFnType: """Return a check_retry_fn which can be used by lib.Retry(). Arguments: fallback_fn: Use this function if check_...
python
wandb/util.py
934
957
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
948
check_retry_fn
def check_retry_fn(e: Exception) -> Union[bool, timedelta]: check = check_fn(e) if check is None: return fallback_retry_fn(e) if check is False: return False if check_timedelta: return check_timedelta return True
python
wandb/util.py
947
955
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
949
find_runner
def find_runner(program: str) -> Union[None, list, List[str]]: """Return a command that will run program. Arguments: program: The string name of the program to try to run. Returns: commandline list of strings to run the program (eg. with subprocess.call()) or None """ if os.path.is...
python
wandb/util.py
960
980
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
950
downsample
def downsample(values: Sequence, target_length: int) -> list: """Downsample 1d values to target_length, including start and end. Algorithm just rounds index down. Values can be any sequence, including a generator. """ if not target_length > 1: raise UsageError("target_length must be > 1") ...
python
wandb/util.py
983
999
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
951
has_num
def has_num(dictionary: Mapping, key: Any) -> bool: return key in dictionary and isinstance(dictionary[key], numbers.Number)
python
wandb/util.py
1,002
1,003
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
952
get_log_file_path
def get_log_file_path() -> str: """Log file path used in error messages. It would probably be better if this pointed to a log file in a run directory. """ # TODO(jhr, cvp): refactor if wandb.run is not None: return wandb.run._settings.log_internal return os.path.join("wandb", "debug...
python
wandb/util.py
1,006
1,015
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
953
docker_image_regex
def docker_image_regex(image: str) -> Any: """Regex match for valid docker image names.""" if image: return re.match( r"^(?:(?=[^:\/]{1,253})(?!-)[a-zA-Z0-9-]{1,63}(?<!-)(?:\.(?!-)[a-zA-Z0-9-]{1,63}(?<!-))*(?::[0-9]{1,5})?/)?((?![._-])(?:[a-z0-9._-]*)(?<![._-])(?:/(?![._-])[a-z0-9._-]*(?<![....
python
wandb/util.py
1,018
1,025
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
954
image_from_docker_args
def image_from_docker_args(args: List[str]) -> Optional[str]: """Scan docker run args and attempt to find the most likely docker image argument. It excludes any arguments that start with a dash, and the argument after it if it isn't a boolean switch. This can be improved, we currently fallback gracefully w...
python
wandb/util.py
1,028
1,078
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
955
load_yaml
def load_yaml(file: Any) -> Any: return yaml.safe_load(file)
python
wandb/util.py
1,081
1,082
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
956
image_id_from_k8s
def image_id_from_k8s() -> Optional[str]: """Ping the k8s metadata service for the image id. Specify the KUBERNETES_NAMESPACE environment variable if your pods are not in the default namespace: - name: KUBERNETES_NAMESPACE valueFrom: fieldRef: fieldPath: metadata.namespace """ ...
python
wandb/util.py
1,085
1,120
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
957
async_call
def async_call( target: Callable, timeout: Optional[Union[int, float]] = None ) -> Callable: """Wrap a method to run in the background with an optional timeout. Returns a new method that will call the original with any args, waiting for upto timeout seconds. This new method blocks on the original and r...
python
wandb/util.py
1,123
1,158
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
958
wrapped_target
def wrapped_target(q: "queue.Queue", *args: Any, **kwargs: Any) -> Any: try: q.put(target(*args, **kwargs)) except Exception as e: q.put(e)
python
wandb/util.py
1,136
1,140
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
959
wrapper
def wrapper( *args: Any, **kwargs: Any ) -> Union[Tuple[Exception, "threading.Thread"], Tuple[None, "threading.Thread"]]: thread = threading.Thread( target=wrapped_target, args=(q,) + args, kwargs=kwargs ) thread.daemon = True thread.start() try: ...
python
wandb/util.py
1,142
1,156
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
960
read_many_from_queue
def read_many_from_queue( q: "queue.Queue", max_items: int, queue_timeout: Union[int, float] ) -> list: try: item = q.get(True, queue_timeout) except queue.Empty: return [] items = [item] for _ in range(max_items): try: item = q.get_nowait() except queue.E...
python
wandb/util.py
1,161
1,175
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
961
stopwatch_now
def stopwatch_now() -> float: """Get a time value for interval comparisons. When possible it is a monotonic clock to prevent backwards time issues. """ return time.monotonic()
python
wandb/util.py
1,178
1,183
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
962
class_colors
def class_colors(class_count: int) -> List[List[int]]: # make class 0 black, and the rest equally spaced fully saturated hues return [[0, 0, 0]] + [ colorsys.hsv_to_rgb(i / (class_count - 1.0), 1.0, 1.0) # type: ignore for i in range(class_count - 1) ]
python
wandb/util.py
1,186
1,191
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
963
_prompt_choice
def _prompt_choice( input_timeout: Optional[int] = None, jupyter: bool = False, ) -> str: input_fn: Callable = input prompt = term.LOG_STRING if input_timeout is not None: # delayed import to mitigate risk of timed_input complexity from wandb.sdk.lib import timed_input input...
python
wandb/util.py
1,194
1,214
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
964
prompt_choices
def prompt_choices( choices: Sequence[str], input_timeout: Optional[int] = None, jupyter: bool = False, ) -> str: """Allow a user to choose from a list of options.""" for i, choice in enumerate(choices): wandb.termlog(f"({i+1}) {choice}") idx = -1 while idx < 0 or idx > len(choices)...
python
wandb/util.py
1,217
1,240
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
965
guess_data_type
def guess_data_type(shape: Sequence[int], risky: bool = False) -> Optional[str]: """Infer the type of data based on the shape of the tensors. Arguments: shape (Sequence[int]): The shape of the data risky(bool): some guesses are more likely to be wrong. """ # (samples,) or (samples,logit...
python
wandb/util.py
1,243
1,264
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
966
download_file_from_url
def download_file_from_url( dest_path: str, source_url: str, api_key: Optional[str] = None ) -> None: response = requests.get(source_url, auth=("api", api_key), stream=True, timeout=5) # type: ignore response.raise_for_status() if os.sep in dest_path: filesystem.mkdir_exists_ok(os.path.dirname...
python
wandb/util.py
1,267
1,277
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
967
isatty
def isatty(ob: IO) -> bool: return hasattr(ob, "isatty") and ob.isatty()
python
wandb/util.py
1,280
1,281
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
968
to_human_size
def to_human_size(size: int, units: Optional[List[Tuple[str, Any]]] = None) -> str: units = units or POW_10_BYTES unit, value = units[0] factor = round(float(size) / value, 1) return ( f"{factor}{unit}" if factor < 1024 or len(units) == 1 else to_human_size(size, units[1:]) )
python
wandb/util.py
1,284
1,292
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
969
from_human_size
def from_human_size(size: str, units: Optional[List[Tuple[str, Any]]] = None) -> int: units = units or POW_10_BYTES units_dict = {unit.upper(): value for (unit, value) in units} regex = re.compile( r"(\d+\.?\d*)\s*({})?".format("|".join(units_dict.keys())), re.IGNORECASE ) match = re.match(r...
python
wandb/util.py
1,295
1,308
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
970
auto_project_name
def auto_project_name(program: Optional[str]) -> str: # if we're in git, set project name to git repo name + relative path within repo root_dir = wandb.wandb_sdk.lib.git.GitRepo().root_dir if root_dir is None: return "uncategorized" # On windows, GitRepo returns paths in unix style, but os.path ...
python
wandb/util.py
1,311
1,331
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
971
parse_sweep_id
def parse_sweep_id(parts_dict: dict) -> Optional[str]: """In place parse sweep path from parts dict. Arguments: parts_dict (dict): dict(entity=,project=,name=). Modifies dict inplace. Returns: None or str if there is an error """ entity = None project = None sweep_id = par...
python
wandb/util.py
1,334
1,364
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
972
to_forward_slash_path
def to_forward_slash_path(path: str) -> LogicalFilePathStr: if platform.system() == "Windows": path = path.replace("\\", "/") return LogicalFilePathStr(path)
python
wandb/util.py
1,367
1,370
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
973
to_native_slash_path
def to_native_slash_path(path: str) -> FilePathStr: return FilePathStr(path.replace("/", os.sep))
python
wandb/util.py
1,373
1,374
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
974
check_and_warn_old
def check_and_warn_old(files: List[str]) -> bool: if "wandb-metadata.json" in files: wandb.termwarn("These runs were logged with a previous version of wandb.") wandb.termwarn( "Run pip install wandb<0.10.0 to get the old library and sync your runs." ) return True retu...
python
wandb/util.py
1,377
1,384
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
975
__init__
def __init__(self) -> None: self.modules: Dict[str, ModuleType] = dict() self.on_import: Dict[str, list] = dict()
python
wandb/util.py
1,388
1,390
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
976
add
def add(self, fullname: str, on_import: Callable) -> None: self.on_import.setdefault(fullname, []).append(on_import)
python
wandb/util.py
1,392
1,393
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
977
install
def install(self) -> None: sys.meta_path.insert(0, self) # type: ignore
python
wandb/util.py
1,395
1,396
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
978
uninstall
def uninstall(self) -> None: sys.meta_path.remove(self) # type: ignore
python
wandb/util.py
1,398
1,399
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
979
find_module
def find_module( self, fullname: str, path: Optional[str] = None ) -> Optional["ImportMetaHook"]: if fullname in self.on_import: return self return None
python
wandb/util.py
1,401
1,406
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
980
load_module
def load_module(self, fullname: str) -> ModuleType: self.uninstall() mod = importlib.import_module(fullname) self.install() self.modules[fullname] = mod on_imports = self.on_import.get(fullname) if on_imports: for f in on_imports: f() r...
python
wandb/util.py
1,408
1,417
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
981
get_modules
def get_modules(self) -> Tuple[str, ...]: return tuple(self.modules)
python
wandb/util.py
1,419
1,420
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
982
get_module
def get_module(self, module: str) -> ModuleType: return self.modules[module]
python
wandb/util.py
1,422
1,423
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
983
add_import_hook
def add_import_hook(fullname: str, on_import: Callable) -> None: global _import_hook if _import_hook is None: _import_hook = ImportMetaHook() _import_hook.install() _import_hook.add(fullname, on_import)
python
wandb/util.py
1,429
1,434
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
984
host_from_path
def host_from_path(path: Optional[str]) -> str: """Return the host of the path.""" url = urllib.parse.urlparse(path) return str(url.netloc)
python
wandb/util.py
1,437
1,440
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
985
uri_from_path
def uri_from_path(path: Optional[str]) -> str: """Return the URI of the path.""" url = urllib.parse.urlparse(path) uri = url.path if url.path[0] != "/" else url.path[1:] return str(uri)
python
wandb/util.py
1,443
1,447
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
986
is_unicode_safe
def is_unicode_safe(stream: TextIO) -> bool: """Return True if the stream supports UTF-8.""" encoding = getattr(stream, "encoding", None) return encoding.lower() in {"utf-8", "utf_8"} if encoding else False
python
wandb/util.py
1,450
1,453
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
987
_has_internet
def _has_internet() -> bool: """Attempt to open a DNS connection to Googles root servers.""" try: s = socket.create_connection(("8.8.8.8", 53), 0.5) s.close() return True except OSError: return False
python
wandb/util.py
1,456
1,463
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
988
rand_alphanumeric
def rand_alphanumeric( length: int = 8, rand: Optional[Union[ModuleType, random.Random]] = None ) -> str: wandb.termerror("rand_alphanumeric is deprecated, use 'secrets.token_hex'") rand = rand or random return "".join(rand.choice("0123456789ABCDEF") for _ in range(length))
python
wandb/util.py
1,466
1,471
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
989
fsync_open
def fsync_open( path: Union[pathlib.Path, str], mode: str = "w", encoding: Optional[str] = None ) -> Generator[IO[Any], None, None]: """Open a path for I/O and guarante that the file is flushed and synced.""" with open(path, mode, encoding=encoding) as f: yield f f.flush() os.fsync(...
python
wandb/util.py
1,475
1,483
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
990
_is_kaggle
def _is_kaggle() -> bool: return ( os.getenv("KAGGLE_KERNEL_RUN_TYPE") is not None or "kaggle_environments" in sys.modules )
python
wandb/util.py
1,486
1,490
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
991
_is_likely_kaggle
def _is_likely_kaggle() -> bool: # Telemetry to mark first runs from Kagglers. return ( _is_kaggle() or os.path.exists( os.path.expanduser(os.path.join("~", ".kaggle", "kaggle.json")) ) or "kaggle" in sys.modules )
python
wandb/util.py
1,493
1,501
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
992
_is_databricks
def _is_databricks() -> bool: # check if we are running inside a databricks notebook by # inspecting sys.modules, searching for dbutils and verifying that # it has the appropriate structure if "dbutils" in sys.modules: dbutils = sys.modules["dbutils"] if hasattr(dbutils, "shell"): ...
python
wandb/util.py
1,504
1,517
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
993
_is_py_path
def _is_py_path(path: str) -> bool: return path.endswith(".py")
python
wandb/util.py
1,520
1,521
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
994
sweep_config_err_text_from_jsonschema_violations
def sweep_config_err_text_from_jsonschema_violations(violations: List[str]) -> str: """Consolidate schema violation strings from wandb/sweeps into a single string. Parameters ---------- violations: list of str The warnings to render. Returns: ------- violation: str The cons...
python
wandb/util.py
1,524
1,547
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
995
handle_sweep_config_violations
def handle_sweep_config_violations(warnings: List[str]) -> None: """Echo sweep config schema violation warnings from Gorilla to the terminal. Parameters ---------- warnings: list of str The warnings to render. """ warning = sweep_config_err_text_from_jsonschema_violations(warnings) ...
python
wandb/util.py
1,550
1,560
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
996
_log_thread_stacks
def _log_thread_stacks() -> None: """Log all threads, useful for debugging.""" thread_map = {t.ident: t.name for t in threading.enumerate()} for thread_id, frame in sys._current_frames().items(): logger.info( f"\n--- Stack for thread {thread_id} {thread_map.get(thread_id, 'unknown')} --...
python
wandb/util.py
1,563
1,574
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
997
check_windows_valid_filename
def check_windows_valid_filename(path: Union[int, str]) -> bool: return not bool(re.search(RE_WINFNAMES, path)) # type: ignore
python
wandb/util.py
1,577
1,578
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
998
artifact_to_json
def artifact_to_json( artifact: Union["wandb.sdk.wandb_artifacts.Artifact", "wandb.apis.public.Artifact"] ) -> Dict[str, Any]: # public.Artifact has the _sequence name, instances of wandb.Artifact # just have the name if hasattr(artifact, "_sequence_name"): sequence_name = artifact._sequence_nam...
python
wandb/util.py
1,581
1,598
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
999
check_dict_contains_nested_artifact
def check_dict_contains_nested_artifact(d: dict, nested: bool = False) -> bool: for item in d.values(): if isinstance(item, dict): contains_artifacts = check_dict_contains_nested_artifact(item, True) if contains_artifacts: return True elif ( isinst...
python
wandb/util.py
1,601
1,613
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
1,000
load_json_yaml_dict
def load_json_yaml_dict(config: str) -> Any: ext = os.path.splitext(config)[-1] if ext == ".json": with open(config) as f: return json.load(f) elif ext == ".yaml": with open(config) as f: return yaml.safe_load(f) else: try: return json.loads(co...
python
wandb/util.py
1,616
1,628
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }