id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
1,759
import base64 import ctypes import itertools import os import re import ssl import struct import tempfile from .bindings import CFConst, CoreFoundation, Security def _assert_no_error(error, exception_class=None): """ Checks the return code and throws an exception if there is an error to report """ i...
This function creates a temporary Mac keychain that we can use to work with credentials. This keychain uses a one-time password and a temporary file to store the data. We expect to have one keychain per socket. The returned SecKeychainRef must be freed by the caller, including calling SecKeychainDelete. Returns a tuple...
1,760
import base64 import ctypes import itertools import os import re import ssl import struct import tempfile from .bindings import CFConst, CoreFoundation, Security def _assert_no_error(error, exception_class=None): """ Checks the return code and throws an exception if there is an error to report """ i...
Load certificates and maybe keys from a number of files. Has the end goal of returning a CFArray containing one SecIdentityRef, and then zero or more SecCertificateRef objects, suitable for use as a client certificate trust chain.
1,761
import base64 import ctypes import itertools import os import re import ssl import struct import tempfile from .bindings import CFConst, CoreFoundation, Security TLS_PROTOCOL_VERSIONS = { "SSLv2": (0, 2), "SSLv3": (3, 0), "TLSv1": (3, 1), "TLSv1.1": (3, 2), "TLSv1.2": (3, 3), } The provided code sn...
Builds a TLS alert record for an unknown CA.
1,762
from __future__ import absolute_import import contextlib import ctypes import errno import os.path import shutil import socket import ssl import struct import threading import weakref import six from .. import util from ..util.ssl_ import PROTOCOL_TLS_CLIENT from ._securetransport.bindings import CoreFoundation, Securi...
Monkey-patch urllib3 with SecureTransport-backed SSL-support.
1,763
from __future__ import absolute_import import contextlib import ctypes import errno import os.path import shutil import socket import ssl import struct import threading import weakref import six from .. import util from ..util.ssl_ import PROTOCOL_TLS_CLIENT from ._securetransport.bindings import CoreFoundation, Securi...
Undo monkey-patching by :func:`inject_into_urllib3`.
1,764
from __future__ import absolute_import import contextlib import ctypes import errno import os.path import shutil import socket import ssl import struct import threading import weakref import six from .. import util from ..util.ssl_ import PROTOCOL_TLS_CLIENT from ._securetransport.bindings import CoreFoundation, Securi...
SecureTransport read callback. This is called by ST to request that data be returned from the socket.
1,765
from __future__ import absolute_import import contextlib import ctypes import errno import os.path import shutil import socket import ssl import struct import threading import weakref import six from .. import util from ..util.ssl_ import PROTOCOL_TLS_CLIENT from ._securetransport.bindings import CoreFoundation, Securi...
SecureTransport write callback. This is called by ST to request that data actually be sent on the network.
1,766
from __future__ import absolute_import import contextlib import ctypes import errno import os.path import shutil import socket import ssl import struct import threading import weakref import six from .. import util from ..util.ssl_ import PROTOCOL_TLS_CLIENT from ._securetransport.bindings import CoreFoundation, Securi...
null
1,767
from __future__ import absolute_import import contextlib import ctypes import errno import os.path import shutil import socket import ssl import struct import threading import weakref import six from .. import util from ..util.ssl_ import PROTOCOL_TLS_CLIENT from ._securetransport.bindings import CoreFoundation, Securi...
null
1,768
import os The provided code snippet includes necessary dependencies for implementing the `is_prod_appengine_mvms` function. Write a Python function `def is_prod_appengine_mvms()` to solve the following problem: Deprecated. Here is the function: def is_prod_appengine_mvms(): """Deprecated.""" return False
Deprecated.
1,769
from __future__ import absolute_import import OpenSSL.crypto import OpenSSL.SSL from cryptography import x509 from cryptography.hazmat.backends.openssl import backend as openssl_backend from io import BytesIO from socket import error as SocketError from socket import timeout import logging import ssl import sys import ...
Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.
1,770
from __future__ import absolute_import import OpenSSL.crypto import OpenSSL.SSL from cryptography import x509 from cryptography.hazmat.backends.openssl import backend as openssl_backend from io import BytesIO from socket import error as SocketError from socket import timeout import logging import ssl import sys import ...
Undo monkey-patching by :func:`inject_into_urllib3`.
1,771
from __future__ import absolute_import import OpenSSL.crypto import OpenSSL.SSL from cryptography import x509 from cryptography.hazmat.backends.openssl import backend as openssl_backend try: from cryptography.x509 import UnsupportedExtension except ImportError: # UnsupportedExtension is gone in cryptography >= ...
Given an PyOpenSSL certificate, provides all the subject alternative names.
1,772
from __future__ import absolute_import import OpenSSL.crypto import OpenSSL.SSL from cryptography import x509 from cryptography.hazmat.backends.openssl import backend as openssl_backend from io import BytesIO from socket import error as SocketError from socket import timeout import logging import ssl import sys import ...
null
1,773
from __future__ import absolute_import import OpenSSL.crypto import OpenSSL.SSL from cryptography import x509 from cryptography.hazmat.backends.openssl import backend as openssl_backend from io import BytesIO from socket import error as SocketError from socket import timeout import logging import ssl import sys import ...
null
1,774
from __future__ import absolute_import import errno import logging import re import socket import sys import warnings from socket import error as SocketError from socket import timeout as SocketTimeout from .connection import ( BaseSSLError, BrokenPipeError, DummyConnection, HTTPConnection, HTTPExce...
Given a url, return an :class:`.ConnectionPool` instance of its host. This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an :class:`.ConnectionPool` instance. :param url: Absolute URL string that must include the scheme. Port is optional. :param \\**kw: Passes additiona...
1,775
from __future__ import absolute_import import errno import logging import re import socket import sys import warnings from socket import error as SocketError from socket import timeout as SocketTimeout from .connection import ( BaseSSLError, BrokenPipeError, DummyConnection, HTTPConnection, HTTPExce...
Normalize hosts for comparisons and use with sockets.
1,776
from __future__ import absolute_import import email.utils import mimetypes import re from .packages import six The provided code snippet includes necessary dependencies for implementing the `guess_content_type` function. Write a Python function `def guess_content_type(filename, default="application/octet-stream")` to ...
Guess the "Content-Type" of a file. :param filename: The filename to guess the "Content-Type" of using :mod:`mimetypes`. :param default: If no "Content-Type" can be guessed, default to `default`.
1,777
from __future__ import absolute_import import email.utils import mimetypes import re from .packages import six The provided code snippet includes necessary dependencies for implementing the `format_header_param_rfc2231` function. Write a Python function `def format_header_param_rfc2231(name, value)` to solve the follo...
Helper function to format and quote a single header parameter using the strategy defined in RFC 2231. Particularly useful for header parameters which might contain non-ASCII values, like file names. This follows `RFC 2388 Section 4.4 <https://tools.ietf.org/html/rfc2388#section-4.4>`_. :param name: The name of the para...
1,778
from __future__ import absolute_import import email.utils import mimetypes import re from .packages import six _HTML5_REPLACEMENTS = { u"\u0022": u"%22", # Replace "\" with "\\". u"\u005C": u"\u005C\u005C", } _HTML5_REPLACEMENTS.update( { six.unichr(cc): u"%{:02X}".format(cc) for cc in r...
Helper function to format and quote a single header parameter using the HTML5 strategy. Particularly useful for header parameters which might contain non-ASCII values, like file names. This follows the `HTML5 Working Draft Section 4.10.22.7`_ and matches the behavior of curl and modern browsers. .. _HTML5 Working Draft...
1,779
from __future__ import absolute_import import io import logging import sys import warnings import zlib from contextlib import contextmanager from socket import error as SocketError from socket import timeout as SocketTimeout from . import util from ._collections import HTTPHeaderDict from .connection import BaseSSLErro...
null
1,780
from __future__ import absolute_import import collections import functools import logging from ._collections import RecentlyUsedContainer from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme from .exceptions import ( LocationValueError, MaxRetryError, ProxySchemeUnknown, P...
Create a pool key out of a request context dictionary. According to RFC 3986, both the scheme and host are case-insensitive. Therefore, this function normalizes both before constructing the pool key for an HTTPS request. If you wish to change this behaviour, provide alternate callables to ``key_fn_by_scheme``. :param k...
1,781
from __future__ import absolute_import import collections import functools import logging from ._collections import RecentlyUsedContainer from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme from .exceptions import ( LocationValueError, MaxRetryError, ProxySchemeUnknown, P...
null
1,782
from __future__ import absolute_import import functools import itertools import operator import sys import types The provided code snippet includes necessary dependencies for implementing the `_add_doc` function. Write a Python function `def _add_doc(func, doc)` to solve the following problem: Add documentation to a f...
Add documentation to a function.
1,783
from __future__ import absolute_import import functools import itertools import operator import sys import types if sys.platform == "win32": _moved_attributes += [ MovedModule("winreg", "_winreg"), ] if sys.version_info[:2] > (3,): exec_( """def raise_from(value, from_value): try: ...
Import module, returning the module after the last dot.
1,784
from __future__ import absolute_import import functools import itertools import operator import sys import types class _MovedItems(_LazyModule): """Lazy loading of moved objects""" __path__ = [] # mark as package _MovedItems._moved_attributes = _moved_attributes The provided code snippet includes necessary de...
Add an item to six.moves.
1,785
from __future__ import absolute_import import functools import itertools import operator import sys import types class _MovedItems(_LazyModule): """Lazy loading of moved objects""" __path__ = [] # mark as package _MovedItems._moved_attributes = _moved_attributes moves = _MovedItems(__name__ + ".moves") The pr...
Remove item from six.moves.
1,786
from __future__ import absolute_import import functools import itertools import operator import sys import types next = advance_iterator def advance_iterator(it): return it.next()
null
1,787
from __future__ import absolute_import import functools import itertools import operator import sys import types def callable(obj): return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
null
1,788
from __future__ import absolute_import import functools import itertools import operator import sys import types def create_unbound_method(func, cls): return func
null
1,789
from __future__ import absolute_import import functools import itertools import operator import sys import types def get_unbound_function(unbound): return unbound.im_func
null
1,790
from __future__ import absolute_import import functools import itertools import operator import sys import types def create_bound_method(func, obj): return types.MethodType(func, obj, obj.__class__)
null
1,791
from __future__ import absolute_import import functools import itertools import operator import sys import types def create_unbound_method(func, cls): return types.MethodType(func, None, cls)
null
1,792
from __future__ import absolute_import import functools import itertools import operator import sys import types def iterkeys(d, **kw): return iter(d.keys(**kw))
null
1,793
from __future__ import absolute_import import functools import itertools import operator import sys import types def itervalues(d, **kw): return iter(d.values(**kw))
null
1,794
from __future__ import absolute_import import functools import itertools import operator import sys import types def iterlists(d, **kw): return iter(d.lists(**kw))
null
1,795
from __future__ import absolute_import import functools import itertools import operator import sys import types def iterkeys(d, **kw): return d.iterkeys(**kw)
null
1,796
from __future__ import absolute_import import functools import itertools import operator import sys import types def itervalues(d, **kw): return d.itervalues(**kw)
null
1,797
from __future__ import absolute_import import functools import itertools import operator import sys import types def iterlists(d, **kw): return d.iterlists(**kw)
null
1,798
from __future__ import absolute_import import functools import itertools import operator import sys import types def u(s): return s
null
1,799
from __future__ import absolute_import import functools import itertools import operator import sys import types def u(s): return unicode(s.replace(r"\\", r"\\\\"), "unicode_escape")
null
1,800
from __future__ import absolute_import import functools import itertools import operator import sys import types def byte2int(bs): return ord(bs[0])
null
1,801
from __future__ import absolute_import import functools import itertools import operator import sys import types def indexbytes(buf, i): return ord(buf[i])
null
1,802
from __future__ import absolute_import import functools import itertools import operator import sys import types def assertCountEqual(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs)
null
1,803
from __future__ import absolute_import import functools import itertools import operator import sys import types def assertRaisesRegex(self, *args, **kwargs): return getattr(self, _assertRaisesRegex)(*args, **kwargs)
null
1,804
from __future__ import absolute_import import functools import itertools import operator import sys import types def assertRegex(self, *args, **kwargs): return getattr(self, _assertRegex)(*args, **kwargs)
null
1,805
from __future__ import absolute_import import functools import itertools import operator import sys import types def assertNotRegex(self, *args, **kwargs): return getattr(self, _assertNotRegex)(*args, **kwargs)
null
1,806
from __future__ import absolute_import import functools import itertools import operator import sys import types def reraise(tp, value, tb=None): try: if value is None: value = tp() if value.__traceback__ is not tb: raise value.with_traceback(tb) ...
null
1,807
from __future__ import absolute_import import functools import itertools import operator import sys import types if sys.platform == "win32": _moved_attributes += [ MovedModule("winreg", "_winreg"), ] if sys.version_info[:2] > (3,): exec_( """def raise_from(value, from_value): try: ...
Execute code in a namespace.
1,808
from __future__ import absolute_import import functools import itertools import operator import sys import types if sys.platform == "win32": _moved_attributes += [ MovedModule("winreg", "_winreg"), ] if sys.version_info[:2] > (3,): exec_( """def raise_from(value, from_value): try: ...
The new-style print function for Python 2.4 and 2.5.
1,809
from __future__ import absolute_import import functools import itertools import operator import sys import types if sys.platform == "win32": _moved_attributes += [ MovedModule("winreg", "_winreg"), ] if sys.version_info[:2] > (3,): exec_( """def raise_from(value, from_value): try: ...
null
1,810
from __future__ import absolute_import import functools import itertools import operator import sys import types if sys.version_info[0:2] < (3, 4): # This does exactly the same what the :func:`py3:functools.update_wrapper` # function does on Python versions after 3.2. It sets the ``__wrapped__`` # attribute...
null
1,811
from __future__ import absolute_import import functools import itertools import operator import sys import types if sys.platform == "win32": _moved_attributes += [ MovedModule("winreg", "_winreg"), ] if sys.version_info[:2] > (3,): exec_( """def raise_from(value, from_value): try: ...
Create a base class with a metaclass.
1,812
from __future__ import absolute_import import functools import itertools import operator import sys import types The provided code snippet includes necessary dependencies for implementing the `add_metaclass` function. Write a Python function `def add_metaclass(metaclass)` to solve the following problem: Class decorato...
Class decorator for creating a class with a metaclass.
1,813
from __future__ import absolute_import import functools import itertools import operator import sys import types The provided code snippet includes necessary dependencies for implementing the `ensure_binary` function. Write a Python function `def ensure_binary(s, encoding="utf-8", errors="strict")` to solve the follow...
Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes`
1,814
from __future__ import absolute_import import functools import itertools import operator import sys import types PY2 = sys.version_info[0] == 2 The provided code snippet includes necessary dependencies for implementing the `python_2_unicode_compatible` function. Write a Python function `def python_2_unicode_compatible...
A class decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class.
1,815
from __future__ import absolute_import import datetime import logging import os import re import socket import warnings from socket import error as SocketError from socket import timeout as SocketTimeout from .packages import six from .packages.six.moves.http_client import HTTPConnection as _HTTPConnection from .packag...
null
1,816
from __future__ import absolute_import import datetime import logging import os import re import socket import warnings from socket import error as SocketError from socket import timeout as SocketTimeout from .packages import six from .packages.six.moves.http_client import HTTPConnection as _HTTPConnection from .packag...
null
1,817
from __future__ import absolute_import import re from collections import namedtuple from ..exceptions import LocationParseError from ..packages import six The provided code snippet includes necessary dependencies for implementing the `split_first` function. Write a Python function `def split_first(s, delims)` to solve...
.. deprecated:: 1.25 Given a string and an iterable of delimiters, split on the first found delimiter. Return two split parts and the matched delimiter. If not found, then the first part is the full input string. Example:: >>> split_first('foo/bar?baz', '?/=') ('foo', 'bar?baz', '/') >>> split_first('foo/bar?baz', '123...
1,818
from __future__ import absolute_import import re from collections import namedtuple from ..exceptions import LocationParseError from ..packages import six TARGET_RE = re.compile(r"^(/[^?#]*)(?:\?([^#]*))?(?:#.*)?$") PATH_CHARS = USERINFO_CHARS | {"@", "/"} QUERY_CHARS = FRAGMENT_CHARS = PATH_CHARS | {"?"} def _encode_i...
Percent-encodes a request target so that there are no invalid characters
1,819
from __future__ import absolute_import from email.errors import MultipartInvariantViolationDefect, StartBoundaryNotFoundDefect from ..exceptions import HeaderParsingError from ..packages.six.moves import http_client as httplib The provided code snippet includes necessary dependencies for implementing the `is_fp_closed...
Checks whether a given file-like object is closed. :param obj: The file-like object to check.
1,820
from __future__ import absolute_import from email.errors import MultipartInvariantViolationDefect, StartBoundaryNotFoundDefect from ..exceptions import HeaderParsingError from ..packages.six.moves import http_client as httplib class HeaderParsingError(HTTPError): """Raised by assert_header_parsing, but we convert ...
Asserts whether all headers have been successfully parsed. Extracts encountered errors from the result of parsing headers. Only works on Python 3. :param http.client.HTTPMessage headers: Headers to verify. :raises urllib3.exceptions.HeaderParsingError: If parsing errors are found.
1,821
from __future__ import absolute_import from email.errors import MultipartInvariantViolationDefect, StartBoundaryNotFoundDefect from ..exceptions import HeaderParsingError from ..packages.six.moves import http_client as httplib The provided code snippet includes necessary dependencies for implementing the `is_response_...
Checks whether the request of a response has been a HEAD-request. Handles the quirks of AppEngine. :param http.client.HTTPResponse response: Response to check if the originating request used 'HEAD' as a method.
1,822
from __future__ import absolute_import from base64 import b64encode from ..exceptions import UnrewindableBodyError from ..packages.six import b, integer_types ACCEPT_ENCODING = "gzip,deflate" The provided code snippet includes necessary dependencies for implementing the `make_headers` function. Write a Python function...
Shortcuts for generating request headers. :param keep_alive: If ``True``, adds 'connection: keep-alive' header. :param accept_encoding: Can be a boolean, list, or string. ``True`` translates to 'gzip,deflate'. List will get joined by comma. String will be used as provided. :param user_agent: String representing the use...
1,823
from __future__ import absolute_import from base64 import b64encode from ..exceptions import UnrewindableBodyError from ..packages.six import b, integer_types _FAILEDTELL = object() def rewind_body(body, body_pos): """ Attempt to rewind body to a certain position. Primarily used for request redirects and re...
If a position is provided, move file to that point. Otherwise, we'll attempt to record a position for future use.
1,824
import errno import select import sys from functools import partial def wait_for_socket(*args, **kwargs): # We delay choosing which implementation to use until the first time we're # called. We could do it at import time, but then we might make the wrong # decision if someone goes wild with monkeypatching s...
Waits for writing to be available on a given socket. Returns True if the socket is readable, or False if the timeout expired.
1,825
from __future__ import absolute_import import hmac import os import sys import warnings from binascii import hexlify, unhexlify from hashlib import md5, sha1, sha256 from ..exceptions import ( InsecurePlatformWarning, ProxySchemeUnsupported, SNIMissingWarning, SSLError, ) from ..packages import six from...
Compare two digests of equal length in constant time. The digests must be of type str/bytes. Returns True if the digests match, and False otherwise.
1,826
from __future__ import absolute_import import hmac import os import sys import warnings from binascii import hexlify, unhexlify from hashlib import md5, sha1, sha256 from ..exceptions import ( InsecurePlatformWarning, ProxySchemeUnsupported, SNIMissingWarning, SSLError, ) from ..packages import six from...
Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons.
1,827
from __future__ import absolute_import import hmac import os import sys import warnings from binascii import hexlify, unhexlify from hashlib import md5, sha1, sha256 from ..exceptions import ( InsecurePlatformWarning, ProxySchemeUnsupported, SNIMissingWarning, SSLError, ) from ..packages import six from...
All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be ...
1,828
from .ssl_ import create_urllib3_context, resolve_cert_reqs, resolve_ssl_version The provided code snippet includes necessary dependencies for implementing the `connection_requires_http_tunnel` function. Write a Python function `def connection_requires_http_tunnel( proxy_url=None, proxy_config=None, destination_sc...
Returns True if the connection requires an HTTP CONNECT through the proxy. :param URL proxy_url: URL of the proxy. :param ProxyConfig proxy_config: Proxy configuration from poolmanager.py :param str destination_scheme: The scheme of the destination. (i.e https, http, etc)
1,829
from .ssl_ import create_urllib3_context, resolve_cert_reqs, resolve_ssl_version def resolve_cert_reqs(candidate): """ Resolves the argument to a numeric constant, which can be passed to the wrap_socket function/method from the ssl module. Defaults to :data:`ssl.CERT_REQUIRED`. If given a string it...
Generates a default proxy ssl context if one hasn't been provided by the user.
1,830
from __future__ import absolute_import import socket from ..contrib import _appengine_environ from ..exceptions import LocationParseError from ..packages import six from .wait import NoWayToWaitForSocketError, wait_for_read class NoWayToWaitForSocketError(Exception): pass def wait_for_read(sock, tim...
Returns True if the connection is dropped and should be closed. :param conn: :class:`http.client.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycling transparently for us.
1,831
from __future__ import absolute_import import socket from ..contrib import _appengine_environ from ..exceptions import LocationParseError from ..packages import six from .wait import NoWayToWaitForSocketError, wait_for_read def _set_socket_options(sock, options): if options is None: return for opt in op...
Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default time...
1,832
from __future__ import absolute_import import socket from ..contrib import _appengine_environ from ..exceptions import LocationParseError from ..packages import six from .wait import NoWayToWaitForSocketError, wait_for_read The provided code snippet includes necessary dependencies for implementing the `_has_ipv6` func...
Returns True if the system can bind an IPv6 address.
1,833
import functools import math import warnings from collections.abc import Mapping, Sequence from ipaddress import ip_address from urllib.parse import SplitResult, parse_qsl, quote, urljoin, urlsplit, urlunsplit import idna from multidict import MultiDict, MultiDictProxy from ._quoting import _Quoter, _Unquoter def rewr...
null
1,834
import functools import math import warnings from collections.abc import Mapping, Sequence from ipaddress import ip_address from urllib.parse import SplitResult, parse_qsl, quote, urljoin, urlsplit, urlunsplit import idna from multidict import MultiDict, MultiDictProxy from ._quoting import _Quoter, _Unquoter def _hum...
null
1,835
import functools import math import warnings from collections.abc import Mapping, Sequence from ipaddress import ip_address from urllib.parse import SplitResult, parse_qsl, quote, urljoin, urlsplit, urlunsplit import idna from multidict import MultiDict, MultiDictProxy from ._quoting import _Quoter, _Unquoter def _idna...
null
1,836
import functools import math import warnings from collections.abc import Mapping, Sequence from ipaddress import ip_address from urllib.parse import SplitResult, parse_qsl, quote, urljoin, urlsplit, urlunsplit import idna from multidict import MultiDict, MultiDictProxy from ._quoting import _Quoter, _Unquoter def _idna...
null
1,837
import functools import math import warnings from collections.abc import Mapping, Sequence from ipaddress import ip_address from urllib.parse import SplitResult, parse_qsl, quote, urljoin, urlsplit, urlunsplit import idna from multidict import MultiDict, MultiDictProxy from ._quoting import _Quoter, _Unquoter _MAXCACHE...
null
1,838
import sys if sys.version_info >= (3, 11): from importlib.resources import as_file, files _CACERT_CTX = None _CACERT_PATH = None elif sys.version_info >= (3, 7): from importlib.resources import path as get_path, read_text _CACERT_CTX = None _CACERT_PATH = None else: import os import type...
null
1,839
import bpy import openai import re import os import sys def get_api_key(context, addon_name): preferences = context.preferences addon_prefs = preferences.addons[addon_name].preferences return addon_prefs.api_key
null
1,840
import bpy import openai import re import os import sys def init_props(): bpy.types.Scene.gpt4_chat_history = bpy.props.CollectionProperty(type=bpy.types.PropertyGroup) bpy.types.Scene.gpt4_model = bpy.props.EnumProperty( name="GPT Model", description="Select the GPT model to use", items=[ ...
null
1,841
import bpy import openai import re import os import sys def clear_props(): del bpy.types.Scene.gpt4_chat_history del bpy.types.Scene.gpt4_chat_input del bpy.types.Scene.gpt4_button_pressed
null
1,842
import bpy import openai import re import os import sys def generate_blender_code(prompt, chat_history, context, system_prompt): messages = [{"role": "system", "content": system_prompt}] for message in chat_history[-10:]: if message.type == "assistant": messages.append({"role": "assistant",...
null
1,843
import bpy import openai import re import os import sys def split_area_to_text_editor(context): area = context.area for region in area.regions: if region.type == 'WINDOW': override = {'area': area, 'region': region} bpy.ops.screen.area_split(override, direction='VERTICAL', facto...
null
1,844
import torch import random from transformers.optimization import AdamW from transformers import ( get_polynomial_decay_schedule_with_warmup, get_cosine_schedule_with_warmup, ) from vilt.modules.dist_utils import all_gather from vilt.modules.objectives import compute_irtr_recall from vilt.gadgets.my_metrics impo...
null
1,845
import torch import random from transformers.optimization import AdamW from transformers import ( get_polynomial_decay_schedule_with_warmup, get_cosine_schedule_with_warmup, ) from vilt.modules.dist_utils import all_gather from vilt.modules.objectives import compute_irtr_recall from vilt.gadgets.my_metrics impo...
null
1,846
import torch import random from transformers.optimization import AdamW from transformers import ( get_polynomial_decay_schedule_with_warmup, get_cosine_schedule_with_warmup, ) from vilt.modules.dist_utils import all_gather from vilt.modules.objectives import compute_irtr_recall from vilt.gadgets.my_metrics impo...
null
1,847
import torch import random from transformers.optimization import AdamW from transformers import ( get_polynomial_decay_schedule_with_warmup, get_cosine_schedule_with_warmup, ) from vilt.modules.dist_utils import all_gather from vilt.modules.objectives import compute_irtr_recall from vilt.gadgets.my_metrics impo...
null
1,848
import torch import random from transformers.optimization import AdamW from transformers import ( get_polynomial_decay_schedule_with_warmup, get_cosine_schedule_with_warmup, ) from vilt.modules.dist_utils import all_gather from vilt.modules.objectives import compute_irtr_recall from vilt.gadgets.my_metrics impo...
null
1,849
import functools import logging import numpy as np import pickle import torch import torch.distributed as dist import torch _LOCAL_PROCESS_GROUP = None def get_rank() -> int: if not dist.is_available(): return 0 if not dist.is_initialized(): return 0 return dist.get_rank() The provided code...
Returns: The rank of the current process within the local (per-machine) process group.
1,850
import functools import logging import numpy as np import pickle import torch import torch.distributed as dist import torch _LOCAL_PROCESS_GROUP = None def get_world_size() -> int: if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size() The p...
Returns: The size of the per-machine process group, i.e. the number of processes per machine.
1,851
import functools import logging import numpy as np import pickle import torch import torch.distributed as dist import torch def get_rank() -> int: if not dist.is_available(): return 0 if not dist.is_initialized(): return 0 return dist.get_rank() def is_main_process() -> bool: return get...
null
1,852
import functools import logging import numpy as np import pickle import torch import torch.distributed as dist import torch def get_world_size() -> int: if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size() The provided code snippet include...
Helper function to synchronize (barrier) among all processes when using distributed training
1,853
import functools import logging import numpy as np import pickle import torch import torch.distributed as dist import torch def get_world_size() -> int: if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size() def get_rank() -> int: if not ...
Run gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object dst (int): destination rank group: a torch process group. By default, will use a group which contains all ranks on gloo backend. Returns: list[data]: on dst, a list of data gathered from each rank. Otherwise, an empty lis...
1,854
import functools import logging import numpy as np import pickle import torch import torch.distributed as dist import torch def all_gather(data, group=None): """ Run all_gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object group: a torch process grou...
Returns: int: a random number that is the same across all workers. If workers need a shared RNG, they can use this shared seed to create one. All workers must call this function, otherwise it will deadlock.
1,855
import functools import logging import numpy as np import pickle import torch import torch.distributed as dist import torch def get_world_size() -> int: if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size() def get_rank() -> int: if not ...
Reduce the values in the dictionary from all processes so that process with rank 0 has the reduced results. Args: input_dict (dict): inputs to be reduced. All the values must be scalar CUDA Tensor. average (bool): whether to do average or sum Returns: a dict with the same keys as input_dict, after reduction.
1,856
import torch import torch.nn as nn import torch.nn.functional as F import os import glob import json import tqdm import functools from torch.utils.data.distributed import DistributedSampler from einops import rearrange from vilt.modules.dist_utils import all_gather def cost_matrix_cosine(x, y, eps=1e-5): """Compute...
[B, M, D], [B, N, D], [B, M], [B, N]
1,857
import torch import torch.nn as nn import torch.nn.functional as F import os import glob import json import tqdm import functools from torch.utils.data.distributed import DistributedSampler from einops import rearrange from vilt.modules.dist_utils import all_gather def compute_mlm(pl_module, batch): infer = pl_mod...
null
1,858
import torch import torch.nn as nn import torch.nn.functional as F import os import glob import json import tqdm import functools from torch.utils.data.distributed import DistributedSampler from einops import rearrange from vilt.modules.dist_utils import all_gather def compute_mpp(pl_module, batch): infer = pl_mod...
null