id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
34,945 | import os
import time
from flask import Flask, jsonify, request, Response
import sqlalchemy.exc
from flask_sqlalchemy import SQLAlchemy
def missing_field():
response_data = {
"id": "123",
"name": "Alice",
# "age" field is missing
}
return jsonify(response_data), 200 | null |
34,946 | import os
import time
from flask import Flask, jsonify, request, Response
import sqlalchemy.exc
from flask_sqlalchemy import SQLAlchemy
data_db = {"0": "Data for ID 0"}
def undocumented_status_code():
id = request.args.get("id")
if id is None:
return jsonify({"error": "ID is required"}), 400
data ... | null |
34,947 | import os
import time
from flask import Flask, jsonify, request, Response
import sqlalchemy.exc
from flask_sqlalchemy import SQLAlchemy
MAX_ITEMS = 120
DELAY_PER_ITEM = 0.001
def unbounded_result_set():
limit = min(request.args.get("limit", default=MAX_ITEMS, type=int), MAX_ITEMS)
if limit <= 0:
retur... | null |
34,948 | import os
import time
from flask import Flask, jsonify, request, Response
import sqlalchemy.exc
from flask_sqlalchemy import SQLAlchemy
MAX_N = 100000
def generate_fibonacci(n):
# The loop generates Fibonacci numbers inefficiently, leading to increased response times for large n.
fib_sequence = [0, 1]
while... | null |
34,949 | import os
import time
from flask import Flask, jsonify, request, Response
import sqlalchemy.exc
from flask_sqlalchemy import SQLAlchemy
def openapi():
return Response(RAW_SCHEMA, content_type="application/json") | null |
34,950 | import os
import time
from flask import Flask, jsonify, request, Response
import sqlalchemy.exc
from flask_sqlalchemy import SQLAlchemy
PORT = int(os.getenv("FLASK_RUN_PORT", 5123))
def ui():
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link href=... | null |
34,951 | import os
import time
from flask import Flask, jsonify, request, Response
import sqlalchemy.exc
from flask_sqlalchemy import SQLAlchemy
def handle_500(error):
exception = error.original_exception
if exception:
error = str(exception)
else:
error = None
return jsonify({"success": False, "... | null |
34,952 | import csv
import sys
import os
import logging
from dotenv import load_dotenv
from pathlib import Path
import sqlalchemy as db
from datetime import datetime
from sqlalchemy.orm import sessionmaker
from models import Account, Channel, ChatUser, Keyword, Message, Monitor, Notification
Session = None
session = None
SERVER... | null |
34,953 | import logging
import os
import re
import ffmpeg
import numpy as np
import opencc
import srt
def load_audio(file: str, sr: int = 16000) -> np.ndarray:
try:
out, _ = (
ffmpeg.input(file, threads=0)
.output("-", format="s16le", acodec="pcm_s16le", ac=1, ar=sr)
.run(cmd=["f... | null |
34,954 | import logging
import os
import re
import ffmpeg
import numpy as np
import opencc
import srt
def is_audio(filename):
_, ext = os.path.splitext(filename)
return ext in [".ogg", ".wav", ".mp3", ".flac", ".m4a"] | null |
34,955 | import logging
import os
import re
import ffmpeg
import numpy as np
import opencc
import srt
def change_ext(filename, new_ext):
# Change the extension of filename to new_ext
base, _ = os.path.splitext(filename)
if not new_ext.startswith("."):
new_ext = "." + new_ext
return base + new_ext | null |
34,956 | import logging
import os
import re
import ffmpeg
import numpy as np
import opencc
import srt
def add_cut(filename):
# Add cut mark to the filename
base, ext = os.path.splitext(filename)
if base.endswith("_cut"):
base = base[:-4] + "_" + base[-4:]
else:
base += "_cut"
return base + e... | null |
34,957 | import logging
import os
import re
import ffmpeg
import numpy as np
import opencc
import srt
def expand_segments(segments, expand_head, expand_tail, total_length):
# Pad head and tail for each time segment
results = []
for i in range(len(segments)):
t = segments[i]
start = max(t["start"] - ... | null |
34,958 | import logging
import os
import re
import ffmpeg
import numpy as np
import opencc
import srt
def remove_short_segments(segments, threshold):
# Remove segments whose length < threshold
return [s for s in segments if s["end"] - s["start"] > threshold] | null |
34,959 | import logging
import os
import re
import ffmpeg
import numpy as np
import opencc
import srt
def merge_adjacent_segments(segments, threshold):
# Merge two adjacent segments if their distance < threshold
results = []
i = 0
while i < len(segments):
s = segments[i]
for j in range(i + 1, le... | null |
34,960 | import logging
import os
import re
import ffmpeg
import numpy as np
import opencc
import srt
def compact_rst(sub_fn, encoding):
cc = opencc.OpenCC("t2s")
base, ext = os.path.splitext(sub_fn)
COMPACT = "_compact"
if ext != ".srt":
logging.fatal("only .srt file is supported")
if base.endswi... | null |
34,961 | import logging
import os
import re
import ffmpeg
import numpy as np
import opencc
import srt
def is_video(filename):
_, ext = os.path.splitext(filename)
return ext in [".mp4", ".mov", ".mkv", ".avi", ".flv", ".f4v", ".webm"]
class MD:
def __init__(self, filename, encoding):
self.lines = []
s... | null |
34,962 | import os.path
import argparse
import numpy as np
from utils.logger import setup_logger
from utils.manipulator import train_boundary
The provided code snippet includes necessary dependencies for implementing the `parse_args` function. Write a Python function `def parse_args()` to solve the following problem:
Parses ar... | Parses arguments. |
34,963 | import os.path
import argparse
from collections import defaultdict
import cv2
import numpy as np
from tqdm import tqdm
from models.model_settings import MODEL_POOL
from models.pggan_generator import PGGANGenerator
from models.stylegan_generator import StyleGANGenerator
from utils.logger import setup_logger
MODEL_POOL ... | Parses arguments. |
34,964 | import os.path
import argparse
import cv2
import numpy as np
from tqdm import tqdm
from models.model_settings import MODEL_POOL
from models.pggan_generator import PGGANGenerator
from models.stylegan_generator import StyleGANGenerator
from utils.logger import setup_logger
from utils.manipulator import linear_interpolate... | Parses arguments. |
34,965 | import os
import time
import numpy as np
import tensorflow as tf
import config
import tfutil
import dataset
import misc
def setup_snapshot_image_grid(G, training_set,
size = '1080p', # '1080p' = to be viewed on 1080p display, '4k' = to be viewed on 4k display.
layout = 'random'): # 'random' = grid c... | null |
34,966 | import pickle
import inspect
import numpy as np
import tfutil
import networks
theano_gan_remap = {
'G_paper': 'G_paper',
'G_progressive_8': 'G_paper',
'D_paper': 'D_paper',
'D_progressive_8': 'D_paper'}
def patch_theano_gan(state):
if 'version' in state or state['build_func_spec... | null |
34,967 | import pickle
import inspect
import numpy as np
import tfutil
import networks
def ignore_unknown_theano_network(state):
if 'version' in state:
return state
print('Ignoring unknown Theano network:', state['build_func_spec']['func'])
return {
'version': 2,
'name': ... | null |
34,968 | import os
import sys
import inspect
import importlib
import imp
import numpy as np
from collections import OrderedDict
import tensorflow as tf
def shape_to_list(shape):
return [dim.value for dim in shape] | null |
34,969 | import os
import sys
import inspect
import importlib
import imp
import numpy as np
from collections import OrderedDict
import tensorflow as tf
def lerp_clip(a, b, t):
with tf.name_scope('LerpClip'):
return a + (b - a) * tf.clip_by_value(t, 0.0, 1.0) | null |
34,970 | import os
import sys
import inspect
import importlib
import imp
import numpy as np
from collections import OrderedDict
import tensorflow as tf
def run(*args, **kwargs): # Run the specified ops in the default session.
return tf.get_default_session().run(*args, **kwargs)
def is_tf_expression(x):
return isinstance... | null |
34,971 | import numpy as np
import scipy.ndimage
def get_descriptors_for_minibatch(minibatch, nhood_size, nhoods_per_image):
S = minibatch.shape # (minibatch, channel, height, width)
assert len(S) == 4 and S[1] == 3
N = nhoods_per_image * S[0]
H = nhood_size // 2
nhood, chan, x, y = np.ogrid[0:N, 0:3, -H:H+... | null |
34,972 | import numpy as np
import scipy.ndimage
def finalize_descriptors(desc):
if isinstance(desc, list):
desc = np.concatenate(desc, axis=0)
assert desc.ndim == 4 # (neighborhood, channel, height, width)
desc -= np.mean(desc, axis=(0, 2, 3), keepdims=True)
desc /= np.std(desc, axis=(0, 2, 3), keepdim... | null |
34,973 | import numpy as np
import scipy.ndimage
def sliced_wasserstein(A, B, dir_repeats, dirs_per_repeat):
assert A.ndim == 2 and A.shape == B.shape # (neighborhood, descriptor_component)
results = []
for repeat in range(dir_repeats):
dirs = np.random.randn(A.shape[1], dirs_per_r... | null |
34,974 | import numpy as np
import scipy.ndimage
def downscale_minibatch(minibatch, lod):
if lod == 0:
return minibatch
t = minibatch.astype(np.float32)
for i in range(lod):
t = (t[:, :, 0::2, 0::2] + t[:, :, 0::2, 1::2] + t[:, :, 1::2, 0::2] + t[:, :, 1::2, 1::2]) * 0.25
return np.round(t).clip... | null |
34,975 | import numpy as np
import scipy.ndimage
def pyr_down(minibatch): # matches cv2.pyrDown()
assert minibatch.ndim == 4
return scipy.ndimage.convolve(minibatch, gaussian_filter[np.newaxis, np.newaxis, :, :], mode='mirror')[:, :, ::2, ::2]
def pyr_up(minibatch): # matches cv2.pyrUp()
assert minibatch.ndim == 4
... | null |
34,976 | import numpy as np
import scipy.ndimage
def pyr_up(minibatch):
def reconstruct_laplacian_pyramid(pyramid):
minibatch = pyramid[-1]
for level in pyramid[-2::-1]:
minibatch = pyr_up(minibatch) + level
return minibatch | null |
34,977 | from __future__ import absolute_import, division, print_function
import numpy as np
import scipy as sp
import os
import gzip, pickle
import tensorflow as tf
from scipy.misc import imread
import pathlib
import urllib
def create_inception_graph(pth):
"""Creates a graph from saved GraphDef file."""
# Creates graph... | Calculates the FID of two paths. |
34,978 | import numpy as np
from scipy import signal
from scipy.ndimage.filters import convolve
def _SSIMForMultiScale(img1, img2, max_val=255, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03):
"""Return the Structural Similarity Map between `img1` and `img2`.
This function attempts to match the functionality of ssim... | Return the MS-SSIM score between `img1` and `img2`. This function implements Multi-Scale Structural Similarity (MS-SSIM) Image Quality Assessment according to Zhou Wang's paper, "Multi-scale structural similarity for image quality assessment" (2003). Link: https://ece.uwaterloo.ca/~z70wang/publications/msssim.pdf Autho... |
34,979 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import sys
import tarfile
import numpy as np
from six.moves import urllib
import tensorflow as tf
import glob
import scipy.misc
import math
import sys
softmax = None
def get_inception_score(image... | null |
34,980 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import sys
import tarfile
import numpy as np
from six.moves import urllib
import tensorflow as tf
import glob
import scipy.misc
import math
import sys
MODEL_DIR = '/tmp/imagenet'
DATA_URL = 'http:... | null |
34,981 | import os
import time
import re
import bisect
from collections import OrderedDict
import numpy as np
import tensorflow as tf
import scipy.ndimage
import scipy.misc
import config
import misc
import tfutil
import train
import dataset
; ;
;;;;;;
;
def generate_fake_images(run_id, snapshot=None, grid_size=[1,1... | null |
34,982 | import os
import time
import re
import bisect
from collections import OrderedDict
import numpy as np
import tensorflow as tf
import scipy.ndimage
import scipy.misc
import config
import misc
import tfutil
import train
import dataset
; ;
;;;;;;
;
def generate_interpolation_video(run_id, snapshot=None, grid_s... | null |
34,983 | import os
import time
import re
import bisect
from collections import OrderedDict
import numpy as np
import tensorflow as tf
import scipy.ndimage
import scipy.misc
import config
import misc
import tfutil
import train
import dataset
; ;
;;;;;;
;
def generate_training_video(run_id, duration_sec=20.0, time_wa... | null |
34,984 | import os
import time
import re
import bisect
from collections import OrderedDict
import numpy as np
import tensorflow as tf
import scipy.ndimage
import scipy.misc
import config
import misc
import tfutil
import train
import dataset
; ;
;;;;;;
;
def evaluate_metrics(run_id, log, metrics, num_images, real_pa... | null |
34,985 | import os
import sys
import glob
import datetime
import pickle
import re
import numpy as np
from collections import OrderedDict
import scipy.ndimage
import PIL.Image
import config
import dataset
import legacy
def convert_to_pil_image(image, drange=[0,1]):
assert image.ndim == 2 or image.ndim == 3
if image.ndim... | null |
34,986 | import os
import sys
import glob
import datetime
import pickle
import re
import numpy as np
from collections import OrderedDict
import scipy.ndimage
import PIL.Image
import config
import dataset
import legacy
class OutputLogger(object):
def __init__(self):
def set_log_file(self, filename, mode='wt'):
de... | null |
34,987 | import numpy as np
import tensorflow as tf
import tfutil
def fp32(*values):
if len(values) == 1 and isinstance(values[0], tuple):
values = values[0]
values = tuple(tf.cast(v, tf.float32) for v in values)
return values if len(values) >= 2 else values[0]
def G_wgan_acgan(G, D, opt, training_set, mini... | null |
34,988 | import numpy as np
import tensorflow as tf
import tfutil
def fp32(*values):
if len(values) == 1 and isinstance(values[0], tuple):
values = values[0]
values = tuple(tf.cast(v, tf.float32) for v in values)
return values if len(values) >= 2 else values[0]
def D_wgangp_acgan(G, D, opt, training_set, mi... | null |
34,989 | import numpy as np
import tensorflow as tf
def lerp(a, b, t): return a + (b - a) * t
def lerp_clip(a, b, t): return a + (b - a) * tf.clip_by_value(t, 0.0, 1.0)
def cset(cur_lambda, new_cond, new_lambda): return lambda: tf.cond(new_cond, new_lambda, cur_lambda)
def dense(x, fmaps, gain=np.sqrt(2), use_wscale=False):
... | null |
34,990 | import numpy as np
import tensorflow as tf
def lerp(a, b, t): return a + (b - a) * t
def lerp_clip(a, b, t): return a + (b - a) * tf.clip_by_value(t, 0.0, 1.0)
def cset(cur_lambda, new_cond, new_lambda): return lambda: tf.cond(new_cond, new_lambda, cur_lambda)
def dense(x, fmaps, gain=np.sqrt(2), use_wscale=False):
... | null |
34,991 | import os
import glob
import numpy as np
import tensorflow as tf
import tfutil
def parse_tfrecord_tf(record):
features = tf.parse_single_example(record, features={
'shape': tf.FixedLenFeature([3], tf.int64),
'data': tf.FixedLenFeature([], tf.string)})
data = tf.decode_raw(features['data'], tf.u... | null |
34,992 | import os
import glob
import numpy as np
import tensorflow as tf
import tfutil
def parse_tfrecord_np(record):
ex = tf.train.Example()
ex.ParseFromString(record)
shape = ex.features.feature['shape'].int64_list.value
data = ex.features.feature['data'].bytes_list.value[0]
return np.fromstring(data, np... | null |
34,993 | import os
import sys
import glob
import argparse
import threading
import six.moves.queue as Queue
import traceback
import numpy as np
import tensorflow as tf
import PIL.Image
import tfutil
import dataset
def display(tfrecord_dir):
print('Loading dataset "%s"' % tfrecord_dir)
tfutil.init_tf({'gpu_options.allow_... | null |
34,994 | import os
import sys
import glob
import argparse
import threading
import six.moves.queue as Queue
import traceback
import numpy as np
import tensorflow as tf
import PIL.Image
import tfutil
import dataset
def extract(tfrecord_dir, output_dir):
print('Loading dataset "%s"' % tfrecord_dir)
tfutil.init_tf({'gpu_op... | null |
34,995 | import os
import sys
import glob
import argparse
import threading
import six.moves.queue as Queue
import traceback
import numpy as np
import tensorflow as tf
import PIL.Image
import tfutil
import dataset
def compare(tfrecord_dir_a, tfrecord_dir_b, ignore_labels):
max_label_size = 0 if ignore_labels else 'full'
... | null |
34,996 | import os
import sys
import glob
import argparse
import threading
import six.moves.queue as Queue
import traceback
import numpy as np
import tensorflow as tf
import PIL.Image
import tfutil
import dataset
class TFRecordExporter:
def __init__(self, tfrecord_dir, expected_images, print_progress=True, progress_interva... | null |
34,997 | import os
import sys
import glob
import argparse
import threading
import six.moves.queue as Queue
import traceback
import numpy as np
import tensorflow as tf
import PIL.Image
import tfutil
import dataset
class TFRecordExporter:
def __init__(self, tfrecord_dir, expected_images, print_progress=True, progress_interva... | null |
34,998 | import os
import sys
import glob
import argparse
import threading
import six.moves.queue as Queue
import traceback
import numpy as np
import tensorflow as tf
import PIL.Image
import tfutil
import dataset
class TFRecordExporter:
def __init__(self, tfrecord_dir, expected_images, print_progress=True, progress_interval... | null |
34,999 | import os
import sys
import glob
import argparse
import threading
import six.moves.queue as Queue
import traceback
import numpy as np
import tensorflow as tf
import PIL.Image
import tfutil
import dataset
class TFRecordExporter:
def __init__(self, tfrecord_dir, expected_images, print_progress=True, progress_interval... | null |
35,000 | import os
import sys
import glob
import argparse
import threading
import six.moves.queue as Queue
import traceback
import numpy as np
import tensorflow as tf
import PIL.Image
import tfutil
import dataset
class TFRecordExporter:
def __init__(self, tfrecord_dir, expected_images, print_progress=True, progress_interval... | null |
35,001 | import os
import sys
import glob
import argparse
import threading
import six.moves.queue as Queue
import traceback
import numpy as np
import tensorflow as tf
import PIL.Image
import tfutil
import dataset
class TFRecordExporter:
def __init__(self, tfrecord_dir, expected_images, print_progress=True, progress_interval... | null |
35,002 | import os
import sys
import glob
import argparse
import threading
import six.moves.queue as Queue
import traceback
import numpy as np
import tensorflow as tf
import PIL.Image
import tfutil
import dataset
def error(msg):
class TFRecordExporter:
def __init__(self, tfrecord_dir, expected_images, print_progress=True, ... | null |
35,003 | import os
import sys
import glob
import argparse
import threading
import six.moves.queue as Queue
import traceback
import numpy as np
import tensorflow as tf
import PIL.Image
import tfutil
import dataset
def error(msg):
print('Error: ' + msg)
exit(1)
class TFRecordExporter:
def __init__(self, tfrecord_dir, ... | null |
35,004 | import os
import sys
import glob
import argparse
import threading
import six.moves.queue as Queue
import traceback
import numpy as np
import tensorflow as tf
import PIL.Image
import tfutil
import dataset
def error(msg):
print('Error: ' + msg)
exit(1)
class TFRecordExporter:
def __init__(self, tfrecord_dir, ... | null |
35,005 | import os
import sys
import glob
import argparse
import threading
import six.moves.queue as Queue
import traceback
import numpy as np
import tensorflow as tf
import PIL.Image
import tfutil
import dataset
class TFRecordExporter:
def __init__(self, tfrecord_dir, expected_images, print_progress=True, progress_interval... | null |
35,006 | import os
import sys
import glob
import argparse
import threading
import six.moves.queue as Queue
import traceback
import numpy as np
import tensorflow as tf
import PIL.Image
import tfutil
import dataset
def execute_cmdline(argv):
prog = argv[0]
parser = argparse.ArgumentParser(
prog = prog,
... | null |
35,007 | import ctypes
import fnmatch
import importlib
import inspect
import numpy as np
import os
import shutil
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import uuid
from distutils.util import strtobool
from typing import Any, List, Tuple, Union
The provid... | Calculate the product of the tuple elements. |
35,008 | import ctypes
import fnmatch
import importlib
import inspect
import numpy as np
import os
import shutil
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import uuid
from distutils.util import strtobool
from typing import Any, List, Tuple, Union
_str_to_cty... | Given a type name string (or an object having a __name__ attribute), return matching Numpy and ctypes types that have the same size in bytes. |
35,009 | import ctypes
import fnmatch
import importlib
import inspect
import numpy as np
import os
import shutil
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import uuid
from distutils.util import strtobool
from typing import Any, List, Tuple, Union
def is_pic... | null |
35,010 | import ctypes
import fnmatch
import importlib
import inspect
import numpy as np
import os
import shutil
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import uuid
from distutils.util import strtobool
from typing import Any, List, Tuple, Union
def is_top_... | Return the fully-qualified name of a top-level function. |
35,011 | import ctypes
import fnmatch
import importlib
import inspect
import numpy as np
import os
import shutil
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import uuid
from distutils.util import strtobool
from typing import Any, List, Tuple, Union
def is_url(... | Download the given URL and return a binary-mode file object to access the data. |
35,012 | import copy
import io
import os
import pathlib
import pickle
import platform
import pprint
import re
import shutil
import time
import traceback
import zipfile
from enum import Enum
from .. import util
from ..util import EasyDict
class PathType(Enum):
"""Determines in which format should a path be formatted.
WIN... | Convert a normal path to template and the convert it back to a normal path with given path type. |
35,013 | import copy
import io
import os
import pathlib
import pickle
import platform
import pprint
import re
import shutil
import time
import traceback
import zipfile
from enum import Enum
from .. import util
from ..util import EasyDict
_user_name_override = None
The provided code snippet includes necessary dependencies for i... | Set the global username override value. |
35,014 | import copy
import io
import os
import pathlib
import pickle
import platform
import pprint
import re
import shutil
import time
import traceback
import zipfile
from enum import Enum
from .. import util
from ..util import EasyDict
class SubmitTarget(Enum):
"""The target where the function should be run.
LOCAL: Ru... | Create a run dir, gather files related to the run, copy files to the run dir, and launch the run in appropriate place. |
35,015 | # import os
import numpy as np
import tensorflow as tf
from typing import Any, Iterable, List, Union
TfExpression = Union[tf.Tensor, tf.Variable, tf.Operation]
TfExpressionEx = Union[TfExpression, int, float, np.ndarray]
The provided code snippet includes necessary dependencies for implementing the `flatten` function... | Shortcut function for flattening a tensor. |
35,016 | # import os
import numpy as np
import tensorflow as tf
from typing import Any, Iterable, List, Union
TfExpression = Union[tf.Tensor, tf.Variable, tf.Operation]
TfExpressionEx = Union[TfExpression, int, float, np.ndarray]
The provided code snippet includes necessary dependencies for implementing the `log2` function. W... | Logarithm in base 2. |
35,017 | # import os
import numpy as np
import tensorflow as tf
from typing import Any, Iterable, List, Union
TfExpression = Union[tf.Tensor, tf.Variable, tf.Operation]
TfExpressionEx = Union[TfExpression, int, float, np.ndarray]
The provided code snippet includes necessary dependencies for implementing the `exp2` function. W... | Exponent in base 2. |
35,018 | # import os
import numpy as np
import tensorflow as tf
from typing import Any, Iterable, List, Union
TfExpressionEx = Union[TfExpression, int, float, np.ndarray]
The provided code snippet includes necessary dependencies for implementing the `lerp` function. Write a Python function `def lerp(a: TfExpressionEx, b: TfEx... | Linear interpolation. |
35,019 | # import os
import numpy as np
import tensorflow as tf
from typing import Any, Iterable, List, Union
TfExpression = Union[tf.Tensor, tf.Variable, tf.Operation]
TfExpressionEx = Union[TfExpression, int, float, np.ndarray]
The provided code snippet includes necessary dependencies for implementing the `lerp_clip` functi... | Linear interpolation with clip. |
35,020 | # import os
import numpy as np
import tensorflow as tf
from typing import Any, Iterable, List, Union
The provided code snippet includes necessary dependencies for implementing the `absolute_variable_scope` function. Write a Python function `def absolute_variable_scope(scope: str, **kwargs) -> tf.variable_scope` to so... | Forcefully enter the specified variable scope, ignoring any surrounding scopes. |
35,021 | # import os
import numpy as np
import tensorflow as tf
from typing import Any, Iterable, List, Union
def _sanitize_tf_config(config_dict: dict = None) -> dict:
# Defaults.
cfg = dict()
cfg["rnd.np_random_seed"] = None # Random seed for NumPy. None = keep as is.
cfg["rnd.tf_random_see... | Initialize TensorFlow session using good default settings. |
35,022 | # import os
import numpy as np
import tensorflow as tf
from typing import Any, Iterable, List, Union
def assert_tf_initialized():
"""Check that TensorFlow session has been initialized."""
if tf.get_default_session() is None:
raise RuntimeError("No default TensorFlow session found. Please call dnnlib.tf... | Create tf.Variable with large initial value without bloating the tf graph. |
35,023 | # import os
import numpy as np
import tensorflow as tf
from typing import Any, Iterable, List, Union
The provided code snippet includes necessary dependencies for implementing the `convert_images_from_uint8` function. Write a Python function `def convert_images_from_uint8(images, drange=[-1,1], nhwc_to_nchw=False)` t... | Convert a minibatch of images from uint8 to float32 with configurable dynamic range. Can be used as an input transformation for Network.run(). |
35,024 | # import os
import numpy as np
import tensorflow as tf
from typing import Any, Iterable, List, Union
The provided code snippet includes necessary dependencies for implementing the `convert_images_to_uint8` function. Write a Python function `def convert_images_to_uint8(images, drange=[-1,1], nchw_to_nhwc=False, shrink... | Convert a minibatch of images from float32 to uint8 with configurable dynamic range. Can be used as an output transformation for Network.run(). |
35,025 | # import types
import inspect
import re
import uuid
import sys
import numpy as np
import tensorflow as tf
from collections import OrderedDict
from typing import Any, List, Tuple, Union
from . import tfutil
from .. import util
from .tfutil import TfExpression, TfExpressionEx
_import_handlers = []
The provided code sni... | Function decorator for declaring custom import handlers. |
35,026 | # import types
import inspect
import re
import uuid
import sys
import numpy as np
import tensorflow as tf
from collections import OrderedDict
from typing import Any, List, Tuple, Union
from . import tfutil
from .. import util
from .tfutil import TfExpression, TfExpressionEx
_print_legacy_warning = True
def _legacy_out... | null |
35,027 | import dnnlib
from dnnlib import EasyDict
import dnnlib.tflib as tflib
import config
from metrics import metric_base
from training import misc
def run_pickle(submit_config, metric_args, network_pkl, dataset_args, mirror_augment):
ctx = dnnlib.RunContext(submit_config)
tflib.init_tf()
print('Evaluating %s m... | null |
35,028 | import dnnlib
from dnnlib import EasyDict
import dnnlib.tflib as tflib
import config
from metrics import metric_base
from training import misc
def run_snapshot(submit_config, metric_args, run_id, snapshot):
ctx = dnnlib.RunContext(submit_config)
tflib.init_tf()
print('Evaluating %s metric on run_id %s, sna... | null |
35,029 | import dnnlib
from dnnlib import EasyDict
import dnnlib.tflib as tflib
import config
from metrics import metric_base
from training import misc
def run_all_snapshots(submit_config, metric_args, run_id):
ctx = dnnlib.RunContext(submit_config)
tflib.init_tf()
print('Evaluating %s metric on all snapshots of ru... | null |
35,030 | import numpy as np
import tensorflow as tf
import dnnlib.tflib as tflib
from metrics import metric_base
from training import misc
def normalize(v):
def slerp(a, b, t):
a = normalize(a)
b = normalize(b)
d = tf.reduce_sum(a * b, axis=-1, keepdims=True)
p = t * tf.math.acos(d)
c = normalize(b - d * a)... | null |
35,031 | from collections import defaultdict
import numpy as np
import sklearn.svm
import tensorflow as tf
import dnnlib.tflib as tflib
from metrics import metric_base
from training import misc
def prob_normalize(p):
p = np.asarray(p).astype(np.float32)
assert len(p.shape) == 2
return p / np.sum(p)
def mutual_inform... | null |
35,032 | import os
import numpy as np
import tensorflow as tf
import dnnlib
import dnnlib.tflib as tflib
from dnnlib.tflib.autosummary import autosummary
import config
import train
from training import dataset
from training import misc
from metrics import metric_base
def process_reals(x, lod, mirror_augment, drange_data, drange... | null |
35,033 | import os
import glob
import pickle
import re
import numpy as np
from collections import defaultdict
import PIL.Image
import dnnlib
import config
from training import dataset
def convert_to_pil_image(image, drange=[0,1]):
assert image.ndim == 2 or image.ndim == 3
if image.ndim == 3:
if image.shape[0] ==... | null |
35,034 | import os
import glob
import pickle
import re
import numpy as np
from collections import defaultdict
import PIL.Image
import dnnlib
import config
from training import dataset
def get_id_string_for_network_pkl(network_pkl):
p = network_pkl.replace('.pkl', '').replace('\\', '/').split('/')
return '-'.join(p[max(... | null |
35,035 | import os
import glob
import pickle
import re
import numpy as np
from collections import defaultdict
import PIL.Image
import dnnlib
import config
from training import dataset
def load_pkl(file_or_url):
def locate_network_pkl(run_id_or_run_dir_or_network_pkl, snapshot_or_network_pkl=None):
def load_network_pkl(run_id_o... | null |
35,036 | import os
import glob
import pickle
import re
import numpy as np
from collections import defaultdict
import PIL.Image
import dnnlib
import config
from training import dataset
def parse_config_for_previous_run(run_id):
run_dir = locate_run_dir(run_id)
# Parse config.txt.
cfg = defaultdict(dict)
with open... | null |
35,037 | import os
import glob
import pickle
import re
import numpy as np
from collections import defaultdict
import PIL.Image
import dnnlib
import config
from training import dataset
def apply_mirror_augment(minibatch):
mask = np.random.rand(minibatch.shape[0]) < 0.5
minibatch = np.array(minibatch)
minibatch[mask]... | null |
35,038 | import tensorflow as tf
import dnnlib.tflib as tflib
from dnnlib.tflib.autosummary import autosummary
def fp32(*values):
if len(values) == 1 and isinstance(values[0], tuple):
values = values[0]
values = tuple(tf.cast(v, tf.float32) for v in values)
return values if len(values) >= 2 else values[0]
d... | null |
35,039 | import tensorflow as tf
import dnnlib.tflib as tflib
from dnnlib.tflib.autosummary import autosummary
def fp32(*values):
#
def autosummary(name: str, value: TfExpressionEx, passthru: TfExpressionEx = None) -> TfExpressionEx:
def D_wgan(G, D, opt, training_set, minibatch_size, reals, labels, # pylint: disa... | null |
35,040 | import tensorflow as tf
import dnnlib.tflib as tflib
from dnnlib.tflib.autosummary import autosummary
def fp32(*values):
if len(values) == 1 and isinstance(values[0], tuple):
values = values[0]
values = tuple(tf.cast(v, tf.float32) for v in values)
return values if len(values) >= 2 else values[0]
... | null |
35,041 | import tensorflow as tf
import dnnlib.tflib as tflib
from dnnlib.tflib.autosummary import autosummary
def fp32(*values):
if len(values) == 1 and isinstance(values[0], tuple):
values = values[0]
values = tuple(tf.cast(v, tf.float32) for v in values)
return values if len(values) >= 2 else values[0]
... | null |
35,042 | import tensorflow as tf
import dnnlib.tflib as tflib
from dnnlib.tflib.autosummary import autosummary
def fp32(*values):
if len(values) == 1 and isinstance(values[0], tuple):
values = values[0]
values = tuple(tf.cast(v, tf.float32) for v in values)
return values if len(values) >= 2 else values[0]
... | null |
35,043 | import tensorflow as tf
import dnnlib.tflib as tflib
from dnnlib.tflib.autosummary import autosummary
def fp32(*values):
if len(values) == 1 and isinstance(values[0], tuple):
values = values[0]
values = tuple(tf.cast(v, tf.float32) for v in values)
return values if len(values) >= 2 else values[0]
d... | null |
35,044 | import tensorflow as tf
import dnnlib.tflib as tflib
from dnnlib.tflib.autosummary import autosummary
def fp32(*values):
if len(values) == 1 and isinstance(values[0], tuple):
values = values[0]
values = tuple(tf.cast(v, tf.float32) for v in values)
return values if len(values) >= 2 else values[0]
d... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.