id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
150,898 | import socket
import ipaddress
import requests
import urllib.parse
from threading import Lock
import logging
import sys
import os.path
import platform
from .conf import settings
from datetime import datetime
from functools import wraps
from .constants import USER_APP_NAME
from .i18n import _
from typing import TYPE_CHE... | null |
150,899 | import socket
import ipaddress
import requests
import urllib.parse
from threading import Lock
import logging
import sys
import os.path
import platform
from .conf import settings
from datetime import datetime
from functools import wraps
from .constants import USER_APP_NAME
from .i18n import _
from typing import TYPE_CHE... | null |
150,900 | import socket
import ipaddress
import requests
import urllib.parse
from threading import Lock
import logging
import sys
import os.path
import platform
from .conf import settings
from datetime import datetime
from functools import wraps
from .constants import USER_APP_NAME
from .i18n import _
from typing import TYPE_CHE... | null |
150,901 | import socket
import ipaddress
import requests
import urllib.parse
from threading import Lock
import logging
import sys
import os.path
import platform
from .conf import settings
from datetime import datetime
from functools import wraps
from .constants import USER_APP_NAME
from .i18n import _
from typing import TYPE_CHE... | null |
150,902 | from PIL import Image
from collections import deque
import subprocess
from multiprocessing import Process, Queue
import threading
import sys
import logging
import queue
from .constants import USER_APP_NAME, APP_NAME
from .conffile import confdir
from .clients import clientManager
from .utils import get_resource
from .l... | null |
150,903 | from PIL import Image
from collections import deque
import subprocess
from multiprocessing import Process, Queue
import threading
import sys
import logging
import queue
from .constants import USER_APP_NAME, APP_NAME
from .conffile import confdir
from .clients import clientManager
from .utils import get_resource
from .l... | null |
150,904 | from PIL import Image
from collections import deque
import subprocess
from multiprocessing import Process, Queue
import threading
import sys
import logging
import queue
from .constants import USER_APP_NAME, APP_NAME
from .conffile import confdir
from .clients import clientManager
from .utils import get_resource
from .l... | null |
150,905 | from PIL import Image
from collections import deque
import subprocess
from multiprocessing import Process, Queue
import threading
import sys
import logging
import queue
from .constants import USER_APP_NAME, APP_NAME
from .conffile import confdir
from .clients import clientManager
from .utils import get_resource
from .l... | null |
150,906 | from pypresence import Client
import time
RPC = Client(client_id)
RPC.start()
def register_join_event(syncplay_join_group: callable):
RPC.register_event("activity_join", syncplay_join_group) | null |
150,907 | from pypresence import Client
import time
RPC = Client(client_id)
RPC.start()
def send_presence(
title: str,
subtitle: str,
playback_time: float = None,
duration: float = None,
playing: bool = False,
syncplay_group: str = None,
):
small_image = "play-dark3" if playing else None
start = ... | null |
150,908 | from pypresence import Client
import time
RPC = Client(client_id)
RPC.start()
def clear_presence():
RPC.clear_activity() | null |
150,909 | from collections import namedtuple
from .utils import get_sub_display_title
from .i18n import _
import time
import logging
from typing import TYPE_CHECKING
Part = namedtuple("Part", ["id", "audio", "subtitle"])
Audio = namedtuple("Audio", ["id", "language_code", "name", "display_name"])
Subtitle = namedtuple(
"Subt... | null |
150,910 | from .conf import settings
from .i18n import _
import urllib.request
import urllib.error
import logging
import sys
import time
from typing import TYPE_CHECKING
def list_request(path: str):
def simple_request(path: str):
def _(string: str) -> str:
def get_profiles():
profile_ids = list_request("list=profiles")
... | null |
150,911 | from .conf import settings
from .i18n import _
import urllib.request
import urllib.error
import logging
import sys
import time
from typing import TYPE_CHECKING
def simple_request(path: str):
response_list = list_request(path)
if response_list is None:
return None
if len(response_list) != 1 or " = " ... | null |
150,912 | from .conf import settings
from .i18n import _
import urllib.request
import urllib.error
import logging
import sys
import time
log = logging.getLogger("svp_integration")
from typing import TYPE_CHECKING
def list_request(path: str):
try:
response = urllib.request.urlopen(settings.svp_url + "?" + path)
... | null |
150,913 | from .conf import settings
from .i18n import _
import urllib.request
import urllib.error
import logging
import sys
import time
from typing import TYPE_CHECKING
def simple_request(path: str):
response_list = list_request(path)
if response_list is None:
return None
if len(response_list) != 1 or " = " ... | null |
150,914 | from .conf import settings
from .i18n import _
import urllib.request
import urllib.error
import logging
import sys
import time
from typing import TYPE_CHECKING
def list_request(path: str):
try:
response = urllib.request.urlopen(settings.svp_url + "?" + path)
return response.read().decode("utf-8").re... | null |
150,915 | from .conf import settings
from .i18n import _
import urllib.request
import urllib.error
import logging
import sys
import time
from typing import TYPE_CHECKING
def simple_request(path: str):
response_list = list_request(path)
if response_list is None:
return None
if len(response_list) != 1 or " = " ... | null |
150,916 | import gettext
import locale
from .conf import settings
translation = gettext.NullTranslations()
settings = Settings()
def get_resource(*path):
def configure():
global translation
from .utils import get_resource
messages_dir = get_resource("messages")
lang = None
if settings.lang is not None:
... | null |
150,917 | import gettext
import locale
from .conf import settings
translation = gettext.NullTranslations()
def get_translation():
return translation | null |
150,918 | import random
import datetime
import math
from ..clients import clientManager
def getUrl(serverAddress, name):
if not name:
raise Exception("Url name cannot be empty")
url = serverAddress
url += "/" if not serverAddress.endswith("/") and not name.startswith("/") else ""
url += name
return ur... | null |
150,919 | import random
import datetime
import math
from ..clients import clientManager
def getUrl(serverAddress, name):
def getPrimaryImageUrl(item, serverAddress):
if item.get("AlbumPrimaryImageTag"):
return getUrl(
serverAddress,
"Items/"
+ item["AlbumId"]
+ "/Image... | null |
150,920 | import random
import datetime
import math
from ..clients import clientManager
def getDisplayName(item):
name = item.get("EpisodeTitle", item.get("Name"))
if item["Type"] == "TvChannel":
if item["Number"]:
return item["Number"] + " " + name
else:
return name
# NOTE: ... | null |
150,921 | import random
import datetime
import math
from ..clients import clientManager
def getRatingHtml(item):
html = ""
if item.get("CommunityRating"):
html += (
"<div class='starRating' title='"
+ str(item["CommunityRating"])
+ "'></div>"
)
html += '<div c... | null |
150,922 | import random
import datetime
import math
from ..clients import clientManager
def __convert_jf_str_datetime(jf_string):
# datetime doesn't quite support fractions of a second the same way Jellyfin does them.
# Best we can do is strip them out entirely.
# FIXME: I think this loses timezone information, but a... | null |
150,923 | import random
import datetime
import math
from ..clients import clientManager
def getBackdropUrl(item, serverAddress):
clientManager = ClientManager()
def getRandomBackdropUrl(_positional_arg_that_is_never_used=None, **params):
# This function is to get 1 random item, so ignore those arguments
params["SortBy"... | null |
150,924 | import logging
import re
bad_patterns = (
(re.compile("api_key=[a-f0-9]*"), "api_key=REDACTED"),
(
re.compile("'X-MediaBrowser-Token': '[a-f0-9]*'"),
"'X-MediaBrowser-Token': 'REDACTED'",
),
(re.compile("'AccessToken': '[a-f0-9]*'"), "'AccessToken': 'REDACTED'"),
)
def sanitize(message)... | null |
150,925 | import logging
import re
sanitize_logs = False
def enable_sanitization():
global sanitize_logs
sanitize_logs = True | null |
150,926 | import logging
import re
root_logger = logging.getLogger("")
root_logger.level = logging.DEBUG
class CustomFormatter(logging.Formatter):
def __init__(self, force_sanitize=False):
self.force_sanitize = force_sanitize
super(CustomFormatter, self).__init__(
fmt="%(asctime)s [%(levelname)8s]... | null |
150,927 | import logging
import re
root_logger = logging.getLogger("")
root_logger.level = logging.DEBUG
class CustomFormatter(logging.Formatter):
def __init__(self, force_sanitize=False):
def format(self, record):
def configure_log_file(destination: str):
handler = logging.FileHandler(destination, mode="w")
#... | null |
150,928 | from __future__ import annotations
from typing import Optional
import logging
def allow_none(constructor):
def wrapper(input):
if input is None or input == "null":
return None
return constructor(input)
return wrapper | null |
150,929 | from __future__ import annotations
from typing import Optional
import logging
yes_set = {1, "yes", "Yes", "True", "true", "1", True}
def adv_bool(value):
return value in yes_set | null |
150,930 | import os.path
import os
import sys
import getpass
def get(app: str, conf_file: str, create: bool = False):
conf_folder = confdir(app)
if not os.path.isdir(conf_folder):
os.makedirs(conf_folder)
conf_file = os.path.join(conf_folder, conf_file)
if create and not os.path.isfile(conf_file):
... | null |
150,931 | import os.path
import os
import sys
import getpass
username = getpass.getuser()
def get(app: str, conf_file: str, create: bool = False):
conf_folder = confdir(app)
if not os.path.isdir(conf_folder):
os.makedirs(conf_folder)
conf_file = os.path.join(conf_folder, conf_file)
if create and not os.pa... | null |
150,932 | import os.path
import os
import sys
import getpass
def confdir(app: str):
if custom_config is not None:
return custom_config
elif _confdir is not None:
return _confdir(app)
else:
return ""
def get_dir(app: str, subfolder: str):
conf_folder = os.path.join(confdir(app), subfolder)... | null |
150,933 | import logging
import os
import sys
import time
import platform
from threading import RLock, Lock, Event
from queue import Queue
from collections import OrderedDict
from typing import TYPE_CHECKING, Optional
from . import conffile
from .utils import synchronous, Timer, none_fallback, get_resource
from .conf import sett... | null |
150,934 | import logging
import os
import sys
import time
import platform
from threading import RLock, Lock, Event
from queue import Queue
from collections import OrderedDict
from typing import TYPE_CHECKING, Optional
from . import conffile
from .utils import synchronous, Timer, none_fallback, get_resource
from .conf import sett... | null |
150,935 | import logging
import threading
import os
from datetime import datetime, timedelta
from .clients import clientManager
from .media import Media
from .i18n import _
from .conf import settings
from typing import TYPE_CHECKING, Optional
def _parse_precise_time(time: str):
# We have to remove the Z and the least signif... | null |
150,936 | import logging
import threading
import os
from datetime import datetime, timedelta
from .clients import clientManager
from .media import Media
from .i18n import _
from .conf import settings
from typing import TYPE_CHECKING, Optional
class TimeoutThread(threading.Thread):
def __init__(self, action, delay: float, arg... | Similar to setTimeout JS function. |
150,937 | import logging
import os
import uuid
import socket
import json
import os.path
import sys
import getpass
from typing import Optional
from .settings_base import SettingsBase
def get_default_sdir():
if sys.platform.startswith("win32"):
if os.environ.get("USERPROFILE"):
return os.path.join(os.envir... | null |
150,938 | import win32gui
import logging
log = logging.getLogger("win_utils")
def window_enumeration_handler(hwnd, top_windows):
top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
def raise_mpv():
# This workaround is madness. Apparently SetForegroundWindow
# won't work randomly, so I have to call ShowWindow t... | null |
150,939 | import win32gui
import logging
log = logging.getLogger("win_utils")
def window_enumeration_handler(hwnd, top_windows):
top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
def mirror_act(state: bool, name: str = "Jellyfin MPV Shim Mirror"):
try:
top_windows = []
win32gui.EnumWindows(window_... | null |
150,940 | import logging
import os
from .conf import settings
from .media import Media
from .player import playerManager
from .timeline import timelineManager
bindings = {}
from typing import TYPE_CHECKING
def bind(event_name: str):
def decorator(func):
bindings[event_name] = func
return func
return dec... | null |
150,941 | import struct
from io import BytesIO
from PIL import Image
def decode(fh):
if fh.read(8) != BIF_MAGIC:
raise ValueError("Data provided is not a BIF file.")
bif_version = _read_i32(fh)
if bif_version != BIF_SUPPORTED:
raise ValueError(f"BIF version {bif_version} is not supported.")
image_... | null |
150,942 | import struct
from io import BytesIO
from PIL import Image
def decompress_tiles(width, height, tile_width, tile_height, count, tiles, fh):
image_count = 0
for image in tiles:
image = Image.open(BytesIO(image)).convert("RGBA")
if height * tile_height != image.height or width * tile_width != im... | null |
150,943 | import struct
from io import BytesIO
from PIL import Image
def decompress_bif(images, fh):
height = None
width = None
image_count = 0
for image in images:
image_count += 1
image = Image.open(BytesIO(image)).convert("RGBA")
if height is None:
height = image.height
... | null |
150,944 | import logging
import math
import os
import sys
from dataclasses import dataclass, field
from typing import Optional, Union, List, Dict, Tuple
import torch
import collections
import random
from datasets import load_dataset
import transformers
from transformers import (
CONFIG_MAPPING,
MODEL_FOR_MASKED_LM_MAPPIN... | null |
150,945 | import sys
import io, os
import numpy as np
import logging
import argparse
from prettytable import PrettyTable
import torch
import transformers
from transformers import AutoModel, AutoTokenizer
import senteval
def print_table(task_names, scores):
tb = PrettyTable()
tb.field_names = task_names
tb.add_row(sc... | null |
150,946 | import torch
from scipy.spatial.distance import cosine
from transformers import AutoModel, AutoTokenizer
import gradio as gr
tokenizer = AutoTokenizer.from_pretrained("princeton-nlp/sup-simcse-bert-base-uncased")
model = AutoModel.from_pretrained("princeton-nlp/sup-simcse-bert-base-uncased")
inputs = [
gr.inp... | null |
150,947 | import json
import argparse
import torch
import os
import random
import numpy as np
import requests
import logging
import math
import copy
import string
from tqdm import tqdm
from time import time
from flask import Flask, request, jsonify
from flask_cors import CORS
from tornado.wsgi import WSGIContainer
from tornado.h... | null |
150,950 | from __future__ import absolute_import, division, unicode_literals
import numpy as np
import re
import inspect
from torch import optim
The provided code snippet includes necessary dependencies for implementing the `get_optimizer` function. Write a Python function `def get_optimizer(s)` to solve the following problem:
... | Parse optimizer parameters. Input should be of the form: - "sgd,lr=0.01" - "adagrad,lr=0.1,lr_decay=0.05" |
150,952 | from __future__ import absolute_import, division, unicode_literals
import logging
import sys
import skipthoughts
import senteval
def prepare(params, samples):
return | null |
150,953 | from __future__ import absolute_import, division, unicode_literals
import logging
import sys
import skipthoughts
import senteval
def batcher(params, batch):
batch = [str(' '.join(sent), errors="ignore") if sent != [] else '.' for sent in batch]
embeddings = skipthoughts.encode(params['encoder'], batch,
... | null |
150,954 | from __future__ import absolute_import, division
import os
import sys
import logging
import tensorflow as tf
import tensorflow_hub as hub
import senteval
def prepare(params, samples):
return | null |
150,955 | from __future__ import absolute_import, division
import os
import sys
import logging
import tensorflow as tf
import tensorflow_hub as hub
import senteval
def batcher(params, batch):
batch = [' '.join(sent) if sent != [] else '.' for sent in batch]
embeddings = params['google_use'](batch)
return embeddings | null |
150,956 | from __future__ import absolute_import, division
import os
import sys
import logging
import tensorflow as tf
import tensorflow_hub as hub
tf.logging.set_verbosity(0)
import senteval
session = tf.Session()
def make_embed_fn(module):
with tf.Graph().as_default():
sentences = tf.placeholder(tf.string)
embed = h... | null |
150,957 | from __future__ import absolute_import, division, unicode_literals
import sys
import io
import numpy as np
import logging
PATH_TO_VEC = 'fasttext/crawl-300d-2M.vec'
import senteval
def create_dictionary(sentences, threshold=0):
words = {}
for s in sentences:
for word in s:
words[word] = word... | null |
150,958 | from __future__ import absolute_import, division, unicode_literals
import sys
import io
import numpy as np
import logging
import senteval
def batcher(params, batch):
batch = [sent if sent != [] else ['.'] for sent in batch]
embeddings = []
for sent in batch:
sentvec = []
for word in sent:
... | null |
150,959 | from __future__ import absolute_import, division, unicode_literals
import sys
import os
import torch
import logging
from models import InferSent
import senteval
def prepare(params, samples):
params.infersent.build_vocab([' '.join(s) for s in samples], tokenize=False) | null |
150,960 | from __future__ import absolute_import, division, unicode_literals
import sys
import os
import torch
import logging
from models import InferSent
import senteval
def batcher(params, batch):
sentences = [' '.join(s) for s in batch]
embeddings = params.infersent.encode(sentences, bsize=params.batch_size, tokenize... | null |
150,961 | from __future__ import absolute_import, division, unicode_literals
import sys
import logging
from gensen import GenSen, GenSenSingle
import senteval
def prepare(params, samples):
return | null |
150,962 | from __future__ import absolute_import, division, unicode_literals
import sys
import logging
from gensen import GenSen, GenSenSingle
import senteval
def batcher(params, batch):
batch = [' '.join(sent) if sent != [] else '.' for sent in batch]
_, reps_h_t = gensen.get_representation(
sentences, pool='la... | null |
150,963 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
import transformers
from transformers import RobertaTokenizer
from transformers.models.roberta.modeling_roberta import RobertaPreTrainedModel, RobertaModel, RobertaLMHead
from transformers.models.bert.modeling_bert impor... | Contrastive learning class init function. |
150,964 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
import transformers
from transformers import RobertaTokenizer
from transformers.models.roberta.modeling_roberta import RobertaPreTrainedModel, RobertaModel, RobertaLMHead
from transformers.models.bert.modeling_bert impor... | null |
150,965 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
import transformers
from transformers import RobertaTokenizer
from transformers.models.roberta.modeling_roberta import RobertaPreTrainedModel, RobertaModel, RobertaLMHead
from transformers.models.bert.modeling_bert impor... | null |
150,966 | from fastapi import FastAPI
from routers import products, users, basic_auth_users, jwt_auth_users, users_db
from fastapi.staticfiles import StaticFiles
async def root():
return "Hola FastAPI!" | null |
150,967 | from fastapi import FastAPI
from routers import products, users, basic_auth_users, jwt_auth_users, users_db
from fastapi.staticfiles import StaticFiles
async def url():
return {"url": "https://mouredev.com/python"} | null |
150,968 | from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
users_db = {
"mouredev": {
"username": "mouredev",
"full_name": "Brais Moure",
"email": "braismoure@mourede.com",
... | null |
150,969 | from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
class User(BaseModel):
username: str
full_name: str
email: str
disabled: bool
async def current_user(token: str = Depends(oauth2)):
... | null |
150,970 | from fastapi import APIRouter
products_list = ["Producto 1", "Producto 2",
"Producto 3", "Producto 4", "Producto 5"]
async def products():
return products_list | null |
150,971 | from fastapi import APIRouter
products_list = ["Producto 1", "Producto 2",
"Producto 3", "Producto 4", "Producto 5"]
async def products(id: int):
return products_list[id] | null |
150,972 | from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
async def usersjson(): # Creamos un JSON a mano
return [{"name": "Brais", "surname": "Moure", "url": "https://moure.dev", "age": 35},
{"name": "Moure", "surname": "Dev",
"url": "https://mouredev.com", "age": 35... | null |
150,973 | from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import jwt, JWTError
from passlib.context import CryptContext
from datetime import datetime, timedelta
ALGORITHM = "HS256"
ACCESS_TOKEN_DURA... | null |
150,974 | from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import jwt, JWTError
from passlib.context import CryptContext
from datetime import datetime, timedelta
class User(BaseModel):
username: ... | null |
150,975 | from functools import reduce
def sum_one(value):
return value + 1 | null |
150,976 | from functools import reduce
def sum_five(value):
return value + 5 | null |
150,977 | from functools import reduce
def sum_two_values_and_add_value(first_value, second_value, f_sum):
return f_sum(first_value + second_value) | null |
150,978 | from functools import reduce
def sum_ten(original_value):
def add(value):
return value + 10 + original_value
return add | null |
150,979 | from functools import reduce
def multiply_two(number):
return number * 2 | null |
150,980 | from functools import reduce
def filter_greater_than_ten(number):
if number > 10:
return True
return False | null |
150,981 | from functools import reduce
def sum_two_values(first_value, second_value):
return first_value + second_value | null |
150,982 | from datetime import timedelta
from datetime import date
from datetime import time
from datetime import datetime
print(current_time.hour)
print(current_time.minute)
print(current_time.second)
print(current_date.year)
print(current_date.month)
print(current_date.day)
print(current_date.year)
print(current_date.month)
pr... | null |
150,983 |
def sum_five(number):
return number + 5 | null |
150,984 | print(is_anagram("Amor", "Roma"))
print(reverse("Hola mundo"))
def fizzbuzz():
for index in range(1, 101):
if index % 3 == 0 and index % 5 == 0:
print("fizzbuz")
elif index % 3 == 0:
print("fizz")
elif index % 5 == 0:
print("buzz")
else:
... | null |
150,985 |
def is_anagram(word_one, word_two):
if word_one.lower() == word_two.lower():
return False
return sorted(word_one.lower()) == sorted(word_two.lower()) | null |
150,986 | print(is_anagram("Amor", "Roma"))
print(reverse("Hola mundo"))
def fibonacci():
prev = 0
next = 1
for index in range(0, 50):
print(prev)
fib = prev + next
prev = next
next = fib | null |
150,987 | print(is_anagram("Amor", "Roma"))
print(reverse("Hola mundo"))
def is_prime():
for number in range(1, 101):
if number >= 2:
is_divisible = False
for index in range(2, number):
if number % index == 0:
is_divisible = True
bre... | null |
150,988 |
def reverse(text):
text_len = len(text)
reversed_text = ""
for index in range(0, text_len):
reversed_text += text[text_len - index - 1]
return reversed_text | null |
150,989 |
def sum_two_values(first_value, second_value):
return first_value + second_value | null |
150,990 |
def sum_two_values(
first_value, second_value): return first_value + second_value | null |
150,991 |
def multiply_values(
first_value, second_value): return first_value * second_value - 3 | null |
150,992 |
def sum_three_values(value):
return lambda first_value, second_value: first_value + second_value + value | null |
150,993 | print(my_result)
print(my_result)
def my_function():
print("Esto es una función") | null |
150,994 | print(my_result)
print(my_result)
def sum_two_values(first_value: int, second_value):
print(first_value + second_value) | null |
150,995 |
def sum_two_values_with_return(first_value, second_value):
my_sum = first_value + second_value
return my_sum | null |
150,996 | print(my_result)
print(my_result)
def print_name(name, surname):
print(f"{name} {surname}") | null |
150,997 | print(my_result)
print(my_result)
def print_name_with_default(name, surname, alias="Sin alias"):
print(f"{name} {surname} {alias}") | null |
150,998 | print(my_result)
print(my_result)
def print_upper_texts(*texts):
print(type(texts))
for text in texts:
print(text.upper()) | null |
150,999 |
def sumValue(numberOne, numberTwo, numberThree):
print(numberOne + numberTwo + numberThree) | null |
151,000 |
def printValue(value):
print(value) | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.