Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
UpdateCacheMiddleware.process_response
(self, request, response)
Sets the cache, if needed.
Sets the cache, if needed.
def process_response(self, request, response): """Sets the cache, if needed.""" if not self._should_update_cache(request, response): # We don't need to update the cache, just return. return response if response.streaming or response.status_code not in (200, 304): ...
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "if", "not", "self", ".", "_should_update_cache", "(", "request", ",", "response", ")", ":", "# We don't need to update the cache, just return.", "return", "response", "if", "response...
[ 73, 4 ]
[ 105, 23 ]
python
en
['en', 'en', 'en']
True
FetchFromCacheMiddleware.process_request
(self, request)
Checks whether the page is already cached and returns the cached version if available.
Checks whether the page is already cached and returns the cached version if available.
def process_request(self, request): """ Checks whether the page is already cached and returns the cached version if available. """ if request.method not in ('GET', 'HEAD'): request._cache_update_cache = False return None # Don't bother checking the cache....
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "if", "request", ".", "method", "not", "in", "(", "'GET'", ",", "'HEAD'", ")", ":", "request", ".", "_cache_update_cache", "=", "False", "return", "None", "# Don't bother checking the cache.", "#...
[ 122, 4 ]
[ 148, 23 ]
python
en
['en', 'error', 'th']
False
decide_user_install
( use_user_site, # type: Optional[bool] prefix_path=None, # type: Optional[str] target_dir=None, # type: Optional[str] root_path=None, # type: Optional[str] isolated_mode=False, # type: bool )
Determine whether to do a user install based on the input options. If use_user_site is False, no additional checks are done. If use_user_site is True, it is checked for compatibility with other options. If use_user_site is None, the default behaviour depends on the environment, which is provided by...
Determine whether to do a user install based on the input options.
def decide_user_install( use_user_site, # type: Optional[bool] prefix_path=None, # type: Optional[str] target_dir=None, # type: Optional[str] root_path=None, # type: Optional[str] isolated_mode=False, # type: bool ): # type: (...) -> bool """Determine whether to do a user install based ...
[ "def", "decide_user_install", "(", "use_user_site", ",", "# type: Optional[bool]", "prefix_path", "=", "None", ",", "# type: Optional[str]", "target_dir", "=", "None", ",", "# type: Optional[str]", "root_path", "=", "None", ",", "# type: Optional[str]", "isolated_mode", "...
[ 599, 0 ]
[ 656, 15 ]
python
en
['en', 'en', 'en']
True
reject_location_related_install_options
(requirements, options)
If any location-changing --install-option arguments were passed for requirements or on the command-line, then show a deprecation warning.
If any location-changing --install-option arguments were passed for requirements or on the command-line, then show a deprecation warning.
def reject_location_related_install_options(requirements, options): # type: (List[InstallRequirement], Optional[List[str]]) -> None """If any location-changing --install-option arguments were passed for requirements or on the command-line, then show a deprecation warning. """ def format_options(opti...
[ "def", "reject_location_related_install_options", "(", "requirements", ",", "options", ")", ":", "# type: (List[InstallRequirement], Optional[List[str]]) -> None", "def", "format_options", "(", "option_names", ")", ":", "# type: (Iterable[str]) -> List[str]", "return", "[", "\"--...
[ 659, 0 ]
[ 698, 5 ]
python
en
['en', 'en', 'en']
True
create_env_error_message
(error, show_traceback, using_user_site)
Format an error message for an EnvironmentError It may occur anytime during the execution of the install command.
Format an error message for an EnvironmentError
def create_env_error_message(error, show_traceback, using_user_site): # type: (EnvironmentError, bool, bool) -> str """Format an error message for an EnvironmentError It may occur anytime during the execution of the install command. """ parts = [] # Mention the error if we are not going to sho...
[ "def", "create_env_error_message", "(", "error", ",", "show_traceback", ",", "using_user_site", ")", ":", "# type: (EnvironmentError, bool, bool) -> str", "parts", "=", "[", "]", "# Mention the error if we are not going to show a traceback", "parts", ".", "append", "(", "\"Co...
[ 701, 0 ]
[ 735, 40 ]
python
br
['br', 'gl', 'en']
False
get_band_for_image
(image)
Returns the band number corresponding to a particular image
Returns the band number corresponding to a particular image
def get_band_for_image(image): """ Returns the band number corresponding to a particular image """ return tkp.db.execute(""" SELECT band FROM image WHERE image.id = %(id)s """, {"id": image.id}).fetchone()[0]
[ "def", "get_band_for_image", "(", "image", ")", ":", "return", "tkp", ".", "db", ".", "execute", "(", "\"\"\"\n SELECT band\n FROM image\n WHERE image.id = %(id)s\n \"\"\"", ",", "{", "\"id\"", ":", "image", ".", "id", "}", ")", ".", "fetchone"...
[ 9, 0 ]
[ 17, 40 ]
python
en
['en', 'error', 'th']
False
get_freq_for_image
(image)
Returns the stored frequency corresponding to a particular image
Returns the stored frequency corresponding to a particular image
def get_freq_for_image(image): """ Returns the stored frequency corresponding to a particular image """ return tkp.db.execute(""" SELECT freq_central FROM image ,frequencyband WHERE image.id = %(id)s AND image.band = frequencyband.id """, {"id": image.id...
[ "def", "get_freq_for_image", "(", "image", ")", ":", "return", "tkp", ".", "db", ".", "execute", "(", "\"\"\"\n SELECT freq_central\n FROM image\n ,frequencyband\n WHERE image.id = %(id)s\n AND image.band = frequencyband.id\n \"\"\"", ",", "{...
[ 20, 0 ]
[ 30, 40 ]
python
en
['en', 'error', 'th']
False
TestBand.test_frequency_range
(self)
Determine range of frequencies supported by DB schema.
Determine range of frequencies supported by DB schema.
def test_frequency_range(self): """ Determine range of frequencies supported by DB schema. """ dataset = DataSet(data={'description': self._testMethodName}, database=self.database) data = copy(self.image_data) data['freq_eff'] = 1e6 # 1MHz ...
[ "def", "test_frequency_range", "(", "self", ")", ":", "dataset", "=", "DataSet", "(", "data", "=", "{", "'description'", ":", "self", ".", "_testMethodName", "}", ",", "database", "=", "self", ".", "database", ")", "data", "=", "copy", "(", "self", ".", ...
[ 83, 4 ]
[ 104, 78 ]
python
en
['en', 'error', 'th']
False
TestBand.test_max_bandwidth
(self)
Test if setting max bandwidth correctly affects the band of images
Test if setting max bandwidth correctly affects the band of images
def test_max_bandwidth(self): """ Test if setting max bandwidth correctly affects the band of images """ data = copy(self.image_data) dataset_data = {'description': self._testMethodName} dataset = DataSet(data=dataset_data, database=self.database) data['freq_eff'...
[ "def", "test_max_bandwidth", "(", "self", ")", ":", "data", "=", "copy", "(", "self", ".", "image_data", ")", "dataset_data", "=", "{", "'description'", ":", "self", ".", "_testMethodName", "}", "dataset", "=", "DataSet", "(", "data", "=", "dataset_data", ...
[ 107, 4 ]
[ 133, 97 ]
python
en
['en', 'error', 'th']
False
HashPermutationMapper.__init__
(self, hash_name)
Just keeps the name.
Just keeps the name.
def __init__(self, hash_name): """ Just keeps the name. """ super(HashPermutationMapper, self).__init__(hash_name) self.child_hashes = [] self.dim = None self.bucket_key_map = {}
[ "def", "__init__", "(", "self", ",", "hash_name", ")", ":", "super", "(", "HashPermutationMapper", ",", "self", ")", ".", "__init__", "(", "hash_name", ")", "self", ".", "child_hashes", "=", "[", "]", "self", ".", "dim", "=", "None", "self", ".", "buck...
[ 44, 4 ]
[ 49, 32 ]
python
en
['en', 'en', 'en']
True
HashPermutationMapper.reset
(self, dim)
Resets / Initializes the hash for the specified dimension.
Resets / Initializes the hash for the specified dimension.
def reset(self, dim): """ Resets / Initializes the hash for the specified dimension. """ self.dim = dim self.bucket_key_map = {} # Reset all child hashes for child_hash in self.child_hashes: child_hash.reset(dim)
[ "def", "reset", "(", "self", ",", "dim", ")", ":", "self", ".", "dim", "=", "dim", "self", ".", "bucket_key_map", "=", "{", "}", "# Reset all child hashes", "for", "child_hash", "in", "self", ".", "child_hashes", ":", "child_hash", ".", "reset", "(", "di...
[ 51, 4 ]
[ 57, 33 ]
python
en
['en', 'en', 'en']
True
HashPermutationMapper.hash_vector
(self, v, querying=False)
Hashes the vector and returns the bucket key as string.
Hashes the vector and returns the bucket key as string.
def hash_vector(self, v, querying=False): """ Hashes the vector and returns the bucket key as string. """ bucket_keys = [] if querying: # If we are querying, use the bucket key map for lshash in self.child_hashes: # Get regular bucket key...
[ "def", "hash_vector", "(", "self", ",", "v", ",", "querying", "=", "False", ")", ":", "bucket_keys", "=", "[", "]", "if", "querying", ":", "# If we are querying, use the bucket key map", "for", "lshash", "in", "self", ".", "child_hashes", ":", "# Get regular buc...
[ 67, 4 ]
[ 109, 26 ]
python
en
['en', 'error', 'th']
False
HashPermutationMapper.get_config
(self)
Returns pickle-serializable configuration struct for storage.
Returns pickle-serializable configuration struct for storage.
def get_config(self): """ Returns pickle-serializable configuration struct for storage. """ return { 'hash_name': self.hash_name, 'dim': self.dim, 'bucket_key_map': self.bucket_key_map }
[ "def", "get_config", "(", "self", ")", ":", "return", "{", "'hash_name'", ":", "self", ".", "hash_name", ",", "'dim'", ":", "self", ".", "dim", ",", "'bucket_key_map'", ":", "self", ".", "bucket_key_map", "}" ]
[ 111, 4 ]
[ 119, 9 ]
python
en
['en', 'error', 'th']
False
HashPermutationMapper.apply_config
(self, config)
Applies config
Applies config
def apply_config(self, config): """ Applies config """ self.hash_name = config['hash_name'] self.dim = config['dim'] self.bucket_key_map = config['bucket_key_map']
[ "def", "apply_config", "(", "self", ",", "config", ")", ":", "self", ".", "hash_name", "=", "config", "[", "'hash_name'", "]", "self", ".", "dim", "=", "config", "[", "'dim'", "]", "self", ".", "bucket_key_map", "=", "config", "[", "'bucket_key_map'", "]...
[ 121, 4 ]
[ 127, 54 ]
python
en
['en', 'error', 'th']
False
HashPermutationMapper.add_child_hash
(self, child_hash)
Adds specified child hash. The hash must be one of the binary types.
Adds specified child hash.
def add_child_hash(self, child_hash): """ Adds specified child hash. The hash must be one of the binary types. """ # Hash must generate binary keys if not (isinstance(child_hash,PCABinaryProjections) or isinstance(child_hash,RandomBinaryProjections) or isinstance(child_...
[ "def", "add_child_hash", "(", "self", ",", "child_hash", ")", ":", "# Hash must generate binary keys", "if", "not", "(", "isinstance", "(", "child_hash", ",", "PCABinaryProjections", ")", "or", "isinstance", "(", "child_hash", ",", "RandomBinaryProjections", ")", "o...
[ 129, 4 ]
[ 142, 44 ]
python
en
['en', 'error', 'th']
False
check_panels_in_model
(cls, context='model')
Check panels configuration uses `panels` when `edit_handler` not in use.
Check panels configuration uses `panels` when `edit_handler` not in use.
def check_panels_in_model(cls, context='model'): """Check panels configuration uses `panels` when `edit_handler` not in use.""" from wagtail.admin.edit_handlers import BaseCompositeEditHandler, InlinePanel from wagtail.core.models import Page errors = [] if hasattr(cls, 'get_edit_handler'): ...
[ "def", "check_panels_in_model", "(", "cls", ",", "context", "=", "'model'", ")", ":", "from", "wagtail", ".", "admin", ".", "edit_handlers", "import", "BaseCompositeEditHandler", ",", "InlinePanel", "from", "wagtail", ".", "core", ".", "models", "import", "Page"...
[ 93, 0 ]
[ 153, 17 ]
python
en
['en', 'en', 'en']
True
contained_in
(filename, directory)
Test if a file is located within the given directory.
Test if a file is located within the given directory.
def contained_in(filename, directory): """Test if a file is located within the given directory.""" filename = os.path.normcase(os.path.abspath(filename)) directory = os.path.normcase(os.path.abspath(directory)) return os.path.commonprefix([filename, directory]) == directory
[ "def", "contained_in", "(", "filename", ",", "directory", ")", ":", "filename", "=", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(", "filename", ")", ")", "directory", "=", "os", ".", "path", ".", "normcase", "(", "os...
[ 67, 0 ]
[ 71, 67 ]
python
en
['en', 'en', 'en']
True
_build_backend
()
Find and load the build backend
Find and load the build backend
def _build_backend(): """Find and load the build backend""" # Add in-tree backend directories to the front of sys.path. backend_path = os.environ.get('PEP517_BACKEND_PATH') if backend_path: extra_pathitems = backend_path.split(os.pathsep) sys.path[:0] = extra_pathitems ep = os.envir...
[ "def", "_build_backend", "(", ")", ":", "# Add in-tree backend directories to the front of sys.path.", "backend_path", "=", "os", ".", "environ", ".", "get", "(", "'PEP517_BACKEND_PATH'", ")", "if", "backend_path", ":", "extra_pathitems", "=", "backend_path", ".", "spli...
[ 74, 0 ]
[ 99, 14 ]
python
en
['en', 'en', 'en']
True
get_requires_for_build_wheel
(config_settings)
Invoke the optional get_requires_for_build_wheel hook Returns [] if the hook is not defined.
Invoke the optional get_requires_for_build_wheel hook
def get_requires_for_build_wheel(config_settings): """Invoke the optional get_requires_for_build_wheel hook Returns [] if the hook is not defined. """ backend = _build_backend() try: hook = backend.get_requires_for_build_wheel except AttributeError: return [] else: r...
[ "def", "get_requires_for_build_wheel", "(", "config_settings", ")", ":", "backend", "=", "_build_backend", "(", ")", "try", ":", "hook", "=", "backend", ".", "get_requires_for_build_wheel", "except", "AttributeError", ":", "return", "[", "]", "else", ":", "return"...
[ 102, 0 ]
[ 113, 36 ]
python
en
['en', 'en', 'en']
True
prepare_metadata_for_build_wheel
( metadata_directory, config_settings, _allow_fallback)
Invoke optional prepare_metadata_for_build_wheel Implements a fallback by building a wheel if the hook isn't defined, unless _allow_fallback is False in which case HookMissing is raised.
Invoke optional prepare_metadata_for_build_wheel
def prepare_metadata_for_build_wheel( metadata_directory, config_settings, _allow_fallback): """Invoke optional prepare_metadata_for_build_wheel Implements a fallback by building a wheel if the hook isn't defined, unless _allow_fallback is False in which case HookMissing is raised. """ back...
[ "def", "prepare_metadata_for_build_wheel", "(", "metadata_directory", ",", "config_settings", ",", "_allow_fallback", ")", ":", "backend", "=", "_build_backend", "(", ")", "try", ":", "hook", "=", "backend", ".", "prepare_metadata_for_build_wheel", "except", "AttributeE...
[ 116, 0 ]
[ 132, 56 ]
python
en
['en', 'no', 'en']
True
_dist_info_files
(whl_zip)
Identify the .dist-info folder inside a wheel ZipFile.
Identify the .dist-info folder inside a wheel ZipFile.
def _dist_info_files(whl_zip): """Identify the .dist-info folder inside a wheel ZipFile.""" res = [] for path in whl_zip.namelist(): m = re.match(r'[^/\\]+-[^/\\]+\.dist-info/', path) if m: res.append(path) if res: return res raise Exception("No .dist-info folder ...
[ "def", "_dist_info_files", "(", "whl_zip", ")", ":", "res", "=", "[", "]", "for", "path", "in", "whl_zip", ".", "namelist", "(", ")", ":", "m", "=", "re", ".", "match", "(", "r'[^/\\\\]+-[^/\\\\]+\\.dist-info/'", ",", "path", ")", "if", "m", ":", "res"...
[ 138, 0 ]
[ 147, 58 ]
python
en
['en', 'fy', 'en']
True
_get_wheel_metadata_from_wheel
( backend, metadata_directory, config_settings)
Build a wheel and extract the metadata from it. Fallback for when the build backend does not define the 'get_wheel_metadata' hook.
Build a wheel and extract the metadata from it.
def _get_wheel_metadata_from_wheel( backend, metadata_directory, config_settings): """Build a wheel and extract the metadata from it. Fallback for when the build backend does not define the 'get_wheel_metadata' hook. """ from zipfile import ZipFile whl_basename = backend.build_wheel(met...
[ "def", "_get_wheel_metadata_from_wheel", "(", "backend", ",", "metadata_directory", ",", "config_settings", ")", ":", "from", "zipfile", "import", "ZipFile", "whl_basename", "=", "backend", ".", "build_wheel", "(", "metadata_directory", ",", "config_settings", ")", "w...
[ 150, 0 ]
[ 166, 37 ]
python
en
['en', 'en', 'en']
True
_find_already_built_wheel
(metadata_directory)
Check for a wheel already built during the get_wheel_metadata hook.
Check for a wheel already built during the get_wheel_metadata hook.
def _find_already_built_wheel(metadata_directory): """Check for a wheel already built during the get_wheel_metadata hook. """ if not metadata_directory: return None metadata_parent = os.path.dirname(metadata_directory) if not os.path.isfile(pjoin(metadata_parent, WHEEL_BUILT_MARKER)): ...
[ "def", "_find_already_built_wheel", "(", "metadata_directory", ")", ":", "if", "not", "metadata_directory", ":", "return", "None", "metadata_parent", "=", "os", ".", "path", ".", "dirname", "(", "metadata_directory", ")", "if", "not", "os", ".", "path", ".", "...
[ 169, 0 ]
[ 188, 23 ]
python
en
['en', 'en', 'en']
True
build_wheel
(wheel_directory, config_settings, metadata_directory=None)
Invoke the mandatory build_wheel hook. If a wheel was already built in the prepare_metadata_for_build_wheel fallback, this will copy it rather than rebuilding the wheel.
Invoke the mandatory build_wheel hook.
def build_wheel(wheel_directory, config_settings, metadata_directory=None): """Invoke the mandatory build_wheel hook. If a wheel was already built in the prepare_metadata_for_build_wheel fallback, this will copy it rather than rebuilding the wheel. """ prebuilt_whl = _find_already_built_wheel(m...
[ "def", "build_wheel", "(", "wheel_directory", ",", "config_settings", ",", "metadata_directory", "=", "None", ")", ":", "prebuilt_whl", "=", "_find_already_built_wheel", "(", "metadata_directory", ")", "if", "prebuilt_whl", ":", "shutil", ".", "copy2", "(", "prebuil...
[ 191, 0 ]
[ 204, 59 ]
python
en
['en', 'st', 'en']
True
get_requires_for_build_sdist
(config_settings)
Invoke the optional get_requires_for_build_wheel hook Returns [] if the hook is not defined.
Invoke the optional get_requires_for_build_wheel hook
def get_requires_for_build_sdist(config_settings): """Invoke the optional get_requires_for_build_wheel hook Returns [] if the hook is not defined. """ backend = _build_backend() try: hook = backend.get_requires_for_build_sdist except AttributeError: return [] else: r...
[ "def", "get_requires_for_build_sdist", "(", "config_settings", ")", ":", "backend", "=", "_build_backend", "(", ")", "try", ":", "hook", "=", "backend", ".", "get_requires_for_build_sdist", "except", "AttributeError", ":", "return", "[", "]", "else", ":", "return"...
[ 207, 0 ]
[ 218, 36 ]
python
en
['en', 'en', 'en']
True
build_sdist
(sdist_directory, config_settings)
Invoke the mandatory build_sdist hook.
Invoke the mandatory build_sdist hook.
def build_sdist(sdist_directory, config_settings): """Invoke the mandatory build_sdist hook.""" backend = _build_backend() try: return backend.build_sdist(sdist_directory, config_settings) except getattr(backend, 'UnsupportedOperation', _DummyException): raise GotUnsupportedOperation(tra...
[ "def", "build_sdist", "(", "sdist_directory", ",", "config_settings", ")", ":", "backend", "=", "_build_backend", "(", ")", "try", ":", "return", "backend", ".", "build_sdist", "(", "sdist_directory", ",", "config_settings", ")", "except", "getattr", "(", "backe...
[ 231, 0 ]
[ 237, 61 ]
python
en
['en', 'st', 'en']
True
ReactionEmojiTest.test_missing_emoji
(self)
Sending reaction without emoji fails
Sending reaction without emoji fails
def test_missing_emoji(self) -> None: """ Sending reaction without emoji fails """ sender = self.example_user("hamlet") reaction_info = { "emoji_name": "", } result = self.api_post(sender, "/api/v1/messages/1/reactions", reaction_info) self.as...
[ "def", "test_missing_emoji", "(", "self", ")", "->", "None", ":", "sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "reaction_info", "=", "{", "\"emoji_name\"", ":", "\"\"", ",", "}", "result", "=", "self", ".", "api_post", "(", "sender",...
[ 21, 4 ]
[ 31, 49 ]
python
en
['en', 'error', 'th']
False
ReactionEmojiTest.test_add_invalid_emoji
(self)
Sending invalid emoji fails
Sending invalid emoji fails
def test_add_invalid_emoji(self) -> None: """ Sending invalid emoji fails """ sender = self.example_user("hamlet") reaction_info = { "emoji_name": "foo", } result = self.api_post(sender, "/api/v1/messages/1/reactions", reaction_info) self.asse...
[ "def", "test_add_invalid_emoji", "(", "self", ")", "->", "None", ":", "sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "reaction_info", "=", "{", "\"emoji_name\"", ":", "\"foo\"", ",", "}", "result", "=", "self", ".", "api_post", "(", "s...
[ 33, 4 ]
[ 43, 68 ]
python
en
['en', 'error', 'th']
False
ReactionEmojiTest.test_add_deactivated_realm_emoji
(self)
Sending deactivated realm emoji fails.
Sending deactivated realm emoji fails.
def test_add_deactivated_realm_emoji(self) -> None: """ Sending deactivated realm emoji fails. """ emoji = RealmEmoji.objects.get(name="green_tick") emoji.deactivated = True emoji.save(update_fields=["deactivated"]) sender = self.example_user("hamlet") rea...
[ "def", "test_add_deactivated_realm_emoji", "(", "self", ")", "->", "None", ":", "emoji", "=", "RealmEmoji", ".", "objects", ".", "get", "(", "name", "=", "\"green_tick\"", ")", "emoji", ".", "deactivated", "=", "True", "emoji", ".", "save", "(", "update_fiel...
[ 45, 4 ]
[ 59, 75 ]
python
en
['en', 'error', 'th']
False
ReactionEmojiTest.test_valid_emoji
(self)
Reacting with valid emoji succeeds
Reacting with valid emoji succeeds
def test_valid_emoji(self) -> None: """ Reacting with valid emoji succeeds """ sender = self.example_user("hamlet") reaction_info = { "emoji_name": "smile", } base_query = Reaction.objects.filter( user_profile=sender, message=M...
[ "def", "test_valid_emoji", "(", "self", ")", "->", "None", ":", "sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "reaction_info", "=", "{", "\"emoji_name\"", ":", "\"smile\"", ",", "}", "base_query", "=", "Reaction", ".", "objects", ".", ...
[ 61, 4 ]
[ 83, 91 ]
python
en
['en', 'error', 'th']
False
ReactionEmojiTest.test_cached_reaction_data
(self)
Formatted reactions data is saved in cache.
Formatted reactions data is saved in cache.
def test_cached_reaction_data(self) -> None: """ Formatted reactions data is saved in cache. """ sender = self.example_user("hamlet") reaction_info = { "emoji_name": "smile", } result = self.api_post(sender, "/api/v1/messages/1/reactions", reaction_inf...
[ "def", "test_cached_reaction_data", "(", "self", ")", "->", "None", ":", "sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "reaction_info", "=", "{", "\"emoji_name\"", ":", "\"smile\"", ",", "}", "result", "=", "self", ".", "api_post", "(",...
[ 85, 4 ]
[ 113, 70 ]
python
en
['en', 'error', 'th']
False
ReactionEmojiTest.test_zulip_emoji
(self)
Reacting with zulip emoji succeeds
Reacting with zulip emoji succeeds
def test_zulip_emoji(self) -> None: """ Reacting with zulip emoji succeeds """ sender = self.example_user("hamlet") reaction_info = { "emoji_name": "zulip", "reaction_type": "zulip_extra_emoji", } base_query = Reaction.objects.filter( ...
[ "def", "test_zulip_emoji", "(", "self", ")", "->", "None", ":", "sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "reaction_info", "=", "{", "\"emoji_name\"", ":", "\"zulip\"", ",", "\"reaction_type\"", ":", "\"zulip_extra_emoji\"", ",", "}", ...
[ 115, 4 ]
[ 137, 86 ]
python
en
['en', 'error', 'th']
False
ReactionEmojiTest.test_valid_emoji_react_historical
(self)
Reacting with valid emoji on a historical message succeeds
Reacting with valid emoji on a historical message succeeds
def test_valid_emoji_react_historical(self) -> None: """ Reacting with valid emoji on a historical message succeeds """ stream_name = "Saxony" self.subscribe(self.example_user("cordelia"), stream_name) message_id = self.send_stream_message(self.example_user("cordelia"), s...
[ "def", "test_valid_emoji_react_historical", "(", "self", ")", "->", "None", ":", "stream_name", "=", "\"Saxony\"", "self", ".", "subscribe", "(", "self", ".", "example_user", "(", "\"cordelia\"", ")", ",", "stream_name", ")", "message_id", "=", "self", ".", "s...
[ 139, 4 ]
[ 167, 52 ]
python
en
['en', 'error', 'th']
False
ReactionEmojiTest.test_valid_realm_emoji
(self)
Reacting with valid realm emoji succeeds
Reacting with valid realm emoji succeeds
def test_valid_realm_emoji(self) -> None: """ Reacting with valid realm emoji succeeds """ sender = self.example_user("hamlet") reaction_info = { "emoji_name": "green_tick", "reaction_type": "realm_emoji", } result = self.api_post(sender,...
[ "def", "test_valid_realm_emoji", "(", "self", ")", "->", "None", ":", "sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "reaction_info", "=", "{", "\"emoji_name\"", ":", "\"green_tick\"", ",", "\"reaction_type\"", ":", "\"realm_emoji\"", ",", "...
[ 169, 4 ]
[ 181, 40 ]
python
en
['en', 'error', 'th']
False
ReactionEmojiTest.test_emoji_name_to_emoji_code
(self)
An emoji name is mapped canonically to emoji code.
An emoji name is mapped canonically to emoji code.
def test_emoji_name_to_emoji_code(self) -> None: """ An emoji name is mapped canonically to emoji code. """ realm = get_realm("zulip") realm_emoji = RealmEmoji.objects.get(name="green_tick") # Test active realm emoji. emoji_code, reaction_type = emoji_name_to_emo...
[ "def", "test_emoji_name_to_emoji_code", "(", "self", ")", "->", "None", ":", "realm", "=", "get_realm", "(", "\"zulip\"", ")", "realm_emoji", "=", "RealmEmoji", ".", "objects", ".", "get", "(", "name", "=", "\"green_tick\"", ")", "# Test active realm emoji.", "e...
[ 183, 4 ]
[ 236, 84 ]
python
en
['en', 'error', 'th']
False
ReactionMessageIDTest.test_missing_message_id
(self)
Reacting without a message_id fails
Reacting without a message_id fails
def test_missing_message_id(self) -> None: """ Reacting without a message_id fails """ sender = self.example_user("hamlet") reaction_info = { "emoji_name": "smile", } result = self.api_post(sender, "/api/v1/messages//reactions", reaction_info) ...
[ "def", "test_missing_message_id", "(", "self", ")", "->", "None", ":", "sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "reaction_info", "=", "{", "\"emoji_name\"", ":", "\"smile\"", ",", "}", "result", "=", "self", ".", "api_post", "(", ...
[ 240, 4 ]
[ 250, 49 ]
python
en
['en', 'error', 'th']
False
ReactionMessageIDTest.test_invalid_message_id
(self)
Reacting to an invalid message id fails
Reacting to an invalid message id fails
def test_invalid_message_id(self) -> None: """ Reacting to an invalid message id fails """ sender = self.example_user("hamlet") reaction_info = { "emoji_name": "smile", } result = self.api_post(sender, "/api/v1/messages/-1/reactions", reaction_info) ...
[ "def", "test_invalid_message_id", "(", "self", ")", "->", "None", ":", "sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "reaction_info", "=", "{", "\"emoji_name\"", ":", "\"smile\"", ",", "}", "result", "=", "self", ".", "api_post", "(", ...
[ 252, 4 ]
[ 262, 49 ]
python
en
['en', 'error', 'th']
False
ReactionMessageIDTest.test_inaccessible_message_id
(self)
Reacting to a inaccessible (for instance, private) message fails
Reacting to a inaccessible (for instance, private) message fails
def test_inaccessible_message_id(self) -> None: """ Reacting to a inaccessible (for instance, private) message fails """ pm_sender = self.example_user("hamlet") pm_recipient = self.example_user("othello") reaction_sender = self.example_user("iago") result = self....
[ "def", "test_inaccessible_message_id", "(", "self", ")", "->", "None", ":", "pm_sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "pm_recipient", "=", "self", ".", "example_user", "(", "\"othello\"", ")", "reaction_sender", "=", "self", ".", "...
[ 264, 4 ]
[ 286, 60 ]
python
en
['en', 'error', 'th']
False
ReactionTest.test_add_existing_reaction
(self)
Creating the same reaction twice fails
Creating the same reaction twice fails
def test_add_existing_reaction(self) -> None: """ Creating the same reaction twice fails """ pm_sender = self.example_user("hamlet") pm_recipient = self.example_user("othello") reaction_sender = pm_recipient pm = self.api_post( pm_sender, ...
[ "def", "test_add_existing_reaction", "(", "self", ")", "->", "None", ":", "pm_sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "pm_recipient", "=", "self", ".", "example_user", "(", "\"othello\"", ")", "reaction_sender", "=", "pm_recipient", "p...
[ 290, 4 ]
[ 318, 66 ]
python
en
['en', 'error', 'th']
False
ReactionTest.test_remove_nonexisting_reaction
(self)
Removing a reaction twice fails
Removing a reaction twice fails
def test_remove_nonexisting_reaction(self) -> None: """ Removing a reaction twice fails """ pm_sender = self.example_user("hamlet") pm_recipient = self.example_user("othello") reaction_sender = pm_recipient pm = self.api_post( pm_sender, "...
[ "def", "test_remove_nonexisting_reaction", "(", "self", ")", "->", "None", ":", "pm_sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "pm_recipient", "=", "self", ".", "example_user", "(", "\"othello\"", ")", "reaction_sender", "=", "pm_recipient"...
[ 320, 4 ]
[ 352, 65 ]
python
en
['en', 'error', 'th']
False
ReactionTest.test_remove_existing_reaction_with_renamed_emoji
(self)
Removes an old existing reaction but the name of emoji got changed during various emoji infra changes.
Removes an old existing reaction but the name of emoji got changed during various emoji infra changes.
def test_remove_existing_reaction_with_renamed_emoji(self) -> None: """ Removes an old existing reaction but the name of emoji got changed during various emoji infra changes. """ realm = get_realm("zulip") sender = self.example_user("hamlet") emoji_code, reaction_...
[ "def", "test_remove_existing_reaction_with_renamed_emoji", "(", "self", ")", "->", "None", ":", "realm", "=", "get_realm", "(", "\"zulip\"", ")", "sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "emoji_code", ",", "reaction_type", "=", "emoji_na...
[ 354, 4 ]
[ 373, 44 ]
python
en
['en', 'error', 'th']
False
ReactionTest.test_remove_existing_reaction_with_deactivated_realm_emoji
(self)
Removes an old existing reaction but the realm emoji used there has been deactivated.
Removes an old existing reaction but the realm emoji used there has been deactivated.
def test_remove_existing_reaction_with_deactivated_realm_emoji(self) -> None: """ Removes an old existing reaction but the realm emoji used there has been deactivated. """ sender = self.example_user("hamlet") emoji = RealmEmoji.objects.get(name="green_tick") reaction_in...
[ "def", "test_remove_existing_reaction_with_deactivated_realm_emoji", "(", "self", ")", "->", "None", ":", "sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "emoji", "=", "RealmEmoji", ".", "objects", ".", "get", "(", "name", "=", "\"green_tick\""...
[ 375, 4 ]
[ 396, 40 ]
python
en
['en', 'error', 'th']
False
ReactionEventTest.test_add_event
(self)
Recipients of the message receive the reaction event and event contains relevant data
Recipients of the message receive the reaction event and event contains relevant data
def test_add_event(self) -> None: """ Recipients of the message receive the reaction event and event contains relevant data """ pm_sender = self.example_user("hamlet") pm_recipient = self.example_user("othello") reaction_sender = pm_recipient result = sel...
[ "def", "test_add_event", "(", "self", ")", "->", "None", ":", "pm_sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "pm_recipient", "=", "self", ".", "example_user", "(", "\"othello\"", ")", "reaction_sender", "=", "pm_recipient", "result", "=...
[ 400, 4 ]
[ 438, 52 ]
python
en
['en', 'error', 'th']
False
ReactionEventTest.test_remove_event
(self)
Recipients of the message receive the reaction event and event contains relevant data
Recipients of the message receive the reaction event and event contains relevant data
def test_remove_event(self) -> None: """ Recipients of the message receive the reaction event and event contains relevant data """ pm_sender = self.example_user("hamlet") pm_recipient = self.example_user("othello") reaction_sender = pm_recipient result = ...
[ "def", "test_remove_event", "(", "self", ")", "->", "None", ":", "pm_sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "pm_recipient", "=", "self", ".", "example_user", "(", "\"othello\"", ")", "reaction_sender", "=", "pm_recipient", "result", ...
[ 440, 4 ]
[ 482, 52 ]
python
en
['en', 'error', 'th']
False
DefaultEmojiReactionTests.test_react_historical
(self)
Reacting with valid emoji on a historical message succeeds.
Reacting with valid emoji on a historical message succeeds.
def test_react_historical(self) -> None: """ Reacting with valid emoji on a historical message succeeds. """ stream_name = "Saxony" self.subscribe(self.example_user("cordelia"), stream_name) message_id = self.send_stream_message(self.example_user("cordelia"), stream_name)...
[ "def", "test_react_historical", "(", "self", ")", "->", "None", ":", "stream_name", "=", "\"Saxony\"", "self", ".", "subscribe", "(", "self", ".", "example_user", "(", "\"cordelia\"", ")", ",", "stream_name", ")", "message_id", "=", "self", ".", "send_stream_m...
[ 839, 4 ]
[ 870, 52 ]
python
en
['en', 'error', 'th']
False
ReactionAPIEventTest.test_add_event
(self)
Recipients of the message receive the reaction event and event contains relevant data
Recipients of the message receive the reaction event and event contains relevant data
def test_add_event(self) -> None: """ Recipients of the message receive the reaction event and event contains relevant data """ pm_sender = self.example_user("hamlet") pm_recipient = self.example_user("othello") reaction_sender = pm_recipient pm_id = self....
[ "def", "test_add_event", "(", "self", ")", "->", "None", ":", "pm_sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "pm_recipient", "=", "self", ".", "example_user", "(", "\"othello\"", ")", "reaction_sender", "=", "pm_recipient", "pm_id", "="...
[ 1012, 4 ]
[ 1047, 80 ]
python
en
['en', 'error', 'th']
False
ReactionAPIEventTest.test_remove_event
(self)
Recipients of the message receive the reaction event and event contains relevant data
Recipients of the message receive the reaction event and event contains relevant data
def test_remove_event(self) -> None: """ Recipients of the message receive the reaction event and event contains relevant data """ pm_sender = self.example_user("hamlet") pm_recipient = self.example_user("othello") reaction_sender = pm_recipient pm_id = se...
[ "def", "test_remove_event", "(", "self", ")", "->", "None", ":", "pm_sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "pm_recipient", "=", "self", ".", "example_user", "(", "\"othello\"", ")", "reaction_sender", "=", "pm_recipient", "pm_id", ...
[ 1049, 4 ]
[ 1093, 80 ]
python
en
['en', 'error', 'th']
False
ReactionAPIEventTest.test_events_sent_after_transaction_commits
(self)
Tests that `send_event` is hooked to `transaction.on_commit`. This is important, because we don't want to end up holding locks on message rows for too long if the event queue runs into a problem.
Tests that `send_event` is hooked to `transaction.on_commit`. This is important, because we don't want to end up holding locks on message rows for too long if the event queue runs into a problem.
def test_events_sent_after_transaction_commits(self) -> None: """ Tests that `send_event` is hooked to `transaction.on_commit`. This is important, because we don't want to end up holding locks on message rows for too long if the event queue runs into a problem. """ hamlet...
[ "def", "test_events_sent_after_transaction_commits", "(", "self", ")", "->", "None", ":", "hamlet", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "self", ".", "send_stream_message", "(", "hamlet", ",", "\"Scotland\"", ")", "message", "=", "self", "."...
[ 1095, 4 ]
[ 1117, 74 ]
python
en
['en', 'error', 'th']
False
set_ecmwf_url
(url)
If you want to use a different server for ECMWF (for testing, etc).
If you want to use a different server for ECMWF (for testing, etc).
def set_ecmwf_url(url): """If you want to use a different server for ECMWF (for testing, etc).""" global ECMWF_SERVER ECMWF_SERVER = url
[ "def", "set_ecmwf_url", "(", "url", ")", ":", "global", "ECMWF_SERVER", "ECMWF_SERVER", "=", "url" ]
[ 56, 0 ]
[ 59, 22 ]
python
en
['en', 'en', 'en']
True
get_ecmwf_file
(dataset='ERA5', var=None)
Returns a path to the desired ECMWF baseline climate file. If the file is not present, download it. Parameters ---------- dataset : str 'ERA5', 'ERA5L', 'CERA', 'ERA5L-HMA', 'ERA5dr' var : str 'inv' for invariant 'tmp' for temperature 'pre' for precipitation Re...
Returns a path to the desired ECMWF baseline climate file.
def get_ecmwf_file(dataset='ERA5', var=None): """Returns a path to the desired ECMWF baseline climate file. If the file is not present, download it. Parameters ---------- dataset : str 'ERA5', 'ERA5L', 'CERA', 'ERA5L-HMA', 'ERA5dr' var : str 'inv' for invariant 'tmp' fo...
[ "def", "get_ecmwf_file", "(", "dataset", "=", "'ERA5'", ",", "var", "=", "None", ")", ":", "# Be sure input makes sense", "if", "dataset", "not", "in", "BASENAMES", ".", "keys", "(", ")", ":", "raise", "InvalidParamsError", "(", "'ECMWF dataset {} not '", "'in {...
[ 63, 0 ]
[ 93, 72 ]
python
en
['en', 'en', 'en']
True
process_ecmwf_data
(gdir, dataset=None, ensemble_member=0, y0=None, y1=None, output_filesuffix=None)
Processes and writes the ECMWF baseline climate data for this glacier. Extracts the nearest timeseries and writes everything to a NetCDF file. Parameters ---------- dataset : str 'ERA5', 'ERA5L', 'CERA', 'ERA5L-HMA', 'ERA5dr'. Defaults to cfg.PARAMS['baseline_climate'] ensemble_mem...
Processes and writes the ECMWF baseline climate data for this glacier.
def process_ecmwf_data(gdir, dataset=None, ensemble_member=0, y0=None, y1=None, output_filesuffix=None): """Processes and writes the ECMWF baseline climate data for this glacier. Extracts the nearest timeseries and writes everything to a NetCDF file. Parameters ---------- da...
[ "def", "process_ecmwf_data", "(", "gdir", ",", "dataset", "=", "None", ",", "ensemble_member", "=", "0", ",", "y0", "=", "None", ",", "y1", "=", "None", ",", "output_filesuffix", "=", "None", ")", ":", "if", "dataset", "is", "None", ":", "dataset", "="...
[ 106, 0 ]
[ 218, 51 ]
python
en
['en', 'en', 'en']
True
Echo.write
(self, value)
Write the value by returning it, instead of storing in a buffer.
Write the value by returning it, instead of storing in a buffer.
def write(self, value): """Write the value by returning it, instead of storing in a buffer.""" return value.encode("UTF-8")
[ "def", "write", "(", "self", ",", "value", ")", ":", "return", "value", ".", "encode", "(", "\"UTF-8\"", ")" ]
[ 55, 4 ]
[ 57, 36 ]
python
en
['en', 'en', 'en']
True
SpreadsheetExportMixin.get_filename
(self)
Gets the base filename for the exported spreadsheet, without extensions
Gets the base filename for the exported spreadsheet, without extensions
def get_filename(self): """ Gets the base filename for the exported spreadsheet, without extensions """ return "spreadsheet-export"
[ "def", "get_filename", "(", "self", ")", ":", "return", "\"spreadsheet-export\"" ]
[ 84, 4 ]
[ 86, 35 ]
python
en
['en', 'en', 'en']
True
SpreadsheetExportMixin.to_row_dict
(self, item)
Returns an OrderedDict (in the order given by list_export) of the exportable information for a model instance
Returns an OrderedDict (in the order given by list_export) of the exportable information for a model instance
def to_row_dict(self, item): """ Returns an OrderedDict (in the order given by list_export) of the exportable information for a model instance""" row_dict = OrderedDict( (field, multigetattr(item, field)) for field in self.list_export ) return row_dict
[ "def", "to_row_dict", "(", "self", ",", "item", ")", ":", "row_dict", "=", "OrderedDict", "(", "(", "field", ",", "multigetattr", "(", "item", ",", "field", ")", ")", "for", "field", "in", "self", ".", "list_export", ")", "return", "row_dict" ]
[ 88, 4 ]
[ 93, 23 ]
python
en
['en', 'en', 'en']
True
SpreadsheetExportMixin.get_preprocess_function
(self, field, value, export_format)
Returns the preprocessing function for a given field name, field value, and export format
Returns the preprocessing function for a given field name, field value, and export format
def get_preprocess_function(self, field, value, export_format): """ Returns the preprocessing function for a given field name, field value, and export format""" # Try to find a field specific function and return it format_dict = self.custom_field_preprocess.get(field, {}) if export_form...
[ "def", "get_preprocess_function", "(", "self", ",", "field", ",", "value", ",", "export_format", ")", ":", "# Try to find a field specific function and return it", "format_dict", "=", "self", ".", "custom_field_preprocess", ".", "get", "(", "field", ",", "{", "}", "...
[ 95, 4 ]
[ 109, 24 ]
python
en
['en', 'en', 'en']
True
SpreadsheetExportMixin.get_heading
(self, queryset, field)
Get the heading label for a given field for a spreadsheet generated from queryset
Get the heading label for a given field for a spreadsheet generated from queryset
def get_heading(self, queryset, field): """ Get the heading label for a given field for a spreadsheet generated from queryset """ heading_override = self.export_headings.get(field) if heading_override: return force_str(heading_override) try: return force_str( ...
[ "def", "get_heading", "(", "self", ",", "queryset", ",", "field", ")", ":", "heading_override", "=", "self", ".", "export_headings", ".", "get", "(", "field", ")", "if", "heading_override", ":", "return", "force_str", "(", "heading_override", ")", "try", ":"...
[ 133, 4 ]
[ 143, 35 ]
python
en
['en', 'en', 'en']
True
SpreadsheetExportMixin.stream_csv
(self, queryset)
Generate a csv file line by line from queryset, to be used in a StreamingHTTPResponse
Generate a csv file line by line from queryset, to be used in a StreamingHTTPResponse
def stream_csv(self, queryset): """ Generate a csv file line by line from queryset, to be used in a StreamingHTTPResponse """ writer = csv.DictWriter(Echo(), fieldnames=self.list_export) yield writer.writerow( {field: self.get_heading(queryset, field) for field in self.list_export} ...
[ "def", "stream_csv", "(", "self", ",", "queryset", ")", ":", "writer", "=", "csv", ".", "DictWriter", "(", "Echo", "(", ")", ",", "fieldnames", "=", "self", ".", "list_export", ")", "yield", "writer", ".", "writerow", "(", "{", "field", ":", "self", ...
[ 145, 4 ]
[ 153, 68 ]
python
en
['en', 'en', 'en']
True
SpreadsheetExportMixin.write_xlsx
(self, queryset, output)
Write an xlsx workbook from a queryset
Write an xlsx workbook from a queryset
def write_xlsx(self, queryset, output): """ Write an xlsx workbook from a queryset""" workbook = Workbook( output, { "in_memory": True, "constant_memory": True, "remove_timezone": True, "default_date_format": "dd/mm/...
[ "def", "write_xlsx", "(", "self", ",", "queryset", ",", "output", ")", ":", "workbook", "=", "Workbook", "(", "output", ",", "{", "\"in_memory\"", ":", "True", ",", "\"constant_memory\"", ":", "True", ",", "\"remove_timezone\"", ":", "True", ",", "\"default_...
[ 155, 4 ]
[ 174, 24 ]
python
en
['en', 'lb', 'en']
True
SpreadsheetExportMixin.as_spreadsheet
(self, queryset, spreadsheet_format)
Return a response with a spreadsheet representing the exported data from queryset, in the format specified
Return a response with a spreadsheet representing the exported data from queryset, in the format specified
def as_spreadsheet(self, queryset, spreadsheet_format): """ Return a response with a spreadsheet representing the exported data from queryset, in the format specified""" if spreadsheet_format == self.FORMAT_CSV: return self.write_csv_response(queryset) elif spreadsheet_format == self...
[ "def", "as_spreadsheet", "(", "self", ",", "queryset", ",", "spreadsheet_format", ")", ":", "if", "spreadsheet_format", "==", "self", ".", "FORMAT_CSV", ":", "return", "self", ".", "write_csv_response", "(", "queryset", ")", "elif", "spreadsheet_format", "==", "...
[ 196, 4 ]
[ 201, 53 ]
python
en
['en', 'en', 'en']
True
install_editable
( install_options, # type: List[str] global_options, # type: Sequence[str] prefix, # type: Optional[str] home, # type: Optional[str] use_user_site, # type: bool name, # type: str setup_py_path, # type: str isolated, # type: bool build_env, # type: BuildEnvironment unpack...
Install a package in editable mode. Most arguments are pass-through to setuptools.
Install a package in editable mode. Most arguments are pass-through to setuptools.
def install_editable( install_options, # type: List[str] global_options, # type: Sequence[str] prefix, # type: Optional[str] home, # type: Optional[str] use_user_site, # type: bool name, # type: str setup_py_path, # type: str isolated, # type: bool build_env, # type: BuildEn...
[ "def", "install_editable", "(", "install_options", ",", "# type: List[str]", "global_options", ",", "# type: Sequence[str]", "prefix", ",", "# type: Optional[str]", "home", ",", "# type: Optional[str]", "use_user_site", ",", "# type: bool", "name", ",", "# type: str", "setu...
[ 18, 0 ]
[ 51, 13 ]
python
en
['en', 'en', 'en']
True
_insert_installed
(installed, others)
Iterator for ``FoundCandidates``. This iterator is used when the resolver prefers to upgrade an already-installed package. Candidates from index are returned in their normal ordering, except replaced when the version is already installed. Since candidates from index are already sorted by reverse versi...
Iterator for ``FoundCandidates``.
def _insert_installed(installed, others): # type: (Candidate, Iterator[Candidate]) -> Iterator[Candidate] """Iterator for ``FoundCandidates``. This iterator is used when the resolver prefers to upgrade an already-installed package. Candidates from index are returned in their normal ordering, except...
[ "def", "_insert_installed", "(", "installed", ",", "others", ")", ":", "# type: (Candidate, Iterator[Candidate]) -> Iterator[Candidate]", "candidates", "=", "sorted", "(", "itertools", ".", "chain", "(", "[", "installed", "]", ",", "others", ")", ",", "key", "=", ...
[ 26, 0 ]
[ 45, 27 ]
python
en
['en', 'la', 'en']
True
MediaEmbedHandler.get_db_attributes
(tag)
Given a tag that we've identified as a media embed (because it has a data-embedtype="media" attribute), return a dict of the attributes we should have on the resulting <embed> element.
Given a tag that we've identified as a media embed (because it has a data-embedtype="media" attribute), return a dict of the attributes we should have on the resulting <embed> element.
def get_db_attributes(tag): """ Given a tag that we've identified as a media embed (because it has a data-embedtype="media" attribute), return a dict of the attributes we should have on the resulting <embed> element. """ return { 'url': tag['data-url'], ...
[ "def", "get_db_attributes", "(", "tag", ")", ":", "return", "{", "'url'", ":", "tag", "[", "'data-url'", "]", ",", "}" ]
[ 15, 4 ]
[ 23, 9 ]
python
en
['en', 'error', 'th']
False
MediaEmbedHandler.expand_db_attributes
(attrs)
Given a dict of attributes from the <embed> tag, return the real HTML representation for use within the editor.
Given a dict of attributes from the <embed> tag, return the real HTML representation for use within the editor.
def expand_db_attributes(attrs): """ Given a dict of attributes from the <embed> tag, return the real HTML representation for use within the editor. """ try: return format.embed_to_editor_html(attrs['url']) except EmbedException: # Could be replace...
[ "def", "expand_db_attributes", "(", "attrs", ")", ":", "try", ":", "return", "format", ".", "embed_to_editor_html", "(", "attrs", "[", "'url'", "]", ")", "except", "EmbedException", ":", "# Could be replaced with a nice error message", "return", "''" ]
[ 26, 4 ]
[ 35, 21 ]
python
en
['en', 'error', 'th']
False
flock
(lockfile: Union[int, IO[Any]], shared: bool = False)
Lock a file object using flock(2) for the duration of a 'with' statement. If shared is True, use a LOCK_SH lock, otherwise LOCK_EX.
Lock a file object using flock(2) for the duration of a 'with' statement.
def flock(lockfile: Union[int, IO[Any]], shared: bool = False) -> Iterator[None]: """Lock a file object using flock(2) for the duration of a 'with' statement. If shared is True, use a LOCK_SH lock, otherwise LOCK_EX.""" fcntl.flock(lockfile, fcntl.LOCK_SH if shared else fcntl.LOCK_EX) try: yie...
[ "def", "flock", "(", "lockfile", ":", "Union", "[", "int", ",", "IO", "[", "Any", "]", "]", ",", "shared", ":", "bool", "=", "False", ")", "->", "Iterator", "[", "None", "]", ":", "fcntl", ".", "flock", "(", "lockfile", ",", "fcntl", ".", "LOCK_S...
[ 9, 0 ]
[ 18, 44 ]
python
en
['en', 'en', 'en']
True
lockfile
(filename: str, shared: bool = False)
Lock a file using flock(2) for the duration of a 'with' statement. If shared is True, use a LOCK_SH lock, otherwise LOCK_EX. The file is given by name and will be created if it does not exist.
Lock a file using flock(2) for the duration of a 'with' statement.
def lockfile(filename: str, shared: bool = False) -> Iterator[None]: """Lock a file using flock(2) for the duration of a 'with' statement. If shared is True, use a LOCK_SH lock, otherwise LOCK_EX. The file is given by name and will be created if it does not exist.""" with open(filename, "w") as lock: ...
[ "def", "lockfile", "(", "filename", ":", "str", ",", "shared", ":", "bool", "=", "False", ")", "->", "Iterator", "[", "None", "]", ":", "with", "open", "(", "filename", ",", "\"w\"", ")", "as", "lock", ":", "with", "flock", "(", "lock", ",", "share...
[ 22, 0 ]
[ 30, 17 ]
python
en
['en', 'en', 'en']
True
Pidfile.unlink
(self)
delete pidfile
delete pidfile
def unlink(self): """ delete pidfile""" try: with open(self.fname, "r") as f: pid1 = int(f.read() or 0) if pid1 == self.pid: os.unlink(self.fname) except: pass
[ "def", "unlink", "(", "self", ")", ":", "try", ":", "with", "open", "(", "self", ".", "fname", ",", "\"r\"", ")", "as", "f", ":", "pid1", "=", "int", "(", "f", ".", "read", "(", ")", "or", "0", ")", "if", "pid1", "==", "self", ".", "pid", "...
[ 51, 4 ]
[ 60, 16 ]
python
it
['it', 'it', 'en']
False
Pidfile.validate
(self)
Validate pidfile and make it stale if needed
Validate pidfile and make it stale if needed
def validate(self): """ Validate pidfile and make it stale if needed""" if not self.fname: return try: with open(self.fname, "r") as f: try: wpid = int(f.read()) except ValueError: return ...
[ "def", "validate", "(", "self", ")", ":", "if", "not", "self", ".", "fname", ":", "return", "try", ":", "with", "open", "(", "self", ".", "fname", ",", "\"r\"", ")", "as", "f", ":", "try", ":", "wpid", "=", "int", "(", "f", ".", "read", "(", ...
[ 62, 4 ]
[ 85, 17 ]
python
en
['en', 'en', 'en']
True
Command.send
(self, users: List[UserProfile])
Sends one-use only links for resetting password to target users
Sends one-use only links for resetting password to target users
def send(self, users: List[UserProfile]) -> None: """Sends one-use only links for resetting password to target users""" for user_profile in users: context = { "email": user_profile.delivery_email, "reset_url": generate_password_reset_url(user_profile, default_...
[ "def", "send", "(", "self", ",", "users", ":", "List", "[", "UserProfile", "]", ")", "->", "None", ":", "for", "user_profile", "in", "users", ":", "context", "=", "{", "\"email\"", ":", "user_profile", ".", "delivery_email", ",", "\"reset_url\"", ":", "g...
[ 41, 4 ]
[ 57, 13 ]
python
en
['en', 'en', 'en']
True
arg_byref
(args, offset=-1)
Returns the pointer argument's by-reference value.
Returns the pointer argument's by-reference value.
def arg_byref(args, offset=-1): "Returns the pointer argument's by-reference value." return args[offset]._obj.value
[ "def", "arg_byref", "(", "args", ",", "offset", "=", "-", "1", ")", ":", "return", "args", "[", "offset", "]", ".", "_obj", ".", "value" ]
[ 15, 0 ]
[ 17, 34 ]
python
en
['en', 'en', 'en']
True
ptr_byref
(args, offset=-1)
Returns the pointer argument passed in by-reference.
Returns the pointer argument passed in by-reference.
def ptr_byref(args, offset=-1): "Returns the pointer argument passed in by-reference." return args[offset]._obj
[ "def", "ptr_byref", "(", "args", ",", "offset", "=", "-", "1", ")", ":", "return", "args", "[", "offset", "]", ".", "_obj" ]
[ 20, 0 ]
[ 22, 28 ]
python
en
['en', 'en', 'en']
True
check_const_string
(result, func, cargs, offset=None, cpl=False)
Similar functionality to `check_string`, but does not free the pointer.
Similar functionality to `check_string`, but does not free the pointer.
def check_const_string(result, func, cargs, offset=None, cpl=False): """ Similar functionality to `check_string`, but does not free the pointer. """ if offset: check_err(result, cpl=cpl) ptr = ptr_byref(cargs, offset) return ptr.value else: return result
[ "def", "check_const_string", "(", "result", ",", "func", ",", "cargs", ",", "offset", "=", "None", ",", "cpl", "=", "False", ")", ":", "if", "offset", ":", "check_err", "(", "result", ",", "cpl", "=", "cpl", ")", "ptr", "=", "ptr_byref", "(", "cargs"...
[ 26, 0 ]
[ 35, 21 ]
python
en
['en', 'error', 'th']
False
check_string
(result, func, cargs, offset=-1, str_result=False)
Checks the string output returned from the given function, and frees the string pointer allocated by OGR. The `str_result` keyword may be used when the result is the string pointer, otherwise the OGR error code is assumed. The `offset` keyword may be used to extract the string pointer passed in b...
Checks the string output returned from the given function, and frees the string pointer allocated by OGR. The `str_result` keyword may be used when the result is the string pointer, otherwise the OGR error code is assumed. The `offset` keyword may be used to extract the string pointer passed in b...
def check_string(result, func, cargs, offset=-1, str_result=False): """ Checks the string output returned from the given function, and frees the string pointer allocated by OGR. The `str_result` keyword may be used when the result is the string pointer, otherwise the OGR error code is assumed. The...
[ "def", "check_string", "(", "result", ",", "func", ",", "cargs", ",", "offset", "=", "-", "1", ",", "str_result", "=", "False", ")", ":", "if", "str_result", ":", "# For routines that return a string.", "ptr", "=", "result", "if", "not", "ptr", ":", "s", ...
[ 38, 0 ]
[ 64, 12 ]
python
en
['en', 'error', 'th']
False
check_envelope
(result, func, cargs, offset=-1)
Checks a function that returns an OGR Envelope by reference.
Checks a function that returns an OGR Envelope by reference.
def check_envelope(result, func, cargs, offset=-1): "Checks a function that returns an OGR Envelope by reference." env = ptr_byref(cargs, offset) return env
[ "def", "check_envelope", "(", "result", ",", "func", ",", "cargs", ",", "offset", "=", "-", "1", ")", ":", "env", "=", "ptr_byref", "(", "cargs", ",", "offset", ")", "return", "env" ]
[ 70, 0 ]
[ 73, 14 ]
python
en
['en', 'en', 'en']
True
check_geom
(result, func, cargs)
Checks a function that returns a geometry.
Checks a function that returns a geometry.
def check_geom(result, func, cargs): "Checks a function that returns a geometry." # OGR_G_Clone may return an integer, even though the # restype is set to c_void_p if isinstance(result, six.integer_types): result = c_void_p(result) if not result: raise GDALException('Invalid geometry...
[ "def", "check_geom", "(", "result", ",", "func", ",", "cargs", ")", ":", "# OGR_G_Clone may return an integer, even though the", "# restype is set to c_void_p", "if", "isinstance", "(", "result", ",", "six", ".", "integer_types", ")", ":", "result", "=", "c_void_p", ...
[ 77, 0 ]
[ 85, 17 ]
python
en
['en', 'en', 'en']
True
check_geom_offset
(result, func, cargs, offset=-1)
Chcks the geometry at the given offset in the C parameter list.
Chcks the geometry at the given offset in the C parameter list.
def check_geom_offset(result, func, cargs, offset=-1): "Chcks the geometry at the given offset in the C parameter list." check_err(result) geom = ptr_byref(cargs, offset=offset) return check_geom(geom, func, cargs)
[ "def", "check_geom_offset", "(", "result", ",", "func", ",", "cargs", ",", "offset", "=", "-", "1", ")", ":", "check_err", "(", "result", ")", "geom", "=", "ptr_byref", "(", "cargs", ",", "offset", "=", "offset", ")", "return", "check_geom", "(", "geom...
[ 88, 0 ]
[ 92, 40 ]
python
en
['en', 'en', 'en']
True
check_arg_errcode
(result, func, cargs, cpl=False)
The error code is returned in the last argument, by reference. Check its value with `check_err` before returning the result.
The error code is returned in the last argument, by reference. Check its value with `check_err` before returning the result.
def check_arg_errcode(result, func, cargs, cpl=False): """ The error code is returned in the last argument, by reference. Check its value with `check_err` before returning the result. """ check_err(arg_byref(cargs), cpl=cpl) return result
[ "def", "check_arg_errcode", "(", "result", ",", "func", ",", "cargs", ",", "cpl", "=", "False", ")", ":", "check_err", "(", "arg_byref", "(", "cargs", ")", ",", "cpl", "=", "cpl", ")", "return", "result" ]
[ 105, 0 ]
[ 111, 17 ]
python
en
['en', 'error', 'th']
False
check_errcode
(result, func, cargs, cpl=False)
Check the error code returned (c_int).
Check the error code returned (c_int).
def check_errcode(result, func, cargs, cpl=False): """ Check the error code returned (c_int). """ check_err(result, cpl=cpl)
[ "def", "check_errcode", "(", "result", ",", "func", ",", "cargs", ",", "cpl", "=", "False", ")", ":", "check_err", "(", "result", ",", "cpl", "=", "cpl", ")" ]
[ 114, 0 ]
[ 118, 30 ]
python
en
['en', 'error', 'th']
False
check_pointer
(result, func, cargs)
Makes sure the result pointer is valid.
Makes sure the result pointer is valid.
def check_pointer(result, func, cargs): "Makes sure the result pointer is valid." if isinstance(result, six.integer_types): result = c_void_p(result) if result: return result else: raise GDALException('Invalid pointer returned from "%s"' % func.__name__)
[ "def", "check_pointer", "(", "result", ",", "func", ",", "cargs", ")", ":", "if", "isinstance", "(", "result", ",", "six", ".", "integer_types", ")", ":", "result", "=", "c_void_p", "(", "result", ")", "if", "result", ":", "return", "result", "else", "...
[ 121, 0 ]
[ 128, 81 ]
python
en
['en', 'en', 'en']
True
check_str_arg
(result, func, cargs)
This is for the OSRGet[Angular|Linear]Units functions, which require that the returned string pointer not be freed. This returns both the double and string values.
This is for the OSRGet[Angular|Linear]Units functions, which require that the returned string pointer not be freed. This returns both the double and string values.
def check_str_arg(result, func, cargs): """ This is for the OSRGet[Angular|Linear]Units functions, which require that the returned string pointer not be freed. This returns both the double and string values. """ dbl = result ptr = cargs[-1]._obj return dbl, ptr.value.decode()
[ "def", "check_str_arg", "(", "result", ",", "func", ",", "cargs", ")", ":", "dbl", "=", "result", "ptr", "=", "cargs", "[", "-", "1", "]", ".", "_obj", "return", "dbl", ",", "ptr", ".", "value", ".", "decode", "(", ")" ]
[ 131, 0 ]
[ 139, 34 ]
python
en
['en', 'error', 'th']
False
run_and_return_cost_time
(kalelisp)
(q ()))))))) (c (q ((c (i (f (r (a))) (q (i (q 1) ((c (f (a)) (c (f (a))
(q ()))))))) (c (q ((c (i (f (r (a))) (q (i (q 1) ((c (f (a)) (c (f (a))
def run_and_return_cost_time(kalelisp): start = time.time() clvm_loop = "((c (q ((c (f (a)) (c (f (a)) (c (f (r (a))) (c (f (r (r (a))))" " (q ()))))))) (c (q ((c (i (f (r (a))) (q (i (q 1) ((c (f (a)) (c (f (a))" " (c (- (f (r (a))) (q 1)) (c (f (r (r (a)))) (q ()))))))" " ((c (f (r (r (a)))) (q (...
[ "def", "run_and_return_cost_time", "(", "kalelisp", ")", ":", "start", "=", "time", ".", "time", "(", ")", "clvm_loop", "=", "\"((c (q ((c (f (a)) (c (f (a)) (c (f (r (a))) (c (f (r (r (a))))\"", "\" (c (- (f (r (a))) (q 1)) (c (f (r (r (a)))) (q ()))))))\"", "\" ((c (f (r (r (a)))...
[ 31, 0 ]
[ 47, 27 ]
python
ja
['mt', 'ja', 'ur']
False
benchmark_all_operators
()
(q 0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb)
(q 0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb)
def benchmark_all_operators(): addition = "(+ (q 1000000000) (q 1000000000))" substraction = "(- (q 1000000000) (q 1000000000))" multiply = "(* (q 1000000000) (q 1000000000))" greater = "(> (q 1000000000) (q 1000000000))" equal = "(= (q 1000000000) (q 1000000000))" if_clvm = "(i (= (q 1000000000...
[ "def", "benchmark_all_operators", "(", ")", ":", "addition", "=", "\"(+ (q 1000000000) (q 1000000000))\"", "substraction", "=", "\"(- (q 1000000000) (q 1000000000))\"", "multiply", "=", "\"(* (q 1000000000) (q 1000000000))\"", "greater", "=", "\"(> (q 1000000000) (q 1000000000))\"", ...
[ 54, 0 ]
[ 96, 55 ]
python
cy
['mt', 'cy', 'tr']
False
load_serialized_clvm
(clvm_filename, package_or_requirement=__name__)
This function takes a .clvm file in the given package and compiles it to a .clvm.hex file if the .hex file is missing or older than the .clvm file, then returns the contents of the .hex file as a `Program`. clvm_filename: file name package_or_requirement: usually `__name__` if the clvm file is in ...
This function takes a .clvm file in the given package and compiles it to a .clvm.hex file if the .hex file is missing or older than the .clvm file, then returns the contents of the .hex file as a `Program`.
def load_serialized_clvm(clvm_filename, package_or_requirement=__name__) -> SerializedProgram: """ This function takes a .clvm file in the given package and compiles it to a .clvm.hex file if the .hex file is missing or older than the .clvm file, then returns the contents of the .hex file as a `Program`...
[ "def", "load_serialized_clvm", "(", "clvm_filename", ",", "package_or_requirement", "=", "__name__", ")", "->", "SerializedProgram", ":", "hex_filename", "=", "f\"{clvm_filename}.hex\"", "try", ":", "if", "pkg_resources", ".", "resource_exists", "(", "package_or_requireme...
[ 8, 0 ]
[ 32, 50 ]
python
en
['en', 'error', 'th']
False
ImageNodeTestCase.test_render_valid_image_to_string
(self)
Tests that an ImageNode with a valid image renders an img tag
Tests that an ImageNode with a valid image renders an img tag
def test_render_valid_image_to_string(self): """ Tests that an ImageNode with a valid image renders an img tag """ context = {'image': self.image} node = ImageNode(Variable('image'), 'original') rendered = node.render(context) self.assertIn('<img alt="Test image...
[ "def", "test_render_valid_image_to_string", "(", "self", ")", ":", "context", "=", "{", "'image'", ":", "self", ".", "image", "}", "node", "=", "ImageNode", "(", "Variable", "(", "'image'", ")", ",", "'original'", ")", "rendered", "=", "node", ".", "render...
[ 18, 4 ]
[ 27, 56 ]
python
en
['en', 'error', 'th']
False
ImageNodeTestCase.test_render_none_to_string
(self)
Tests that an ImageNode without image renders an empty string
Tests that an ImageNode without image renders an empty string
def test_render_none_to_string(self): """ Tests that an ImageNode without image renders an empty string """ context = {'image': None} node = ImageNode(Variable('image'), 'original') rendered = node.render(context) self.assertEqual(rendered, '')
[ "def", "test_render_none_to_string", "(", "self", ")", ":", "context", "=", "{", "'image'", ":", "None", "}", "node", "=", "ImageNode", "(", "Variable", "(", "'image'", ")", ",", "'original'", ")", "rendered", "=", "node", ".", "render", "(", "context", ...
[ 29, 4 ]
[ 38, 38 ]
python
en
['en', 'error', 'th']
False
ImageNodeTestCase.test_render_valid_image_as_context_variable
(self)
Tests that an ImageNode with a valid image and a context variable name renders an empty string and puts a rendition in the context variable
Tests that an ImageNode with a valid image and a context variable name renders an empty string and puts a rendition in the context variable
def test_render_valid_image_as_context_variable(self): """ Tests that an ImageNode with a valid image and a context variable name renders an empty string and puts a rendition in the context variable """ context = {'image': self.image, 'image_node': 'fake value'} node = Im...
[ "def", "test_render_valid_image_as_context_variable", "(", "self", ")", ":", "context", "=", "{", "'image'", ":", "self", ".", "image", ",", "'image_node'", ":", "'fake value'", "}", "node", "=", "ImageNode", "(", "Variable", "(", "'image'", ")", ",", "'origin...
[ 40, 4 ]
[ 51, 63 ]
python
en
['en', 'error', 'th']
False
ImageNodeTestCase.test_render_none_as_context_variable
(self)
Tests that an ImageNode without an image and a context variable name renders an empty string and puts None in the context variable
Tests that an ImageNode without an image and a context variable name renders an empty string and puts None in the context variable
def test_render_none_as_context_variable(self): """ Tests that an ImageNode without an image and a context variable name renders an empty string and puts None in the context variable """ context = {'image': None, 'image_node': 'fake value'} node = ImageNode(Variable('imag...
[ "def", "test_render_none_as_context_variable", "(", "self", ")", ":", "context", "=", "{", "'image'", ":", "None", ",", "'image_node'", ":", "'fake value'", "}", "node", "=", "ImageNode", "(", "Variable", "(", "'image'", ")", ",", "'original'", ",", "'image_no...
[ 53, 4 ]
[ 64, 48 ]
python
en
['en', 'error', 'th']
False
load_csv_or_excel
(file_path, index_col=None)
Import csv or excel file using pandas.
Import csv or excel file using pandas.
def load_csv_or_excel(file_path, index_col=None): """ Import csv or excel file using pandas. """ file_path = str(file_path) if '.csv' in file_path: data = pd.read_csv(file_path, index_col=index_col) elif '.xlsx' in file_path: data = pd.read_excel(file_path, index_col=in...
[ "def", "load_csv_or_excel", "(", "file_path", ",", "index_col", "=", "None", ")", ":", "file_path", "=", "str", "(", "file_path", ")", "if", "'.csv'", "in", "file_path", ":", "data", "=", "pd", ".", "read_csv", "(", "file_path", ",", "index_col", "=", "i...
[ 12, 0 ]
[ 26, 15 ]
python
en
['en', 'error', 'th']
False
load_experiment_results
(experiment_results_path)
Load and concatenate all csv or excel files in the experiment_results_path folder.
Load and concatenate all csv or excel files in the experiment_results_path folder.
def load_experiment_results(experiment_results_path): """ Load and concatenate all csv or excel files in the experiment_results_path folder. """ experiment_results_path = str(experiment_results_path) if isdir(experiment_results_path): files = [experiment_results_path + '/' + f...
[ "def", "load_experiment_results", "(", "experiment_results_path", ")", ":", "experiment_results_path", "=", "str", "(", "experiment_results_path", ")", "if", "isdir", "(", "experiment_results_path", ")", ":", "files", "=", "[", "experiment_results_path", "+", "'/'", "...
[ 30, 0 ]
[ 56, 38 ]
python
en
['en', 'error', 'th']
False
write_experiment_results
(data,experiment_results_path)
Write experiment results from simulations.
Write experiment results from simulations.
def write_experiment_results(data,experiment_results_path): """ Write experiment results from simulations. """ from os import listdir count = len(listdir(experiment_results_path)) + 1 data.to_csv( experiment_results_path + '/batch' + str(count) + '.csv', ...
[ "def", "write_experiment_results", "(", "data", ",", "experiment_results_path", ")", ":", "from", "os", "import", "listdir", "count", "=", "len", "(", "listdir", "(", "experiment_results_path", ")", ")", "+", "1", "data", ".", "to_csv", "(", "experiment_results_...
[ 60, 0 ]
[ 72, 17 ]
python
en
['en', 'error', 'th']
False
to_torch
(data, gpu=False)
Convert from pandas dataframe or numpy array to torch array.
Convert from pandas dataframe or numpy array to torch array.
def to_torch(data, gpu=False): """ Convert from pandas dataframe or numpy array to torch array. """ if 'torch' in str(type(data)): torch_data = data else: try: torch_data = torch.from_numpy(np.array(data).astype('float')).float() except: torc...
[ "def", "to_torch", "(", "data", ",", "gpu", "=", "False", ")", ":", "if", "'torch'", "in", "str", "(", "type", "(", "data", ")", ")", ":", "torch_data", "=", "data", "else", ":", "try", ":", "torch_data", "=", "torch", ".", "from_numpy", "(", "np",...
[ 76, 0 ]
[ 93, 21 ]
python
en
['en', 'error', 'th']
False
torch_to_numpy
(data, gpu=False)
Convert from torch.tensor to a numpy.array.
Convert from torch.tensor to a numpy.array.
def torch_to_numpy(data, gpu=False): """ Convert from torch.tensor to a numpy.array. """ # Torch conversion if torch.cuda.is_available() and gpu == True: out = np.array(data.detach().cpu()) else: try: out = np.array(data.detach()) except: out ...
[ "def", "torch_to_numpy", "(", "data", ",", "gpu", "=", "False", ")", ":", "# Torch conversion", "if", "torch", ".", "cuda", ".", "is_available", "(", ")", "and", "gpu", "==", "True", ":", "out", "=", "np", ".", "array", "(", "data", ".", "detach", "(...
[ 95, 0 ]
[ 109, 14 ]
python
en
['en', 'error', 'th']
False
complement
(df1, df2, rounding=False, boolean_out=False)
Complement of two dataframes. Remove elements of df2 in df1. Retains indices of df1.
Complement of two dataframes. Remove elements of df2 in df1. Retains indices of df1.
def complement(df1, df2, rounding=False, boolean_out=False): """ Complement of two dataframes. Remove elements of df2 in df1. Retains indices of df1. """ df1 = df1.copy() df2 = df2.copy().reset_index(drop=True) if rounding != False: df1 = df1.round(decimals=rounding) ...
[ "def", "complement", "(", "df1", ",", "df2", ",", "rounding", "=", "False", ",", "boolean_out", "=", "False", ")", ":", "df1", "=", "df1", ".", "copy", "(", ")", "df2", "=", "df2", ".", "copy", "(", ")", ".", "reset_index", "(", "drop", "=", "Tru...
[ 146, 0 ]
[ 167, 27 ]
python
en
['en', 'error', 'th']
False
chunk_sample
(model, domain_tensor, batch_size, gpu=False, chunk_size=5000)
Sample large spaces can lead to memory issues. To deal with this we can chop the space up into smaller portions, sample the posterior predictive distribution, and the concatenate them. Clunky but just a quick patch for now.
Sample large spaces can lead to memory issues. To deal with this we can chop the space up into smaller portions, sample the posterior predictive distribution, and the concatenate them. Clunky but just a quick patch for now.
def chunk_sample(model, domain_tensor, batch_size, gpu=False, chunk_size=5000): """ Sample large spaces can lead to memory issues. To deal with this we can chop the space up into smaller portions, sample the posterior predictive distribution, and the concatenate them. Clunky but just a quick patch f...
[ "def", "chunk_sample", "(", "model", ",", "domain_tensor", ",", "batch_size", ",", "gpu", "=", "False", ",", "chunk_size", "=", "5000", ")", ":", "# Get number of chunks and remainder", "chunks", "=", "len", "(", "domain_tensor", ")", "//", "chunk_size", "remain...
[ 171, 0 ]
[ 212, 37 ]
python
en
['en', 'error', 'th']
False
sample
(model, domain_tensor, batch_size, gpu=False, chunk_size=5000)
Sample posterior predictive distribution.
Sample posterior predictive distribution.
def sample(model, domain_tensor, batch_size, gpu=False, chunk_size=5000): """ Sample posterior predictive distribution. """ # If the domain is smaller than chunk_size then don't break it up if len(domain_tensor) < chunk_size: samples = model.sample_posterior(domain_tensor, batch_size) ...
[ "def", "sample", "(", "model", ",", "domain_tensor", ",", "batch_size", ",", "gpu", "=", "False", ",", "chunk_size", "=", "5000", ")", ":", "# If the domain is smaller than chunk_size then don't break it up", "if", "len", "(", "domain_tensor", ")", "<", "chunk_size"...
[ 214, 0 ]
[ 225, 18 ]
python
en
['en', 'error', 'th']
False
join_to_df
(sample, domain, gpu=False)
Join sample and candidates (X values). Works on torch arrays. Returns a dataframe. Column names from candidates.
Join sample and candidates (X values). Works on torch arrays. Returns a dataframe. Column names from candidates.
def join_to_df(sample, domain, gpu=False): """ Join sample and candidates (X values). Works on torch arrays. Returns a dataframe. Column names from candidates. """ if torch.cuda.is_available() and gpu == True: sample = np.array(sample.detach().cpu()) else: sample = np.array(samp...
[ "def", "join_to_df", "(", "sample", ",", "domain", ",", "gpu", "=", "False", ")", ":", "if", "torch", ".", "cuda", ".", "is_available", "(", ")", "and", "gpu", "==", "True", ":", "sample", "=", "np", ".", "array", "(", "sample", ".", "detach", "(",...
[ 229, 0 ]
[ 246, 24 ]
python
en
['en', 'error', 'th']
False
argmax
(sample_x_y, known_X, target='sample', duplicates=False, top_n=1)
ArgMax with or without duplicates. Works on dataframes.
ArgMax with or without duplicates. Works on dataframes.
def argmax(sample_x_y, known_X, target='sample', duplicates=False, top_n=1): """ ArgMax with or without duplicates. Works on dataframes. """ sorted_sample = sample_x_y.sort_values(by=target, ascending=False) if duplicates != False: arg_max = sorted_sample.iloc[[0]] else: ...
[ "def", "argmax", "(", "sample_x_y", ",", "known_X", ",", "target", "=", "'sample'", ",", "duplicates", "=", "False", ",", "top_n", "=", "1", ")", ":", "sorted_sample", "=", "sample_x_y", ".", "sort_values", "(", "by", "=", "target", ",", "ascending", "="...
[ 248, 0 ]
[ 263, 18 ]
python
en
['en', 'error', 'th']
False
main
(args=None)
This is preserved for old console scripts that may still be referencing it. For additional details, see https://github.com/pypa/pip/issues/7498.
This is preserved for old console scripts that may still be referencing it.
def main(args=None): # type: (Optional[List[str]]) -> int """This is preserved for old console scripts that may still be referencing it. For additional details, see https://github.com/pypa/pip/issues/7498. """ from pip._internal.utils.entrypoints import _wrapper return _wrapper(args)
[ "def", "main", "(", "args", "=", "None", ")", ":", "# type: (Optional[List[str]]) -> int", "from", "pip", ".", "_internal", ".", "utils", ".", "entrypoints", "import", "_wrapper", "return", "_wrapper", "(", "args", ")" ]
[ 7, 0 ]
[ 16, 25 ]
python
en
['en', 'en', 'en']
True
MeshBallApp.update_points
(self, *args)
replace self.mesh_points based on current slider positions. Called continuously by a timer because this only sample code.
replace self.mesh_points based on current slider positions. Called continuously by a timer because this only sample code.
def update_points(self, *args): """ replace self.mesh_points based on current slider positions. Called continuously by a timer because this only sample code. """ points = [Window.width / 2, Window.height / 2, .5, .5] i = 0 while i < 2 * pi: i += 0.01 * pi ...
[ "def", "update_points", "(", "self", ",", "*", "args", ")", ":", "points", "=", "[", "Window", ".", "width", "/", "2", ",", "Window", ".", "height", "/", "2", ",", ".5", ",", ".5", "]", "i", "=", "0", "while", "i", "<", "2", "*", "pi", ":", ...
[ 80, 4 ]
[ 96, 33 ]
python
en
['en', 'en', 'en']
True
DatabaseAPI20Test.setUp
(self)
self.drivers should override this method to perform required setup if any is necessary, such as creating the database.
self.drivers should override this method to perform required setup if any is necessary, such as creating the database.
def setUp(self): ''' self.drivers should override this method to perform required setup if any is necessary, such as creating the database. ''' pass
[ "def", "setUp", "(", "self", ")", ":", "pass" ]
[ 122, 4 ]
[ 126, 12 ]
python
en
['en', 'en', 'en']
True
DatabaseAPI20Test.tearDown
(self)
self.drivers should override this method to perform required cleanup if any is necessary, such as deleting the test database. The default drops the tables that may be created.
self.drivers should override this method to perform required cleanup if any is necessary, such as deleting the test database. The default drops the tables that may be created.
def tearDown(self): ''' self.drivers should override this method to perform required cleanup if any is necessary, such as deleting the test database. The default drops the tables that may be created. ''' con = self._connect() try: cur = con.cursor() ...
[ "def", "tearDown", "(", "self", ")", ":", "con", "=", "self", ".", "_connect", "(", ")", "try", ":", "cur", "=", "con", ".", "cursor", "(", ")", "for", "ddl", "in", "(", "self", ".", "xddl1", ",", "self", ".", "xddl2", ")", ":", "try", ":", "...
[ 128, 4 ]
[ 145, 23 ]
python
en
['en', 'en', 'en']
True