id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
21,801
import re import string from typing import Dict, Any The provided code snippet includes necessary dependencies for implementing the `get_input_image_file_name` function. Write a Python function `def get_input_image_file_name(data: Dict[str, Any], **_: Dict[str, Any]) -> str` to solve the following problem: get the ima...
get the image file name of the llm request params :param data: the user llm request data :type data: Dict[str, Any] Example: .. code-block:: python from gptcache.processor.pre import get_input_image_file_name content = get_input_image_file_name({"input": {"image": open("test.png", "rb")}}) # "test.png"
21,802
import re import string from typing import Dict, Any The provided code snippet includes necessary dependencies for implementing the `get_image_question` function. Write a Python function `def get_image_question(data: Dict[str, Any], **_: Dict[str, Any]) -> str` to solve the following problem: get the image and questio...
get the image and question str of the llm request params :param data: the user llm request data :type data: Dict[str, Any] Example: .. code-block:: python from gptcache.processor.pre import get_image_question content = get_image_question({"image": open("test.png", "rb"), "question": "foo"})
21,803
import re import string from typing import Dict, Any The provided code snippet includes necessary dependencies for implementing the `get_image` function. Write a Python function `def get_image(data: Dict[str, Any], **_: Dict[str, Any]) -> str` to solve the following problem: get the image of the llm request params :pa...
get the image of the llm request params :param data: the user llm request data :type data: Dict[str, Any] Example: .. code-block:: python from gptcache.processor.pre import get_image content = get_image({"image": open("test.png", "rb")}) # "test.png"
21,804
import re import string from typing import Dict, Any The provided code snippet includes necessary dependencies for implementing the `get_messages_last_content` function. Write a Python function `def get_messages_last_content(data: Dict[str, Any], **_: Any) -> str` to solve the following problem: get the last content o...
get the last content of the llm request messages array :param data: the user llm request data :type data: Dict[str, Any] Example: .. code-block:: python from gptcache.processor.pre import get_messages_last_content content = get_messages_last_content({"messages": [{"content": "hello"}, {"content": "world"}]}) # "world"
21,805
import re import string from typing import Dict, Any The provided code snippet includes necessary dependencies for implementing the `get_openai_moderation_input` function. Write a Python function `def get_openai_moderation_input(data: Dict[str, Any], **_: Dict[str, Any]) -> str` to solve the following problem: get the...
get the input param of the openai moderation request params :param data: the user openai moderation request data :type data: Dict[str, Any] Example: .. code-block:: python from gptcache.processor.pre import get_openai_moderation_input content = get_openai_moderation_input({"input": ["hello", "world"]}) # "['hello', 'wo...
21,806
The provided code snippet includes necessary dependencies for implementing the `check_hit_session` function. Write a Python function `def check_hit_session(cur_session_id: str, cache_session_ids: list, cache_questions: list, cache_answer: str)` to solve the following problem: Check if the sesion result meets the hit ...
Check if the sesion result meets the hit requirement. :param cur_session_id: the name of the current session. :type cur_session_id: str :param cache_session_ids: a list of session names for caching the same content if you are using map as a data management method. Otherwise a list of session names for similar content a...
21,807
from typing import Dict, Any import numpy as np from gptcache.processor import ContextProcess from gptcache.utils import import_huggingface import transformers def summarize_to_length(summarizer, text, target_len, max_len=1024): tokenizer = summarizer.tokenizer def token_length(text): return len(token...
null
21,808
import random from typing import List, Any import numpy from gptcache.utils import softmax The provided code snippet includes necessary dependencies for implementing the `random_one` function. Write a Python function `def random_one(messages: List[Any]) -> Any` to solve the following problem: Randomly select one resul...
Randomly select one result after evaluation. :param messages: A list of candidate outputs. :type messages: List[Any] Example: .. code-block:: python from gptcache.processor.post import random_one messages = ["message 1", "message 2", "message 3"] answer = random_one(messages)
21,809
import random from typing import List, Any import numpy from gptcache.utils import softmax The provided code snippet includes necessary dependencies for implementing the `first` function. Write a Python function `def first(messages: List[Any]) -> Any` to solve the following problem: Get the first result after evaluati...
Get the first result after evaluation. :param messages: A list of candidate outputs. :type messages: List[Any] Example: .. code-block:: python from gptcache.processor.post import first messages = ["message 1", "message 2", "message 3"] answer = first(messages) assert answer = messages[0]
21,810
from typing import Any, Optional, Callable import gptcache.processor.post import gptcache.processor.pre from gptcache import Cache, cache, Config from gptcache.adapter.adapter import adapt from gptcache.embedding import ( Onnx, Huggingface, SBERT, FastText, Data2VecAudio, Timm, ViT, Open...
null
21,811
from typing import Any from gptcache.adapter.adapter import adapt from gptcache.manager.scalar_data.base import Answer, DataType from gptcache.utils import import_huggingface, import_torch from transformers import pipeline def _cache_data_convert(cache_data): return [{"generated_text": cache_data, "gptcache": True...
null
21,812
from typing import Any from gptcache.adapter.adapter import adapt from gptcache.manager.scalar_data.base import Answer, DataType from gptcache.utils import import_huggingface, import_torch from transformers import pipeline class DataType(IntEnum): class Answer: def _update_cache_callback(llm_data, update_cache_func...
null
21,813
from typing import Optional, List, Any, Mapping from gptcache.adapter.adapter import adapt, aadapt from gptcache.core import cache from gptcache.manager.scalar_data.base import Answer, DataType from gptcache.session import Session from gptcache.utils import import_langchain from langchain.llms.base import LLM from lang...
null
21,814
from typing import Optional, List, Any, Mapping from gptcache.adapter.adapter import adapt, aadapt from gptcache.core import cache from gptcache.manager.scalar_data.base import Answer, DataType from gptcache.session import Session from gptcache.utils import import_langchain from langchain.llms.base import LLM from lang...
null
21,815
from typing import Optional, List, Any, Mapping from gptcache.adapter.adapter import adapt, aadapt from gptcache.core import cache from gptcache.manager.scalar_data.base import Answer, DataType from gptcache.session import Session from gptcache.utils import import_langchain from langchain.llms.base import LLM from lang...
null
21,816
from typing import Optional, List, Any, Mapping from gptcache.adapter.adapter import adapt, aadapt from gptcache.core import cache from gptcache.manager.scalar_data.base import Answer, DataType from gptcache.session import Session from gptcache.utils import import_langchain from langchain.llms.base import LLM from lang...
null
21,817
import base64 import warnings from dataclasses import dataclass from io import BytesIO from typing import List from gptcache.adapter.adapter import adapt from gptcache.manager.scalar_data.base import Answer, DataType from gptcache.utils import ( import_stability, import_pillow ) from gptcache.utils.error import Cac...
null
21,818
import time from typing import Iterator from gptcache.adapter.adapter import adapt from gptcache.manager.scalar_data.base import DataType, Answer from gptcache.utils import import_llama_cpp_python import llama_cpp def _construct_resp_from_cache(return_message): return { "gptcache": True, "choices":...
null
21,819
import time from typing import Iterator from gptcache.adapter.adapter import adapt from gptcache.manager.scalar_data.base import DataType, Answer from gptcache.utils import import_llama_cpp_python import llama_cpp def _construct_stream_resp_from_cache(return_message): return [ { "gptcache": Tru...
null
21,820
import base64 import json import os import time from io import BytesIO from typing import Any, AsyncGenerator, Iterator, List from gptcache import cache from gptcache.adapter.adapter import aadapt, adapt from gptcache.adapter.base import BaseCacheLLM from gptcache.manager.scalar_data.base import Answer, DataType from g...
null
21,821
import base64 import json import os import time from io import BytesIO from typing import Any, AsyncGenerator, Iterator, List from gptcache import cache from gptcache.adapter.adapter import aadapt, adapt from gptcache.adapter.base import BaseCacheLLM from gptcache.manager.scalar_data.base import Answer, DataType from g...
null
21,822
import base64 import json import os import time from io import BytesIO from typing import Any, AsyncGenerator, Iterator, List from gptcache import cache from gptcache.adapter.adapter import aadapt, adapt from gptcache.adapter.base import BaseCacheLLM from gptcache.manager.scalar_data.base import Answer, DataType from g...
null
21,823
import base64 import json import os import time from io import BytesIO from typing import Any, AsyncGenerator, Iterator, List from gptcache import cache from gptcache.adapter.adapter import aadapt, adapt from gptcache.adapter.base import BaseCacheLLM from gptcache.manager.scalar_data.base import Answer, DataType from g...
null
21,824
import base64 import json import os import time from io import BytesIO from typing import Any, AsyncGenerator, Iterator, List from gptcache import cache from gptcache.adapter.adapter import aadapt, adapt from gptcache.adapter.base import BaseCacheLLM from gptcache.manager.scalar_data.base import Answer, DataType from g...
null
21,825
import base64 import json import os import time from io import BytesIO from typing import Any, AsyncGenerator, Iterator, List from gptcache import cache from gptcache.adapter.adapter import aadapt, adapt from gptcache.adapter.base import BaseCacheLLM from gptcache.manager.scalar_data.base import Answer, DataType from g...
null
21,826
import base64 import json import os import time from io import BytesIO from typing import Any, AsyncGenerator, Iterator, List from gptcache import cache from gptcache.adapter.adapter import aadapt, adapt from gptcache.adapter.base import BaseCacheLLM from gptcache.manager.scalar_data.base import Answer, DataType from g...
Returns the number of tokens used by a list of messages.
21,827
import base64 from io import BytesIO from gptcache.adapter.adapter import adapt from gptcache.manager.scalar_data.base import Answer, DataType from gptcache.utils import ( import_pillow, import_diffusers, import_huggingface ) from gptcache.utils.error import CacheError from PIL import Image import diffusers impor...
null
21,828
import time import numpy as np from gptcache import cache from gptcache.processor.post import temperature_softmax from gptcache.utils.error import NotInitError from gptcache.utils.log import gptcache_log from gptcache.utils.time import time_cal def adapt(llm_handler, cache_data_convert, update_cache_callback, *args, **...
Simple copy of the 'adapt' method to different llm for 'async llm function' :param llm_handler: Async LLM calling method, when the cache misses, this function will be called :param cache_data_convert: When the cache hits, convert the answer in the cache to the format of the result returned by llm :param update_cache_ca...
21,829
from typing import Dict, List, Tuple, Any import numpy as np from gptcache.similarity_evaluation import SimilarityEvaluation from gptcache.utils import ( import_onnxruntime, import_huggingface_hub, import_huggingface, ) from transformers import AutoTokenizer from huggingface_hub import hf_hub_download imp...
null
21,830
from typing import Tuple, Dict, Any, List import numpy as np from gptcache.adapter.api import _get_model from gptcache.similarity_evaluation import SimilarityEvaluation def euclidean_distance_calculate(vec_l: np.array, vec_r: np.array): return np.sum((vec_l - vec_r) ** 2)
null
21,831
from typing import Tuple, Dict, Any, List import numpy as np from gptcache.adapter.api import _get_model from gptcache.similarity_evaluation import SimilarityEvaluation def reweight(weights, length): if length >= len(weights): return weights else: reweighted_ws = [] sum_ws = 0 f...
null
21,832
import numpy as np from typing import Dict, Any from gptcache.similarity_evaluation.distance import SearchDistanceEvaluation from gptcache.manager.vector_data.base import VectorBase def euclidean_distance_calculate(vec_l: np.array, vec_r: np.array): return np.sum((vec_l - vec_r)**2)
null
21,833
The provided code snippet includes necessary dependencies for implementing the `to_embeddings` function. Write a Python function `def to_embeddings(data, **_)` to solve the following problem: Nothing to do, return the origin data Here is the function: def to_embeddings(data, **_): """Nothing to do, return the o...
Nothing to do, return the origin data
21,834
import pickle from abc import abstractmethod, ABCMeta from typing import List, Any, Optional, Union import cachetools import numpy as np import requests from gptcache.manager.eviction import EvictionBase from gptcache.manager.eviction.distributed_cache import NoOpEviction from gptcache.manager.eviction_manager import E...
null
21,835
from typing import List import numpy as np from gptcache.manager.vector_data.base import VectorBase, VectorData from gptcache.utils import import_sqlalchemy from sqlalchemy import create_engine, Column, Index, text from sqlalchemy.types import ( # pylint: disable=C0413 Integer, UserDefinedType ) from sqlalche...
null
21,836
from typing import Any, Callable, List import cachetools from gptcache.manager.eviction.base import EvictionBase def popitem_wrapper(func, wrapper_func, clean_size): def wrapper(*args, **kwargs): keys = [] try: keys = [func(*args, **kwargs)[0] for _ in range(clean_size)] except ...
null
21,837
import os from pathlib import Path from typing import Union, Callable from gptcache.manager import CacheBase, VectorBase, ObjectBase from gptcache.manager.data_manager import SSDataManager, MapDataManager from gptcache.manager.eviction import EvictionBase from gptcache.utils.log import gptcache_log def get_data_manager...
Factory of DataManager. By using this factory method, you only need to specify the root directory of the data, and it can automatically manage all the local files. :param manager: Type of DataManager. Supports: Map, or {scalar_name},{vector_name} or {scalar_name},{vector_name},{object_name} :type manager: str :param da...
21,838
from datetime import datetime from typing import List, Optional, Dict import numpy as np from gptcache.manager.scalar_data.base import ( CacheStorage, CacheData, Question, QuestionDep, ) from gptcache.utils import import_sqlalchemy import sqlalchemy from sqlalchemy import func, create_engine, Column, Se...
null
21,839
import datetime from typing import List, Optional import numpy as np from gptcache.manager.scalar_data.base import ( CacheStorage, CacheData, Question, QuestionDep, ) from gptcache.utils import import_redis from redis import Redis from redis.client import Pipeline from redis_om import get_redis_connecti...
Get all the models for the given global key and redis connection. :param global_key: Global key will be used as a prefix for all the keys :type global_key: str :param redis_connection: Redis connection to use for all the models. Note: This needs to be explicitly mentioned in `Meta` class for each Object Model, otherwis...
21,840
from datetime import datetime from typing import List, Optional import numpy as np from gptcache.manager.scalar_data.base import ( CacheStorage, CacheData, Question, QuestionDep, ) from gptcache.utils import import_mongodb from mongoengine import Document from mongoengine import fields import mongoengin...
null
21,841
def cache_all(*_, **__): return True
null
21,842
import subprocess from gptcache.utils.error import PipInstallError from gptcache.utils.log import gptcache_log class PipInstallError(CacheError): """Raise when failed to install package.""" def __init__(self, package): super().__init__(f"Ran into error installing {package}.") gptcache_log = logging.ge...
Function used to prompt user to install a package.
21,843
import base64 import requests def get_message_from_openai_answer(openai_resp): return openai_resp["choices"][0]["message"]["content"]
null
21,844
import base64 import requests def get_stream_message_from_openai_answer(openai_data): return openai_data["choices"][0]["delta"].get("content", "")
null
21,845
import base64 import requests def get_text_from_openai_answer(openai_resp): return openai_resp["choices"][0]["text"]
null
21,846
import base64 import requests def get_image_from_openai_b64(openai_resp): return openai_resp["data"][0]["b64_json"]
null
21,847
import base64 import requests def get_image_from_openai_url(openai_resp): url = openai_resp["data"][0]["url"] img_content = requests.get(url).content img_data = base64.b64encode(img_content) return img_data
null
21,848
import base64 import requests def get_image_from_path(openai_resp): img_path = openai_resp["data"][0]["url"] with open(img_path, "rb") as f: img_data = base64.b64encode(f.read()) return img_data
null
21,849
import base64 import requests def get_audio_text_from_openai_answer(openai_resp): return openai_resp["text"]
null
21,850
class CacheError(Exception): """GPTCache base error""" The provided code snippet includes necessary dependencies for implementing the `wrap_error` function. Write a Python function `def wrap_error(e: Exception) -> Exception` to solve the following problem: Add a type to exception `e` while ensuring that the origin...
Add a type to exception `e` while ensuring that the original type is not changed Example: .. code-block:: python import openai from gptcache.utils.error import wrap_error def raise_error(): try: raise openai.error.OpenAIError(message="test") except openai.error.OpenAIError as e: raise wrap_error(e) try: raise_error() e...
21,851
import argparse import json import os import zipfile from typing import Optional from gptcache import cache, Cache from gptcache.adapter import openai from gptcache.adapter.api import ( get, put, init_similar_cache, init_similar_cache_from_config, ) from gptcache.processor.pre import last_content from g...
null
21,852
import argparse import json import os import zipfile from typing import Optional from gptcache import cache, Cache from gptcache.adapter import openai from gptcache.adapter.api import ( get, put, init_similar_cache, init_similar_cache_from_config, ) from gptcache.processor.pre import last_content from g...
null
21,853
import argparse import json import os import zipfile from typing import Optional from gptcache import cache, Cache from gptcache.adapter import openai from gptcache.adapter.api import ( get, put, init_similar_cache, init_similar_cache_from_config, ) from gptcache.processor.pre import last_content from g...
null
21,854
import argparse import json import os import zipfile from typing import Optional from gptcache import cache, Cache from gptcache.adapter import openai from gptcache.adapter.api import ( get, put, init_similar_cache, init_similar_cache_from_config, ) from gptcache.processor.pre import last_content from g...
null
21,855
import argparse import json import os import zipfile from typing import Optional from gptcache import cache, Cache from gptcache.adapter import openai from gptcache.adapter.api import ( get, put, init_similar_cache, init_similar_cache_from_config, ) from gptcache.processor.pre import last_content from g...
null
21,856
import argparse import json import os import zipfile from typing import Optional from gptcache import cache, Cache from gptcache.adapter import openai from gptcache.adapter.api import ( get, put, init_similar_cache, init_similar_cache_from_config, ) from gptcache.processor.pre import last_content from g...
null
21,857
import cv2 import random import numpy as np import argparse from DRL.evaluator import Evaluator from utils.util import * from utils.tensorboard import TensorBoard import time writer = TensorBoard('../train_log/{}'.format(exp)) def train(agent, env, evaluate): train_times = args.train_times env_batch = args.env...
null
21,858
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import Adam, SGD from Renderer.model import * from DRL.rpm import rpm from DRL.actor import * from DRL.critic import * from DRL.wgan import * from utils.util import * for i in range(128): for j in range(128): ...
null
21,859
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import Adam, SGD from Renderer.model import * from DRL.rpm import rpm from DRL.actor import * from DRL.critic import * from DRL.wgan import * from utils.util import * def cal_trans(s, t): return (s.transpose(0, 3...
null
21,860
import torch import torch.nn as nn import numpy as np from torch.optim import Adam, SGD from torch import autograd from torch.autograd import Variable import torch.nn.functional as F from torch.autograd import grad as torch_grad import torch.nn.utils.weight_norm as weightNorm from utils.util import * target_netD = Disc...
null
21,861
import torch import torch.nn as nn import numpy as np from torch.optim import Adam, SGD from torch import autograd from torch.autograd import Variable import torch.nn.functional as F from torch.autograd import grad as torch_grad import torch.nn.utils.weight_norm as weightNorm from utils.util import * device = torch.dev...
null
21,862
import torch import torch.nn as nn import numpy as np from torch.optim import Adam, SGD from torch import autograd from torch.autograd import Variable import torch.nn.functional as F from torch.autograd import grad as torch_grad import torch.nn.utils.weight_norm as weightNorm from utils.util import * netD = Discriminat...
null
21,863
import torch import torch.nn as nn import numpy as np from torch.optim import Adam, SGD from torch import autograd from torch.autograd import Variable import torch.nn.functional as F from torch.autograd import grad as torch_grad import torch.nn.utils.weight_norm as weightNorm from utils.util import * netD = Discriminat...
null
21,864
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.utils.weight_norm as weightNorm from torch.autograd import Variable import sys def conv3x3(in_planes, out_planes, stride=1): return (nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=F...
null
21,865
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.utils.weight_norm as weightNorm from torch.autograd import Variable import sys class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init_...
null
21,866
import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.utils.weight_norm as weightNorm from torch.autograd import Variable import sys def conv3x3(in_planes, out_planes, stride=1): return weightNorm(nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True))
null
21,867
import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.utils.weight_norm as weightNorm from torch.autograd import Variable import sys class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.co...
null
21,868
import cv2 import numpy as np def normal(x, width): return (int)(x * (width - 1) + 0.5) def draw(f, width=128): x0, y0, x1, y1, x2, y2, z0, z2, w0, w2 = f x1 = x0 + (x2 - x0) * x1 y1 = y0 + (y2 - y0) * y1 x0 = normal(x0, width * 2) x1 = normal(x1, width * 2) x2 = normal(x2, width * 2) y...
null
21,869
import cv2 import torch import numpy as np import torch.nn as nn import torch.nn.functional as F from utils.tensorboard import TensorBoard from Renderer.model import FCN from Renderer.stroke_gen import * import torch.optim as optim net = FCN() use_cuda = torch.cuda.is_available() def save_model(): if use_cuda: ...
null
21,870
import cv2 import torch import numpy as np import torch.nn as nn import torch.nn.functional as F from utils.tensorboard import TensorBoard from Renderer.model import FCN from Renderer.stroke_gen import * import torch.optim as optim net = FCN() def load_weights(): pretrained_dict = torch.load("../renderer.pkl") ...
null
21,871
import os import torch from torch.autograd import Variable def prRed(prt): print("\033[91m {}\033[00m" .format(prt))
null
21,872
import os import torch from torch.autograd import Variable def prGreen(prt): print("\033[92m {}\033[00m" .format(prt))
null
21,873
import os import torch from torch.autograd import Variable def prYellow(prt): print("\033[93m {}\033[00m" .format(prt))
null
21,874
import os import torch from torch.autograd import Variable def prLightPurple(prt): print("\033[94m {}\033[00m" .format(prt))
null
21,875
import os import torch from torch.autograd import Variable def prPurple(prt): print("\033[95m {}\033[00m" .format(prt))
null
21,876
import os import torch from torch.autograd import Variable def prCyan(prt): print("\033[96m {}\033[00m" .format(prt))
null
21,877
import os import torch from torch.autograd import Variable def prLightGray(prt): print("\033[97m {}\033[00m" .format(prt))
null
21,878
import os import torch from torch.autograd import Variable def prBlack(prt): print("\033[98m {}\033[00m" .format(prt))
null
21,879
import os import torch from torch.autograd import Variable USE_CUDA = torch.cuda.is_available() def to_numpy(var): return var.cpu().data.numpy() if USE_CUDA else var.data.numpy()
null
21,880
import os import torch from torch.autograd import Variable def to_tensor(ndarray, device): return torch.tensor(ndarray, dtype=torch.float, device=device)
null
21,881
import os import torch from torch.autograd import Variable def soft_update(target, source, tau): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_( target_param.data * (1.0 - tau) + param.data * tau )
null
21,882
import os import torch from torch.autograd import Variable def hard_update(target, source): for m1, m2 in zip(target.modules(), source.modules()): m1._buffers = m2._buffers.copy() for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(param.data)
null
21,883
import os import torch from torch.autograd import Variable The provided code snippet includes necessary dependencies for implementing the `get_output_folder` function. Write a Python function `def get_output_folder(parent_dir, env_name)` to solve the following problem: Return save folder. Assumes folders in the parent...
Return save folder. Assumes folders in the parent_dir have suffix -run{run number}. Finds the highest run number and sets the output folder to that number + 1. This is just convenient so that if you run the same script multiple times tensorboard can plot all of the results on the same plots with different names. Parame...
21,890
import torch import torch.nn as nn import numpy as np from torch.optim import Adam, SGD from torch import autograd from torch.autograd import Variable import torch.nn.functional as F from torch.autograd import grad as torch_grad import torch.nn.utils.weight_norm as weightNorm from utils.util import * netD = Discriminat...
null
21,911
import argparse import tempfile from pathlib import Path import cog import cv2 import imageio from baseline.DRL.actor import * from baseline.Renderer.model import * def decode(x, canvas, Decoder, width): # b * (10 + 3) x = x.view(-1, 10 + 3) stroke = 1 - Decoder(x[:, :10]) stroke = stroke.view(-1, width, ...
null
21,912
import argparse import tempfile from pathlib import Path import cog import cv2 import imageio from baseline.DRL.actor import * from baseline.Renderer.model import * def large2small(x, canvas_cnt, args, width): # (d * width, d * width) -> (d * d, width, width) x = x.reshape(args.divide, width, args.divide, widt...
null
21,913
import argparse import tempfile from pathlib import Path import cog import cv2 import imageio from baseline.DRL.actor import * from baseline.Renderer.model import * def small2large(x, args, width): # (d * d, width, width) -> (d * width, d * width) x = x.reshape(args.divide, args.divide, width, width, -1) x ...
null
21,914
import csv import collections The provided code snippet includes necessary dependencies for implementing the `read_rides_as_tuples` function. Write a Python function `def read_rides_as_tuples(filename)` to solve the following problem: Read the bus ride data as a list of tuples Here is the function: def read_rides_as...
Read the bus ride data as a list of tuples
21,915
import csv import collections The provided code snippet includes necessary dependencies for implementing the `read_rides_as_dicts` function. Write a Python function `def read_rides_as_dicts(filename)` to solve the following problem: Read the bus ride data as a list of dicts Here is the function: def read_rides_as_di...
Read the bus ride data as a list of dicts
21,916
import csv class Row: __slots__ = ('route', 'date', 'daytype', 'rides') def __init__(self, route, date, daytype, rides): self.route = route self.date = date self.daytype = daytype self.rides = rides import collections The provided code snippet includes necessary dependencies for...
Read the bus ride data as a list of instances
21,917
import csv import collections The provided code snippet includes necessary dependencies for implementing the `read_rides_as_columns` function. Write a Python function `def read_rides_as_columns(filename)` to solve the following problem: Read the bus ride data into 4 lists, representing columns Here is the function: ...
Read the bus ride data into 4 lists, representing columns
21,918
import csv import collections class RideData(collections.abc.Sequence): def __init__(self): # Each value is a list with all of the values (a column) self.routes = [] self.dates = [] self.daytypes = [] self.numrides = [] def __len__(self): # All lists assumed to ha...
Read the bus ride data as a list of dicts
21,919
class Integer(Typed): expected_type = int def add(x, y): Integer.check(x) Integer.check(y) return x + y
null
21,920
import os import time import csv from functools import wraps def follow(filename,target): with open(filename,"r") as f: f.seek(0,os.SEEK_END) while True: line = f.readline() if line != '': target.send(line) else: time.sleep(0.1)
null
21,921
import os import time import csv from functools import wraps def consumer(func): @wraps(func) def start(*args,**kwargs): f = func(*args,**kwargs) f.send(None) return f return start
null
21,922
import os import time import csv from functools import wraps def printer(): while True: try: item = yield print(item) except Exception as e: print('ERROR: %r' % e)
null
21,923
import os import time The provided code snippet includes necessary dependencies for implementing the `follow` function. Write a Python function `def follow(filename)` to solve the following problem: Generator that produces a sequence of lines being written at the end of a file. Here is the function: def follow(filen...
Generator that produces a sequence of lines being written at the end of a file.
21,924
import os import time def splitter(lines): for line in lines: yield line.split(',') def make_records(rows,names): for row in rows: yield dict(zip(names,row)) def unquote(records,keylist): for r in records: for key in keylist: r[key] = r[key].strip('"') yield r def...
null
21,925
class Integer(Typed): expected_type = int from inspect import signature def add(x:Integer, y:Integer) -> Integer: return x + y
null
21,926
from .validate import Validator, validated from collections import ChainMap class Validator: def __init__(self, name=None): self.name = name def __set_name__(self, cls, name): self.name = name def check(cls, value): return value def __set__(self, instance, value): ins...
Class decorator that scans a class definition for Validators and builds a _fields variable that captures their definition order.