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
parse_editable
(editable_req)
Parses an editable requirement into: - a requirement name - an URL - extras - editable options Accepted requirements: svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir .[some_extra]
Parses an editable requirement into: - a requirement name - an URL - extras - editable options Accepted requirements: svn+http://blahblah
def parse_editable(editable_req): # type: (str) -> Tuple[Optional[str], str, Set[str]] """Parses an editable requirement into: - a requirement name - an URL - extras - editable options Accepted requirements: svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version...
[ "def", "parse_editable", "(", "editable_req", ")", ":", "# type: (str) -> Tuple[Optional[str], str, Set[str]]", "url", "=", "editable_req", "# If a file path is specified with extras, strip off the extras.", "url_no_extras", ",", "extras", "=", "_strip_extras", "(", "url", ")", ...
[ 67, 0 ]
[ 139, 35 ]
python
en
['en', 'en', 'en']
True
deduce_helpful_msg
(req)
Returns helpful msg in case requirements file does not exist, or cannot be parsed. :params req: Requirements file path
Returns helpful msg in case requirements file does not exist, or cannot be parsed.
def deduce_helpful_msg(req): # type: (str) -> str """Returns helpful msg in case requirements file does not exist, or cannot be parsed. :params req: Requirements file path """ msg = "" if os.path.exists(req): msg = " The path does exist. " # Try to parse and check if it is a...
[ "def", "deduce_helpful_msg", "(", "req", ")", ":", "# type: (str) -> str", "msg", "=", "\"\"", "if", "os", ".", "path", ".", "exists", "(", "req", ")", ":", "msg", "=", "\" The path does exist. \"", "# Try to parse and check if it is a requirements file.", "try", ":...
[ 142, 0 ]
[ 170, 14 ]
python
en
['en', 'en', 'en']
True
_looks_like_path
(name)
Checks whether the string "looks like" a path on the filesystem. This does not check whether the target actually exists, only judge from the appearance. Returns true if any of the following conditions is true: * a path separator is found (either os.path.sep or os.path.altsep); * a dot is found (wh...
Checks whether the string "looks like" a path on the filesystem.
def _looks_like_path(name): # type: (str) -> bool """Checks whether the string "looks like" a path on the filesystem. This does not check whether the target actually exists, only judge from the appearance. Returns true if any of the following conditions is true: * a path separator is found (ei...
[ "def", "_looks_like_path", "(", "name", ")", ":", "# type: (str) -> bool", "if", "os", ".", "path", ".", "sep", "in", "name", ":", "return", "True", "if", "os", ".", "path", ".", "altsep", "is", "not", "None", "and", "os", ".", "path", ".", "altsep", ...
[ 236, 0 ]
[ 253, 16 ]
python
en
['en', 'en', 'en']
True
_get_url_from_path
(path, name)
First, it checks whether a provided path is an installable directory (e.g. it has a setup.py). If it is, returns the path. If false, check if the path is an archive file (such as a .whl). The function checks if the path is a file. If false, if the path has an @, it will treat it as a PEP 440 URL r...
First, it checks whether a provided path is an installable directory (e.g. it has a setup.py). If it is, returns the path.
def _get_url_from_path(path, name): # type: (str, str) -> Optional[str] """ First, it checks whether a provided path is an installable directory (e.g. it has a setup.py). If it is, returns the path. If false, check if the path is an archive file (such as a .whl). The function checks if the path...
[ "def", "_get_url_from_path", "(", "path", ",", "name", ")", ":", "# type: (str, str) -> Optional[str]", "if", "_looks_like_path", "(", "name", ")", "and", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "if", "is_installable_dir", "(", "path", ")", "...
[ 256, 0 ]
[ 287, 28 ]
python
en
['en', 'error', 'th']
False
install_req_from_line
( name, # type: str comes_from=None, # type: Optional[Union[str, InstallRequirement]] use_pep517=None, # type: Optional[bool] isolated=False, # type: bool options=None, # type: Optional[Dict[str, Any]] constraint=False, # type: bool line_source=None, # type: Optional[str] user_sup...
Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. :param line_source: An optional string describing where the line is from, for logging purposes in case of an error.
Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL.
def install_req_from_line( name, # type: str comes_from=None, # type: Optional[Union[str, InstallRequirement]] use_pep517=None, # type: Optional[bool] isolated=False, # type: bool options=None, # type: Optional[Dict[str, Any]] constraint=False, # type: bool line_source=None, # type: O...
[ "def", "install_req_from_line", "(", "name", ",", "# type: str", "comes_from", "=", "None", ",", "# type: Optional[Union[str, InstallRequirement]]", "use_pep517", "=", "None", ",", "# type: Optional[bool]", "isolated", "=", "False", ",", "# type: bool", "options", "=", ...
[ 381, 0 ]
[ 409, 5 ]
python
en
['en', 'en', 'en']
True
MultipleObjectMixin.get_queryset
(self)
Return the list of items for this view. The return value must be an iterable and may be an instance of `QuerySet` in which case `QuerySet` specific behavior will be enabled.
Return the list of items for this view.
def get_queryset(self): """ Return the list of items for this view. The return value must be an iterable and may be an instance of `QuerySet` in which case `QuerySet` specific behavior will be enabled. """ if self.queryset is not None: queryset = self.queryse...
[ "def", "get_queryset", "(", "self", ")", ":", "if", "self", ".", "queryset", "is", "not", "None", ":", "queryset", "=", "self", ".", "queryset", "if", "isinstance", "(", "queryset", ",", "QuerySet", ")", ":", "queryset", "=", "queryset", ".", "all", "(...
[ 25, 4 ]
[ 52, 23 ]
python
en
['en', 'error', 'th']
False
MultipleObjectMixin.get_ordering
(self)
Return the field or fields to use for ordering the queryset.
Return the field or fields to use for ordering the queryset.
def get_ordering(self): """ Return the field or fields to use for ordering the queryset. """ return self.ordering
[ "def", "get_ordering", "(", "self", ")", ":", "return", "self", ".", "ordering" ]
[ 54, 4 ]
[ 58, 28 ]
python
en
['en', 'error', 'th']
False
MultipleObjectMixin.paginate_queryset
(self, queryset, page_size)
Paginate the queryset, if needed.
Paginate the queryset, if needed.
def paginate_queryset(self, queryset, page_size): """ Paginate the queryset, if needed. """ paginator = self.get_paginator( queryset, page_size, orphans=self.get_paginate_orphans(), allow_empty_first_page=self.get_allow_empty()) page_kwarg = self.page_kwar...
[ "def", "paginate_queryset", "(", "self", ",", "queryset", ",", "page_size", ")", ":", "paginator", "=", "self", ".", "get_paginator", "(", "queryset", ",", "page_size", ",", "orphans", "=", "self", ".", "get_paginate_orphans", "(", ")", ",", "allow_empty_first...
[ 60, 4 ]
[ 83, 14 ]
python
en
['en', 'error', 'th']
False
MultipleObjectMixin.get_paginate_by
(self, queryset)
Get the number of items to paginate by, or ``None`` for no pagination.
Get the number of items to paginate by, or ``None`` for no pagination.
def get_paginate_by(self, queryset): """ Get the number of items to paginate by, or ``None`` for no pagination. """ return self.paginate_by
[ "def", "get_paginate_by", "(", "self", ",", "queryset", ")", ":", "return", "self", ".", "paginate_by" ]
[ 85, 4 ]
[ 89, 31 ]
python
en
['en', 'error', 'th']
False
MultipleObjectMixin.get_paginator
(self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)
Return an instance of the paginator for this view.
Return an instance of the paginator for this view.
def get_paginator(self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs): """ Return an instance of the paginator for this view. """ return self.paginator_class( queryset, per_page, orphans=orphans, allow_empty_first_page...
[ "def", "get_paginator", "(", "self", ",", "queryset", ",", "per_page", ",", "orphans", "=", "0", ",", "allow_empty_first_page", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "paginator_class", "(", "queryset", ",", "per_page", ",",...
[ 91, 4 ]
[ 98, 68 ]
python
en
['en', 'error', 'th']
False
MultipleObjectMixin.get_paginate_orphans
(self)
Returns the maximum number of orphans extend the last page by when paginating.
Returns the maximum number of orphans extend the last page by when paginating.
def get_paginate_orphans(self): """ Returns the maximum number of orphans extend the last page by when paginating. """ return self.paginate_orphans
[ "def", "get_paginate_orphans", "(", "self", ")", ":", "return", "self", ".", "paginate_orphans" ]
[ 100, 4 ]
[ 105, 36 ]
python
en
['en', 'error', 'th']
False
MultipleObjectMixin.get_allow_empty
(self)
Returns ``True`` if the view should display empty lists, and ``False`` if a 404 should be raised instead.
Returns ``True`` if the view should display empty lists, and ``False`` if a 404 should be raised instead.
def get_allow_empty(self): """ Returns ``True`` if the view should display empty lists, and ``False`` if a 404 should be raised instead. """ return self.allow_empty
[ "def", "get_allow_empty", "(", "self", ")", ":", "return", "self", ".", "allow_empty" ]
[ 107, 4 ]
[ 112, 31 ]
python
en
['en', 'error', 'th']
False
MultipleObjectMixin.get_context_object_name
(self, object_list)
Get the name of the item to be used in the context.
Get the name of the item to be used in the context.
def get_context_object_name(self, object_list): """ Get the name of the item to be used in the context. """ if self.context_object_name: return self.context_object_name elif hasattr(object_list, 'model'): return '%s_list' % object_list.model._meta.model_na...
[ "def", "get_context_object_name", "(", "self", ",", "object_list", ")", ":", "if", "self", ".", "context_object_name", ":", "return", "self", ".", "context_object_name", "elif", "hasattr", "(", "object_list", ",", "'model'", ")", ":", "return", "'%s_list'", "%",...
[ 114, 4 ]
[ 123, 23 ]
python
en
['en', 'error', 'th']
False
MultipleObjectMixin.get_context_data
(self, **kwargs)
Get the context for this view.
Get the context for this view.
def get_context_data(self, **kwargs): """ Get the context for this view. """ queryset = kwargs.pop('object_list', self.object_list) page_size = self.get_paginate_by(queryset) context_object_name = self.get_context_object_name(queryset) if page_size: pa...
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "queryset", "=", "kwargs", ".", "pop", "(", "'object_list'", ",", "self", ".", "object_list", ")", "page_size", "=", "self", ".", "get_paginate_by", "(", "queryset", ")", "context_o...
[ 125, 4 ]
[ 150, 75 ]
python
en
['en', 'error', 'th']
False
MultipleObjectTemplateResponseMixin.get_template_names
(self)
Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.
Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.
def get_template_names(self): """ Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden. """ try: names = super(MultipleObjectTemplateResponseMixin, self).get_template_names() exce...
[ "def", "get_template_names", "(", "self", ")", ":", "try", ":", "names", "=", "super", "(", "MultipleObjectTemplateResponseMixin", ",", "self", ")", ".", "get_template_names", "(", ")", "except", "ImproperlyConfigured", ":", "# If template_name isn't specified, it's not...
[ 183, 4 ]
[ 203, 20 ]
python
en
['en', 'error', 'th']
False
noise_level
(freq_eff, bandwidth, tau_time, antenna_set, Ncore, Nremote, Nintl)
Returns the theoretical noise level (in Jy) given the supplied array antenna_set. :param bandwidth: in Hz :param tau_time: in seconds :param inner: in case of LBA, inner or outer :param antenna_set: LBA_INNER, LBA_OUTER, LBA_SPARSE, LBA or HBA
Returns the theoretical noise level (in Jy) given the supplied array antenna_set.
def noise_level(freq_eff, bandwidth, tau_time, antenna_set, Ncore, Nremote, Nintl): """ Returns the theoretical noise level (in Jy) given the supplied array antenna_set. :param bandwidth: in Hz :param tau_time: in seconds :param inner: in case of LBA, inner or outer :param a...
[ "def", "noise_level", "(", "freq_eff", ",", "bandwidth", ",", "tau_time", ",", "antenna_set", ",", "Ncore", ",", "Nremote", ",", "Nintl", ")", ":", "if", "antenna_set", ".", "startswith", "(", "\"LBA\"", ")", ":", "ds_core", "=", "antennaarrays", ".", "cor...
[ 28, 0 ]
[ 93, 21 ]
python
en
['en', 'error', 'th']
False
Aeff_dipole
(freq_eff, distance=None)
The effective area of each dipole in the array is determined by its distance to the nearest dipole (d) within the full array. :param freq_eff: Frequency :param distance: Distance to nearest dipole, only required for LBA.
The effective area of each dipole in the array is determined by its distance to the nearest dipole (d) within the full array.
def Aeff_dipole(freq_eff, distance=None): """ The effective area of each dipole in the array is determined by its distance to the nearest dipole (d) within the full array. :param freq_eff: Frequency :param distance: Distance to nearest dipole, only required for LBA. """ wavelength = scipy.c...
[ "def", "Aeff_dipole", "(", "freq_eff", ",", "distance", "=", "None", ")", ":", "wavelength", "=", "scipy", ".", "constants", ".", "c", "/", "freq_eff", "if", "wavelength", ">", "3", ":", "# LBA dipole", "if", "not", "distance", ":", "msg", "=", "\"Distan...
[ 96, 0 ]
[ 113, 50 ]
python
en
['en', 'error', 'th']
False
system_sensitivity
(freq_eff, Aeff)
Returns the SEFD of a system, given the freq_eff and effective collecting area. Returns SEFD in Jansky's.
Returns the SEFD of a system, given the freq_eff and effective collecting area. Returns SEFD in Jansky's.
def system_sensitivity(freq_eff, Aeff): """ Returns the SEFD of a system, given the freq_eff and effective collecting area. Returns SEFD in Jansky's. """ wavelength = scipy.constants.c / freq_eff # Ts0 = 60 +/- 20 K for Galactic latitudes between 10 and 90 degrees. Ts0 = 60 # system ef...
[ "def", "system_sensitivity", "(", "freq_eff", ",", "Aeff", ")", ":", "wavelength", "=", "scipy", ".", "constants", ".", "c", "/", "freq_eff", "# Ts0 = 60 +/- 20 K for Galactic latitudes between 10 and 90 degrees.", "Ts0", "=", "60", "# system efficiency factor (~ 1.0)", "...
[ 116, 0 ]
[ 161, 21 ]
python
en
['en', 'error', 'th']
False
Configuration.make_static_lib_name
(self, name)
Return the full filename for the specified library name
Return the full filename for the specified library name
def make_static_lib_name(self, name): """Return the full filename for the specified library name""" if self.is_windows: assert name == 'c++' # Only allow libc++ to use this function for now. return 'lib' + name + '.lib' else: return 'lib' + name + '.a'
[ "def", "make_static_lib_name", "(", "self", ",", "name", ")", ":", "if", "self", ".", "is_windows", ":", "assert", "name", "==", "'c++'", "# Only allow libc++ to use this function for now.", "return", "'lib'", "+", "name", "+", "'.lib'", "else", ":", "return", "...
[ 120, 4 ]
[ 126, 38 ]
python
en
['en', 'en', 'en']
True
Configuration.configure_use_clang_verify
(self)
If set, run clang with -verify on failing tests.
If set, run clang with -verify on failing tests.
def configure_use_clang_verify(self): '''If set, run clang with -verify on failing tests.''' self.use_clang_verify = self.get_lit_bool('use_clang_verify') if self.use_clang_verify is None: # NOTE: We do not test for the -verify flag directly because # -verify will alway...
[ "def", "configure_use_clang_verify", "(", "self", ")", ":", "self", ".", "use_clang_verify", "=", "self", ".", "get_lit_bool", "(", "'use_clang_verify'", ")", "if", "self", ".", "use_clang_verify", "is", "None", ":", "# NOTE: We do not test for the -verify flag directly...
[ 332, 4 ]
[ 342, 68 ]
python
en
['en', 'en', 'en']
True
Configuration.configure_use_thread_safety
(self)
If set, run clang with -verify on failing tests.
If set, run clang with -verify on failing tests.
def configure_use_thread_safety(self): '''If set, run clang with -verify on failing tests.''' has_thread_safety = self.cxx.hasCompileFlag('-Werror=thread-safety') if has_thread_safety: self.cxx.compile_flags += ['-Werror=thread-safety'] self.config.available_features.add(...
[ "def", "configure_use_thread_safety", "(", "self", ")", ":", "has_thread_safety", "=", "self", ".", "cxx", ".", "hasCompileFlag", "(", "'-Werror=thread-safety'", ")", "if", "has_thread_safety", ":", "self", ".", "cxx", ".", "compile_flags", "+=", "[", "'-Werror=th...
[ 344, 4 ]
[ 350, 70 ]
python
en
['en', 'en', 'en']
True
Configuration.parse_config_site_and_add_features
(self, header)
parse_config_site_and_add_features - Deduce and add the test features that that are implied by the #define's in the __config_site header. Return a dictionary containing the macros found in the '__config_site' header.
parse_config_site_and_add_features - Deduce and add the test features that that are implied by the #define's in the __config_site header. Return a dictionary containing the macros found in the '__config_site' header.
def parse_config_site_and_add_features(self, header): """ parse_config_site_and_add_features - Deduce and add the test features that that are implied by the #define's in the __config_site header. Return a dictionary containing the macros found in the '__config_site' header. ...
[ "def", "parse_config_site_and_add_features", "(", "self", ",", "header", ")", ":", "# Parse the macro contents of __config_site by dumping the macros", "# using 'c++ -dM -E' and filtering the predefines.", "predefines", "=", "self", ".", "_dump_macros_verbose", "(", ")", "macros", ...
[ 630, 4 ]
[ 676, 29 ]
python
en
['en', 'en', 'en']
True
dumps
(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False)
Returns URL-safe, sha1 signed base64 compressed JSON string. If key is None, settings.SECRET_KEY is used instead. If compress is True (not the default) checks if compressing using zlib can save some space. Prepends a '.' to signify compression. This is included in the signature, to protect against...
Returns URL-safe, sha1 signed base64 compressed JSON string. If key is None, settings.SECRET_KEY is used instead.
def dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False): """ Returns URL-safe, sha1 signed base64 compressed JSON string. If key is None, settings.SECRET_KEY is used instead. If compress is True (not the default) checks if compressing using zlib can save some...
[ "def", "dumps", "(", "obj", ",", "key", "=", "None", ",", "salt", "=", "'django.core.signing'", ",", "serializer", "=", "JSONSerializer", ",", "compress", "=", "False", ")", ":", "data", "=", "serializer", "(", ")", ".", "dumps", "(", "obj", ")", "# Fl...
[ 98, 0 ]
[ 128, 56 ]
python
en
['en', 'error', 'th']
False
loads
(s, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None)
Reverse of dumps(), raises BadSignature if signature fails. The serializer is expected to accept a bytestring.
Reverse of dumps(), raises BadSignature if signature fails.
def loads(s, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None): """ Reverse of dumps(), raises BadSignature if signature fails. The serializer is expected to accept a bytestring. """ # TimestampSigner.unsign always returns unicode but base64 and zlib # compression o...
[ "def", "loads", "(", "s", ",", "key", "=", "None", ",", "salt", "=", "'django.core.signing'", ",", "serializer", "=", "JSONSerializer", ",", "max_age", "=", "None", ")", ":", "# TimestampSigner.unsign always returns unicode but base64 and zlib", "# compression operate o...
[ 131, 0 ]
[ 148, 35 ]
python
en
['en', 'error', 'th']
False
TimestampSigner.unsign
(self, value, max_age=None)
Retrieve original value and check it wasn't signed more than max_age seconds ago.
Retrieve original value and check it wasn't signed more than max_age seconds ago.
def unsign(self, value, max_age=None): """ Retrieve original value and check it wasn't signed more than max_age seconds ago. """ result = super(TimestampSigner, self).unsign(value) value, timestamp = result.rsplit(self.sep, 1) timestamp = baseconv.base62.decode(ti...
[ "def", "unsign", "(", "self", ",", "value", ",", "max_age", "=", "None", ")", ":", "result", "=", "super", "(", "TimestampSigner", ",", "self", ")", ".", "unsign", "(", "value", ")", "value", ",", "timestamp", "=", "result", ".", "rsplit", "(", "self...
[ 193, 4 ]
[ 209, 20 ]
python
en
['en', 'error', 'th']
False
LayerMapping.__init__
(self, model, data, mapping, layer=0, source_srs=None, encoding='utf-8', transaction_mode='commit_on_success', transform=True, unique=None, using=None)
A LayerMapping object is initialized using the given Model (not an instance), a DataSource (or string path to an OGR-supported data file), and a mapping dictionary. See the module level docstring for more details and keyword argument usage.
A LayerMapping object is initialized using the given Model (not an instance), a DataSource (or string path to an OGR-supported data file), and a mapping dictionary. See the module level docstring for more details and keyword argument usage.
def __init__(self, model, data, mapping, layer=0, source_srs=None, encoding='utf-8', transaction_mode='commit_on_success', transform=True, unique=None, using=None): """ A LayerMapping object is initialized using the given Model (not an instance), ...
[ "def", "__init__", "(", "self", ",", "model", ",", "data", ",", "mapping", ",", "layer", "=", "0", ",", "source_srs", "=", "None", ",", "encoding", "=", "'utf-8'", ",", "transaction_mode", "=", "'commit_on_success'", ",", "transform", "=", "True", ",", "...
[ 80, 4 ]
[ 149, 87 ]
python
en
['en', 'error', 'th']
False
LayerMapping.check_fid_range
(self, fid_range)
This checks the `fid_range` keyword.
This checks the `fid_range` keyword.
def check_fid_range(self, fid_range): "This checks the `fid_range` keyword." if fid_range: if isinstance(fid_range, (tuple, list)): return slice(*fid_range) elif isinstance(fid_range, slice): return fid_range else: raise...
[ "def", "check_fid_range", "(", "self", ",", "fid_range", ")", ":", "if", "fid_range", ":", "if", "isinstance", "(", "fid_range", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "slice", "(", "*", "fid_range", ")", "elif", "isinstance", "(", "f...
[ 152, 4 ]
[ 162, 23 ]
python
en
['en', 'hmn', 'en']
True
LayerMapping.check_layer
(self)
This checks the Layer metadata, and ensures that it is compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer.
This checks the Layer metadata, and ensures that it is compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer.
def check_layer(self): """ This checks the Layer metadata, and ensures that it is compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer. """ # The geometry field of the model is set h...
[ "def", "check_layer", "(", "self", ")", ":", "# The geometry field of the model is set here.", "# TODO: Support more than one geometry field / model. However, this", "# depends on the GDAL Driver in use.", "self", ".", "geom_field", "=", "False", "self", ".", "fields", "=", "{",...
[ 164, 4 ]
[ 259, 48 ]
python
en
['en', 'error', 'th']
False
LayerMapping.check_srs
(self, source_srs)
Checks the compatibility of the given spatial reference object.
Checks the compatibility of the given spatial reference object.
def check_srs(self, source_srs): "Checks the compatibility of the given spatial reference object." if isinstance(source_srs, SpatialReference): sr = source_srs elif isinstance(source_srs, self.spatial_backend.spatial_ref_sys()): sr = source_srs.srs elif isinstanc...
[ "def", "check_srs", "(", "self", ",", "source_srs", ")", ":", "if", "isinstance", "(", "source_srs", ",", "SpatialReference", ")", ":", "sr", "=", "source_srs", "elif", "isinstance", "(", "source_srs", ",", "self", ".", "spatial_backend", ".", "spatial_ref_sys...
[ 261, 4 ]
[ 277, 21 ]
python
en
['en', 'en', 'en']
True
LayerMapping.check_unique
(self, unique)
Checks the `unique` keyword parameter -- may be a sequence or string.
Checks the `unique` keyword parameter -- may be a sequence or string.
def check_unique(self, unique): "Checks the `unique` keyword parameter -- may be a sequence or string." if isinstance(unique, (list, tuple)): # List of fields to determine uniqueness with for attr in unique: if attr not in self.mapping: raise V...
[ "def", "check_unique", "(", "self", ",", "unique", ")", ":", "if", "isinstance", "(", "unique", ",", "(", "list", ",", "tuple", ")", ")", ":", "# List of fields to determine uniqueness with", "for", "attr", "in", "unique", ":", "if", "attr", "not", "in", "...
[ 279, 4 ]
[ 291, 97 ]
python
en
['en', 'en', 'en']
True
LayerMapping.feature_kwargs
(self, feat)
Given an OGR Feature, this will return a dictionary of keyword arguments for constructing the mapped model.
Given an OGR Feature, this will return a dictionary of keyword arguments for constructing the mapped model.
def feature_kwargs(self, feat): """ Given an OGR Feature, this will return a dictionary of keyword arguments for constructing the mapped model. """ # The keyword arguments for model construction. kwargs = {} # Incrementing through each model field and OGR field i...
[ "def", "feature_kwargs", "(", "self", ",", "feat", ")", ":", "# The keyword arguments for model construction.", "kwargs", "=", "{", "}", "# Incrementing through each model field and OGR field in the", "# dictionary mapping.", "for", "field_name", ",", "ogr_name", "in", "self"...
[ 294, 4 ]
[ 325, 21 ]
python
en
['en', 'error', 'th']
False
LayerMapping.unique_kwargs
(self, kwargs)
Given the feature keyword arguments (from `feature_kwargs`) this routine will construct and return the uniqueness keyword arguments -- a subset of the feature kwargs.
Given the feature keyword arguments (from `feature_kwargs`) this routine will construct and return the uniqueness keyword arguments -- a subset of the feature kwargs.
def unique_kwargs(self, kwargs): """ Given the feature keyword arguments (from `feature_kwargs`) this routine will construct and return the uniqueness keyword arguments -- a subset of the feature kwargs. """ if isinstance(self.unique, six.string_types): return...
[ "def", "unique_kwargs", "(", "self", ",", "kwargs", ")", ":", "if", "isinstance", "(", "self", ".", "unique", ",", "six", ".", "string_types", ")", ":", "return", "{", "self", ".", "unique", ":", "kwargs", "[", "self", ".", "unique", "]", "}", "else"...
[ 327, 4 ]
[ 336, 60 ]
python
en
['en', 'error', 'th']
False
LayerMapping.verify_ogr_field
(self, ogr_field, model_field)
Verifies if the OGR Field contents are acceptable to the Django model field. If they are, the verified value is returned, otherwise the proper exception is raised.
Verifies if the OGR Field contents are acceptable to the Django model field. If they are, the verified value is returned, otherwise the proper exception is raised.
def verify_ogr_field(self, ogr_field, model_field): """ Verifies if the OGR Field contents are acceptable to the Django model field. If they are, the verified value is returned, otherwise the proper exception is raised. """ if (isinstance(ogr_field, OFTString) and ...
[ "def", "verify_ogr_field", "(", "self", ",", "ogr_field", ",", "model_field", ")", ":", "if", "(", "isinstance", "(", "ogr_field", ",", "OFTString", ")", "and", "isinstance", "(", "model_field", ",", "(", "models", ".", "CharField", ",", "models", ".", "Te...
[ 339, 4 ]
[ 395, 18 ]
python
en
['en', 'error', 'th']
False
LayerMapping.verify_fk
(self, feat, rel_model, rel_mapping)
Given an OGR Feature, the related model and its dictionary mapping, this routine will retrieve the related model for the ForeignKey mapping.
Given an OGR Feature, the related model and its dictionary mapping, this routine will retrieve the related model for the ForeignKey mapping.
def verify_fk(self, feat, rel_model, rel_mapping): """ Given an OGR Feature, the related model and its dictionary mapping, this routine will retrieve the related model for the ForeignKey mapping. """ # TODO: It is expensive to retrieve a model for every record -- ...
[ "def", "verify_fk", "(", "self", ",", "feat", ",", "rel_model", ",", "rel_mapping", ")", ":", "# TODO: It is expensive to retrieve a model for every record --", "# explore if an efficient mechanism exists for caching related", "# ForeignKey models.", "# Constructing and verifying the...
[ 397, 4 ]
[ 419, 13 ]
python
en
['en', 'error', 'th']
False
LayerMapping.verify_geom
(self, geom, model_field)
Verifies the geometry -- will construct and return a GeometryCollection if necessary (for example if the model field is MultiPolygonField while the mapped shapefile only contains Polygons).
Verifies the geometry -- will construct and return a GeometryCollection if necessary (for example if the model field is MultiPolygonField while the mapped shapefile only contains Polygons).
def verify_geom(self, geom, model_field): """ Verifies the geometry -- will construct and return a GeometryCollection if necessary (for example if the model field is MultiPolygonField while the mapped shapefile only contains Polygons). """ # Downgrade a 3D geom to a 2D on...
[ "def", "verify_geom", "(", "self", ",", "geom", ",", "model_field", ")", ":", "# Downgrade a 3D geom to a 2D one, if necessary.", "if", "self", ".", "coord_dim", "!=", "geom", ".", "coord_dim", ":", "geom", ".", "coord_dim", "=", "self", ".", "coord_dim", "if", ...
[ 421, 4 ]
[ 446, 20 ]
python
en
['en', 'error', 'th']
False
LayerMapping.coord_transform
(self)
Returns the coordinate transformation object.
Returns the coordinate transformation object.
def coord_transform(self): "Returns the coordinate transformation object." SpatialRefSys = self.spatial_backend.spatial_ref_sys() try: # Getting the target spatial reference system target_srs = SpatialRefSys.objects.using(self.using).get(srid=self.geo_field.srid).srs ...
[ "def", "coord_transform", "(", "self", ")", ":", "SpatialRefSys", "=", "self", ".", "spatial_backend", ".", "spatial_ref_sys", "(", ")", "try", ":", "# Getting the target spatial reference system", "target_srs", "=", "SpatialRefSys", ".", "objects", ".", "using", "(...
[ 449, 4 ]
[ 460, 81 ]
python
en
['en', 'en', 'en']
True
LayerMapping.geometry_field
(self)
Returns the GeometryField instance associated with the geographic column.
Returns the GeometryField instance associated with the geographic column.
def geometry_field(self): "Returns the GeometryField instance associated with the geographic column." # Use `get_field()` on the model's options so that we # get the correct field instance if there's model inheritance. opts = self.model._meta return opts.get_field(self.geom_field...
[ "def", "geometry_field", "(", "self", ")", ":", "# Use `get_field()` on the model's options so that we", "# get the correct field instance if there's model inheritance.", "opts", "=", "self", ".", "model", ".", "_meta", "return", "opts", ".", "get_field", "(", "self", ".", ...
[ 462, 4 ]
[ 467, 46 ]
python
en
['en', 'en', 'en']
True
LayerMapping.make_multi
(self, geom_type, model_field)
Given the OGRGeomType for a geometry and its associated GeometryField, determine whether the geometry should be turned into a GeometryCollection.
Given the OGRGeomType for a geometry and its associated GeometryField, determine whether the geometry should be turned into a GeometryCollection.
def make_multi(self, geom_type, model_field): """ Given the OGRGeomType for a geometry and its associated GeometryField, determine whether the geometry should be turned into a GeometryCollection. """ return (geom_type.num in self.MULTI_TYPES and model_field.__clas...
[ "def", "make_multi", "(", "self", ",", "geom_type", ",", "model_field", ")", ":", "return", "(", "geom_type", ".", "num", "in", "self", ".", "MULTI_TYPES", "and", "model_field", ".", "__class__", ".", "__name__", "==", "'Multi%s'", "%", "geom_type", ".", "...
[ 469, 4 ]
[ 475, 79 ]
python
en
['en', 'error', 'th']
False
LayerMapping.save
(self, verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False)
Saves the contents from the OGR DataSource Layer into the database according to the mapping dictionary given at initialization. Keyword Parameters: verbose: If set, information will be printed subsequent to each model save executed on the database. fid_...
Saves the contents from the OGR DataSource Layer into the database according to the mapping dictionary given at initialization.
def save(self, verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False): """ Saves the contents from the OGR DataSource Layer into the database according to the mapping dictionary given at initialization. Keyword Parameters:...
[ "def", "save", "(", "self", ",", "verbose", "=", "False", ",", "fid_range", "=", "False", ",", "step", "=", "False", ",", "progress", "=", "False", ",", "silent", "=", "False", ",", "stream", "=", "sys", ".", "stdout", ",", "strict", "=", "False", ...
[ 477, 4 ]
[ 628, 19 ]
python
en
['en', 'error', 'th']
False
Feature.__init__
(self, feat, layer)
Initializes Feature from a pointer and its Layer object.
Initializes Feature from a pointer and its Layer object.
def __init__(self, feat, layer): """ Initializes Feature from a pointer and its Layer object. """ if not feat: raise GDALException('Cannot create OGR Feature, invalid pointer given.') self.ptr = feat self._layer = layer
[ "def", "__init__", "(", "self", ",", "feat", ",", "layer", ")", ":", "if", "not", "feat", ":", "raise", "GDALException", "(", "'Cannot create OGR Feature, invalid pointer given.'", ")", "self", ".", "ptr", "=", "feat", "self", ".", "_layer", "=", "layer" ]
[ 21, 4 ]
[ 28, 27 ]
python
en
['en', 'error', 'th']
False
Feature.__getitem__
(self, index)
Gets the Field object at the specified index, which may be either an integer or the Field's string label. Note that the Field object is not the field's _value_ -- use the `get` method instead to retrieve the value (e.g. an integer) instead of a Field instance.
Gets the Field object at the specified index, which may be either an integer or the Field's string label. Note that the Field object is not the field's _value_ -- use the `get` method instead to retrieve the value (e.g. an integer) instead of a Field instance.
def __getitem__(self, index): """ Gets the Field object at the specified index, which may be either an integer or the Field's string label. Note that the Field object is not the field's _value_ -- use the `get` method instead to retrieve the value (e.g. an integer) instead of a ...
[ "def", "__getitem__", "(", "self", ",", "index", ")", ":", "if", "isinstance", "(", "index", ",", "six", ".", "string_types", ")", ":", "i", "=", "self", ".", "index", "(", "index", ")", "else", ":", "if", "index", "<", "0", "or", "index", ">", "...
[ 30, 4 ]
[ 43, 29 ]
python
en
['en', 'error', 'th']
False
Feature.__iter__
(self)
Iterates over each field in the Feature.
Iterates over each field in the Feature.
def __iter__(self): "Iterates over each field in the Feature." for i in range(self.num_fields): yield self[i]
[ "def", "__iter__", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "num_fields", ")", ":", "yield", "self", "[", "i", "]" ]
[ 45, 4 ]
[ 48, 25 ]
python
en
['en', 'en', 'en']
True
Feature.__len__
(self)
Returns the count of fields in this feature.
Returns the count of fields in this feature.
def __len__(self): "Returns the count of fields in this feature." return self.num_fields
[ "def", "__len__", "(", "self", ")", ":", "return", "self", ".", "num_fields" ]
[ 50, 4 ]
[ 52, 30 ]
python
en
['en', 'en', 'en']
True
Feature.__str__
(self)
The string name of the feature.
The string name of the feature.
def __str__(self): "The string name of the feature." return 'Feature FID %d in Layer<%s>' % (self.fid, self.layer_name)
[ "def", "__str__", "(", "self", ")", ":", "return", "'Feature FID %d in Layer<%s>'", "%", "(", "self", ".", "fid", ",", "self", ".", "layer_name", ")" ]
[ 54, 4 ]
[ 56, 74 ]
python
en
['en', 'en', 'en']
True
Feature.__eq__
(self, other)
Does equivalence testing on the features.
Does equivalence testing on the features.
def __eq__(self, other): "Does equivalence testing on the features." return bool(capi.feature_equal(self.ptr, other._ptr))
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "bool", "(", "capi", ".", "feature_equal", "(", "self", ".", "ptr", ",", "other", ".", "_ptr", ")", ")" ]
[ 58, 4 ]
[ 60, 61 ]
python
en
['en', 'en', 'en']
True
Feature.fid
(self)
Returns the feature identifier.
Returns the feature identifier.
def fid(self): "Returns the feature identifier." return capi.get_fid(self.ptr)
[ "def", "fid", "(", "self", ")", ":", "return", "capi", ".", "get_fid", "(", "self", ".", "ptr", ")" ]
[ 68, 4 ]
[ 70, 37 ]
python
en
['en', 'en', 'en']
True
Feature.layer_name
(self)
Returns the name of the layer for the feature.
Returns the name of the layer for the feature.
def layer_name(self): "Returns the name of the layer for the feature." name = capi.get_feat_name(self._layer._ldefn) return force_text(name, self.encoding, strings_only=True)
[ "def", "layer_name", "(", "self", ")", ":", "name", "=", "capi", ".", "get_feat_name", "(", "self", ".", "_layer", ".", "_ldefn", ")", "return", "force_text", "(", "name", ",", "self", ".", "encoding", ",", "strings_only", "=", "True", ")" ]
[ 73, 4 ]
[ 76, 65 ]
python
en
['en', 'en', 'en']
True
Feature.num_fields
(self)
Returns the number of fields in the Feature.
Returns the number of fields in the Feature.
def num_fields(self): "Returns the number of fields in the Feature." return capi.get_feat_field_count(self.ptr)
[ "def", "num_fields", "(", "self", ")", ":", "return", "capi", ".", "get_feat_field_count", "(", "self", ".", "ptr", ")" ]
[ 79, 4 ]
[ 81, 50 ]
python
en
['en', 'en', 'en']
True
Feature.fields
(self)
Returns a list of fields in the Feature.
Returns a list of fields in the Feature.
def fields(self): "Returns a list of fields in the Feature." return [capi.get_field_name(capi.get_field_defn(self._layer._ldefn, i)) for i in range(self.num_fields)]
[ "def", "fields", "(", "self", ")", ":", "return", "[", "capi", ".", "get_field_name", "(", "capi", ".", "get_field_defn", "(", "self", ".", "_layer", ".", "_ldefn", ",", "i", ")", ")", "for", "i", "in", "range", "(", "self", ".", "num_fields", ")", ...
[ 84, 4 ]
[ 87, 48 ]
python
en
['en', 'en', 'en']
True
Feature.geom
(self)
Returns the OGR Geometry for this Feature.
Returns the OGR Geometry for this Feature.
def geom(self): "Returns the OGR Geometry for this Feature." # Retrieving the geometry pointer for the feature. geom_ptr = capi.get_feat_geom_ref(self.ptr) return OGRGeometry(geom_api.clone_geom(geom_ptr))
[ "def", "geom", "(", "self", ")", ":", "# Retrieving the geometry pointer for the feature.", "geom_ptr", "=", "capi", ".", "get_feat_geom_ref", "(", "self", ".", "ptr", ")", "return", "OGRGeometry", "(", "geom_api", ".", "clone_geom", "(", "geom_ptr", ")", ")" ]
[ 90, 4 ]
[ 94, 57 ]
python
en
['en', 'en', 'en']
True
Feature.geom_type
(self)
Returns the OGR Geometry Type for this Feture.
Returns the OGR Geometry Type for this Feture.
def geom_type(self): "Returns the OGR Geometry Type for this Feture." return OGRGeomType(capi.get_fd_geom_type(self._layer._ldefn))
[ "def", "geom_type", "(", "self", ")", ":", "return", "OGRGeomType", "(", "capi", ".", "get_fd_geom_type", "(", "self", ".", "_layer", ".", "_ldefn", ")", ")" ]
[ 97, 4 ]
[ 99, 69 ]
python
en
['en', 'en', 'en']
True
Feature.get
(self, field)
Returns the value of the field, instead of an instance of the Field object. May take a string of the field name or a Field object as parameters.
Returns the value of the field, instead of an instance of the Field object. May take a string of the field name or a Field object as parameters.
def get(self, field): """ Returns the value of the field, instead of an instance of the Field object. May take a string of the field name or a Field object as parameters. """ field_name = getattr(field, 'name', field) return self[field_name].value
[ "def", "get", "(", "self", ",", "field", ")", ":", "field_name", "=", "getattr", "(", "field", ",", "'name'", ",", "field", ")", "return", "self", "[", "field_name", "]", ".", "value" ]
[ 102, 4 ]
[ 109, 37 ]
python
en
['en', 'error', 'th']
False
Feature.index
(self, field_name)
Returns the index of the given field name.
Returns the index of the given field name.
def index(self, field_name): "Returns the index of the given field name." i = capi.get_field_index(self.ptr, force_bytes(field_name)) if i < 0: raise OGRIndexError('invalid OFT field name given: "%s"' % field_name) return i
[ "def", "index", "(", "self", ",", "field_name", ")", ":", "i", "=", "capi", ".", "get_field_index", "(", "self", ".", "ptr", ",", "force_bytes", "(", "field_name", ")", ")", "if", "i", "<", "0", ":", "raise", "OGRIndexError", "(", "'invalid OFT field nam...
[ 111, 4 ]
[ 116, 16 ]
python
en
['en', 'en', 'en']
True
BO.__init__
(self, results_path=None, results=pd.DataFrame(), domain_path=None, domain=pd.DataFrame(), exindex_path=None, exindex=pd.DataFrame(), model=GP_Model, acquisition_function='EI', init_method='rand', target=-1, batch_siz...
Experimental results, experimental domain, and experiment index of known results can be passed as paths to .csv or .xlsx files or as DataFrames. Parameters ---------- results_path : str, optional Path to experimental results. results : pand...
Experimental results, experimental domain, and experiment index of known results can be passed as paths to .csv or .xlsx files or as DataFrames. Parameters ---------- results_path : str, optional Path to experimental results. results : pand...
def __init__(self, results_path=None, results=pd.DataFrame(), domain_path=None, domain=pd.DataFrame(), exindex_path=None, exindex=pd.DataFrame(), model=GP_Model, acquisition_function='EI', init_method='rand', target=-...
[ "def", "__init__", "(", "self", ",", "results_path", "=", "None", ",", "results", "=", "pd", ".", "DataFrame", "(", ")", ",", "domain_path", "=", "None", ",", "domain", "=", "pd", ".", "DataFrame", "(", ")", ",", "exindex_path", "=", "None", ",", "ex...
[ 34, 4 ]
[ 154, 38 ]
python
en
['en', 'error', 'th']
False
BO.init_sample
(self, seed=None, append=False, export_path=None, visualize=False)
Generate initial samples via an initialization method. Parameters ---------- seed : None, int Random seed used for selecting initial points. append : bool Append points to results if computational objective or experiment index are available. ...
Generate initial samples via an initialization method. Parameters ---------- seed : None, int Random seed used for selecting initial points. append : bool Append points to results if computational objective or experiment index are available. ...
def init_sample(self, seed=None, append=False, export_path=None, visualize=False): """Generate initial samples via an initialization method. Parameters ---------- seed : None, int Random seed used for selecting initial points. append : boo...
[ "def", "init_sample", "(", "self", ",", "seed", "=", "None", ",", "append", "=", "False", ",", "export_path", "=", "None", ",", "visualize", "=", "False", ")", ":", "# Run initialization sequence", "if", "self", ".", "init_seq", ".", "method", "!=", "'exte...
[ 157, 4 ]
[ 194, 40 ]
python
en
['en', 'id', 'en']
True
BO.fit
(self, n_restarts=0, learning_rate=0.1, training_iters=100)
Fit surrogate model. Parameters ---------- n_restarts : int Number of restarts used when optimizing GPyTorch model parameters. learning_rate : float ADAM learning rate used when optimizing GPyTorch model parameters. training_iters : int ...
Fit surrogate model. Parameters ---------- n_restarts : int Number of restarts used when optimizing GPyTorch model parameters. learning_rate : float ADAM learning rate used when optimizing GPyTorch model parameters. training_iters : int ...
def fit(self, n_restarts=0, learning_rate=0.1, training_iters=100): """Fit surrogate model. Parameters ---------- n_restarts : int Number of restarts used when optimizing GPyTorch model parameters. learning_rate : float ADAM learning rate used whe...
[ "def", "fit", "(", "self", ",", "n_restarts", "=", "0", ",", "learning_rate", "=", "0.1", ",", "training_iters", "=", "100", ")", ":", "# Initialize and train model", "self", ".", "model", "=", "self", ".", "base_model", "(", "self", ".", "obj", ".", "X"...
[ 197, 4 ]
[ 229, 24 ]
python
fr
['fr', 'fr', 'it']
True
BO.run
(self, append=False, n_restarts=0, learning_rate=0.1, training_iters=100)
Run a single iteration of optimization with known results. Note ---- Use run for human-in-the-loop optimization. Parameters ---------- append : bool Append points to results if computational objective or experiment index are avail...
Run a single iteration of optimization with known results. Note ---- Use run for human-in-the-loop optimization. Parameters ---------- append : bool Append points to results if computational objective or experiment index are avail...
def run(self, append=False, n_restarts=0, learning_rate=0.1, training_iters=100): """Run a single iteration of optimization with known results. Note ---- Use run for human-in-the-loop optimization. Parameters ---------- append : bool ...
[ "def", "run", "(", "self", ",", "append", "=", "False", ",", "n_restarts", "=", "0", ",", "learning_rate", "=", "0.1", ",", "training_iters", "=", "100", ")", ":", "# Initialize and train model", "self", ".", "model", "=", "self", ".", "base_model", "(", ...
[ 232, 4 ]
[ 282, 40 ]
python
en
['en', 'en', 'en']
True
BO.simulate
(self, iterations=1, seed=None, update_priors=False, n_restarts=0, learning_rate=0.1, training_iters=100)
Run autonomous BO loop. Run N iterations of optimization with initial results obtained via initialization method and experiments selected from experiment index via the acquisition function. Simulations require know objectives via an index of results or function. ...
Run autonomous BO loop. Run N iterations of optimization with initial results obtained via initialization method and experiments selected from experiment index via the acquisition function. Simulations require know objectives via an index of results or function. ...
def simulate(self, iterations=1, seed=None, update_priors=False, n_restarts=0, learning_rate=0.1, training_iters=100): """Run autonomous BO loop. Run N iterations of optimization with initial results obtained via initialization method and experiments selected from ...
[ "def", "simulate", "(", "self", ",", "iterations", "=", "1", ",", "seed", "=", "None", ",", "update_priors", "=", "False", ",", "n_restarts", "=", "0", ",", "learning_rate", "=", "0.1", ",", "training_iters", "=", "100", ")", ":", "# Initialization data", ...
[ 285, 4 ]
[ 365, 72 ]
python
en
['fr', 'ms', 'en']
False
BO.clear_results
(self)
Clear results manually. Note ---- 'rand' and 'pam' initialization methods clear results automatically.
Clear results manually. Note ---- 'rand' and 'pam' initialization methods clear results automatically.
def clear_results(self): """Clear results manually. Note ---- 'rand' and 'pam' initialization methods clear results automatically. """ self.obj.clear_results()
[ "def", "clear_results", "(", "self", ")", ":", "self", ".", "obj", ".", "clear_results", "(", ")" ]
[ 368, 4 ]
[ 377, 32 ]
python
en
['en', 'en', 'en']
True
BO.plot_convergence
(self, export_path=None)
Plot optimizer convergence. Parameters ---------- export_path : None, str Path to export SVG of optimizer optimizer convergence plot. Returns ---------- matplotlib.pyplot Plot of optimizer convergence.
Plot optimizer convergence. Parameters ---------- export_path : None, str Path to export SVG of optimizer optimizer convergence plot. Returns ---------- matplotlib.pyplot Plot of optimizer convergence.
def plot_convergence(self, export_path=None): """Plot optimizer convergence. Parameters ---------- export_path : None, str Path to export SVG of optimizer optimizer convergence plot. Returns ---------- matplotlib.pyplot ...
[ "def", "plot_convergence", "(", "self", ",", "export_path", "=", "None", ")", ":", "plot_convergence", "(", "self", ".", "obj", ".", "results_input", "(", ")", "[", "self", ".", "obj", ".", "target", "]", ",", "self", ".", "batch_size", ",", "export_path...
[ 380, 4 ]
[ 397, 40 ]
python
en
['nl', 'zu', 'en']
False
BO.acquisition_summary
(self)
Summarize predicted mean and variance for porposed points. Returns ---------- pandas.DataFrame Summary table.
Summarize predicted mean and variance for porposed points. Returns ---------- pandas.DataFrame Summary table.
def acquisition_summary(self): """Summarize predicted mean and variance for porposed points. Returns ---------- pandas.DataFrame Summary table. """ proposed_experiments = self.proposed_experiments.copy() X = to_torch(proposed_experime...
[ "def", "acquisition_summary", "(", "self", ")", ":", "proposed_experiments", "=", "self", ".", "proposed_experiments", ".", "copy", "(", ")", "X", "=", "to_torch", "(", "proposed_experiments", ",", "gpu", "=", "self", ".", "gpu", ")", "# Compute mean and varianc...
[ 400, 4 ]
[ 420, 35 ]
python
en
['en', 'en', 'en']
True
BO.best
(self)
Best observed objective values and corresponding domain point.
Best observed objective values and corresponding domain point.
def best(self): """Best observed objective values and corresponding domain point.""" sort = self.obj.results_input().sort_values(self.obj.target, ascending=False) return sort.head()
[ "def", "best", "(", "self", ")", ":", "sort", "=", "self", ".", "obj", ".", "results_input", "(", ")", ".", "sort_values", "(", "self", ".", "obj", ".", "target", ",", "ascending", "=", "False", ")", "return", "sort", ".", "head", "(", ")" ]
[ 423, 4 ]
[ 427, 26 ]
python
en
['en', 'en', 'en']
True
BO.save
(self, path='BO.pkl')
Save BO state. Parameters ---------- path : str Path to export <BO state dict>.pkl. Returns ---------- None
Save BO state. Parameters ---------- path : str Path to export <BO state dict>.pkl. Returns ---------- None
def save(self, path='BO.pkl'): """Save BO state. Parameters ---------- path : str Path to export <BO state dict>.pkl. Returns ---------- None """ file = open(path, 'wb') dill.dump(self.__dict__, file...
[ "def", "save", "(", "self", ",", "path", "=", "'BO.pkl'", ")", ":", "file", "=", "open", "(", "path", ",", "'wb'", ")", "dill", ".", "dump", "(", "self", ".", "__dict__", ",", "file", ")", "file", ".", "close", "(", ")" ]
[ 430, 4 ]
[ 445, 20 ]
python
en
['en', 'jv', 'en']
True
BO.load
(self, path='BO.pkl')
Load BO state. Parameters ---------- path : str Path to <BO state dict>.pkl. Returns ---------- None
Load BO state. Parameters ---------- path : str Path to <BO state dict>.pkl. Returns ---------- None
def load(self, path='BO.pkl'): """Load BO state. Parameters ---------- path : str Path to <BO state dict>.pkl. Returns ---------- None """ file = open(path, 'rb') tmp_dict = dill.load(file) f...
[ "def", "load", "(", "self", ",", "path", "=", "'BO.pkl'", ")", ":", "file", "=", "open", "(", "path", ",", "'rb'", ")", "tmp_dict", "=", "dill", ".", "load", "(", "file", ")", "file", ".", "close", "(", ")", "self", ".", "__dict__", ".", "update"...
[ 448, 4 ]
[ 465, 38 ]
python
en
['en', 'en', 'en']
True
BO_express.__init__
(self, reaction_components={}, encoding={}, descriptor_matrices={}, model=GP_Model, acquisition_function='EI', init_method='rand', target=-1, batch_size=5, computational_objective=None)
Parameters ---------- reaction_components : dict Dictionary of reaction components of the form: Example ------- Defining reaction components :: {'A': [a1, a2, a3, ...], 'B...
Parameters ---------- reaction_components : dict Dictionary of reaction components of the form: Example ------- Defining reaction components :: {'A': [a1, a2, a3, ...], 'B...
def __init__(self, reaction_components={}, encoding={}, descriptor_matrices={}, model=GP_Model, acquisition_function='EI', init_method='rand', target=-1, batch_size=5, computational_objective=None): """ Parameters ---------- rea...
[ "def", "__init__", "(", "self", ",", "reaction_components", "=", "{", "}", ",", "encoding", "=", "{", "}", ",", "descriptor_matrices", "=", "{", "}", ",", "model", "=", "GP_Model", ",", "acquisition_function", "=", "'EI'", ",", "init_method", "=", "'rand'"...
[ 532, 4 ]
[ 698, 56 ]
python
en
['en', 'ja', 'th']
False
BO_express.get_experiments
(self, structures=False)
Return indexed experiments proposed by Bayesian optimization algorithm. edbo.BO works directly with a standardized encoded reaction space. This method returns proposed experiments as the origional smiles strings, categories, or numerical values. Parameters ---...
Return indexed experiments proposed by Bayesian optimization algorithm. edbo.BO works directly with a standardized encoded reaction space. This method returns proposed experiments as the origional smiles strings, categories, or numerical values. Parameters ---...
def get_experiments(self, structures=False): """Return indexed experiments proposed by Bayesian optimization algorithm. edbo.BO works directly with a standardized encoded reaction space. This method returns proposed experiments as the origional smiles strings, categories, or n...
[ "def", "get_experiments", "(", "self", ",", "structures", "=", "False", ")", ":", "# Index entries", "experiments", "=", "self", ".", "reaction", ".", "get_experiments", "(", "self", ".", "proposed_experiments", ".", "index", ".", "values", ")", "# SMILES column...
[ 701, 4 ]
[ 734, 26 ]
python
en
['en', 'en', 'en']
True
BO_express.add_results
(self, results_path=None)
Add experimental results. Experimental results should be added with the same column headings as those returned by BO_express.get_experiments. If a path to the results is not specified, an edbo bot is spawned to help load results. It does so by exporting the entire reaction space...
Add experimental results. Experimental results should be added with the same column headings as those returned by BO_express.get_experiments. If a path to the results is not specified, an edbo bot is spawned to help load results. It does so by exporting the entire reaction space...
def add_results(self, results_path=None): """Add experimental results. Experimental results should be added with the same column headings as those returned by BO_express.get_experiments. If a path to the results is not specified, an edbo bot is spawned to help load results. It d...
[ "def", "add_results", "(", "self", ",", "results_path", "=", "None", ")", ":", "if", "results_path", "!=", "None", ":", "results", "=", "load_csv_or_excel", "(", "results_path", ",", "index_col", "=", "0", ")", ".", "dropna", "(", "axis", "=", "0", ")", ...
[ 736, 4 ]
[ 783, 86 ]
python
en
['it', 'en', 'en']
True
BO_express.export_proposed
(self, path=None)
Export proposed experiments. edbo.BO works directly with a standardized encoded reaction space. This method exports proposed experiments as the origional smiles strings, categories, or numerical values. If a path to the results is not specified, a CSV file entitled 'experimen...
Export proposed experiments. edbo.BO works directly with a standardized encoded reaction space. This method exports proposed experiments as the origional smiles strings, categories, or numerical values. If a path to the results is not specified, a CSV file entitled 'experimen...
def export_proposed(self, path=None): """Export proposed experiments. edbo.BO works directly with a standardized encoded reaction space. This method exports proposed experiments as the origional smiles strings, categories, or numerical values. If a path to the results is not ...
[ "def", "export_proposed", "(", "self", ",", "path", "=", "None", ")", ":", "index", "=", "self", ".", "proposed_experiments", ".", "index", ".", "values", "proposed", "=", "self", ".", "reaction", ".", "base_data", "[", "self", ".", "reaction", ".", "ind...
[ 785, 4 ]
[ 815, 33 ]
python
en
['en', 'en', 'en']
True
BO_express.help
(self)
Spawn an edbo bot to help with tasks. If you are not familiar with edbo commands BO_express.help() will spawn an edbo bot to help with tasks. Natural language can be used to interact with edbo bot in the terminal to accomplish tasks such as: initializing (selecting initial exp...
Spawn an edbo bot to help with tasks. If you are not familiar with edbo commands BO_express.help() will spawn an edbo bot to help with tasks. Natural language can be used to interact with edbo bot in the terminal to accomplish tasks such as: initializing (selecting initial exp...
def help(self): """Spawn an edbo bot to help with tasks. If you are not familiar with edbo commands BO_express.help() will spawn an edbo bot to help with tasks. Natural language can be used to interact with edbo bot in the terminal to accomplish tasks such as: initializing ...
[ "def", "help", "(", "self", ")", ":", "# Keywords which trigger responses", "trigger_dict", "=", "{", "'exit'", ":", "[", "'exit'", ",", "'stop'", "]", ",", "'initialize'", ":", "[", "'init'", ",", "'start'", "]", ",", "'optimize'", ":", "[", "'opt'", ",",...
[ 817, 4 ]
[ 908, 54 ]
python
en
['en', 'en', 'en']
True
_normalize_name
(name)
Make a name consistent regardless of source (environment or file)
Make a name consistent regardless of source (environment or file)
def _normalize_name(name): # type: (str) -> str """Make a name consistent regardless of source (environment or file) """ name = name.lower().replace('_', '-') if name.startswith('--'): name = name[2:] # only prefer long opts return name
[ "def", "_normalize_name", "(", "name", ")", ":", "# type: (str) -> str", "name", "=", "name", ".", "lower", "(", ")", ".", "replace", "(", "'_'", ",", "'-'", ")", "if", "name", ".", "startswith", "(", "'--'", ")", ":", "name", "=", "name", "[", "2", ...
[ 53, 0 ]
[ 60, 15 ]
python
en
['en', 'en', 'en']
True
Configuration.load
(self)
Loads configuration from configuration files and environment
Loads configuration from configuration files and environment
def load(self): # type: () -> None """Loads configuration from configuration files and environment """ self._load_config_files() if not self.isolated: self._load_environment_vars()
[ "def", "load", "(", "self", ")", ":", "# type: () -> None", "self", ".", "_load_config_files", "(", ")", "if", "not", "self", ".", "isolated", ":", "self", ".", "_load_environment_vars", "(", ")" ]
[ 133, 4 ]
[ 139, 41 ]
python
en
['en', 'en', 'en']
True
Configuration.get_file_to_edit
(self)
Returns the file with highest priority in configuration
Returns the file with highest priority in configuration
def get_file_to_edit(self): # type: () -> Optional[str] """Returns the file with highest priority in configuration """ assert self.load_only is not None, \ "Need to be specified a file to be editing" try: return self._get_parser_to_modify()[0] exc...
[ "def", "get_file_to_edit", "(", "self", ")", ":", "# type: () -> Optional[str]", "assert", "self", ".", "load_only", "is", "not", "None", ",", "\"Need to be specified a file to be editing\"", "try", ":", "return", "self", ".", "_get_parser_to_modify", "(", ")", "[", ...
[ 141, 4 ]
[ 151, 23 ]
python
en
['en', 'en', 'en']
True
Configuration.items
(self)
Returns key-value pairs like dict.items() representing the loaded configuration
Returns key-value pairs like dict.items() representing the loaded configuration
def items(self): # type: () -> Iterable[Tuple[str, Any]] """Returns key-value pairs like dict.items() representing the loaded configuration """ return self._dictionary.items()
[ "def", "items", "(", "self", ")", ":", "# type: () -> Iterable[Tuple[str, Any]]", "return", "self", ".", "_dictionary", ".", "items", "(", ")" ]
[ 153, 4 ]
[ 158, 39 ]
python
en
['en', 'en', 'en']
True
Configuration.get_value
(self, key)
Get a value from the configuration.
Get a value from the configuration.
def get_value(self, key): # type: (str) -> Any """Get a value from the configuration. """ try: return self._dictionary[key] except KeyError: raise ConfigurationError("No such key - {}".format(key))
[ "def", "get_value", "(", "self", ",", "key", ")", ":", "# type: (str) -> Any", "try", ":", "return", "self", ".", "_dictionary", "[", "key", "]", "except", "KeyError", ":", "raise", "ConfigurationError", "(", "\"No such key - {}\"", ".", "format", "(", "key", ...
[ 160, 4 ]
[ 167, 68 ]
python
en
['en', 'en', 'en']
True
Configuration.set_value
(self, key, value)
Modify a value in the configuration.
Modify a value in the configuration.
def set_value(self, key, value): # type: (str, Any) -> None """Modify a value in the configuration. """ self._ensure_have_load_only() assert self.load_only fname, parser = self._get_parser_to_modify() if parser is not None: section, name = _disassemb...
[ "def", "set_value", "(", "self", ",", "key", ",", "value", ")", ":", "# type: (str, Any) -> None", "self", ".", "_ensure_have_load_only", "(", ")", "assert", "self", ".", "load_only", "fname", ",", "parser", "=", "self", ".", "_get_parser_to_modify", "(", ")",...
[ 169, 4 ]
[ 187, 45 ]
python
en
['en', 'it', 'en']
True
Configuration.unset_value
(self, key)
Unset a value in the configuration.
Unset a value in the configuration.
def unset_value(self, key): # type: (str) -> None """Unset a value in the configuration.""" self._ensure_have_load_only() assert self.load_only if key not in self._config[self.load_only]: raise ConfigurationError("No such key - {}".format(key)) fname, parser...
[ "def", "unset_value", "(", "self", ",", "key", ")", ":", "# type: (str) -> None", "self", ".", "_ensure_have_load_only", "(", ")", "assert", "self", ".", "load_only", "if", "key", "not", "in", "self", ".", "_config", "[", "self", ".", "load_only", "]", ":"...
[ 189, 4 ]
[ 214, 45 ]
python
en
['en', 'en', 'en']
True
Configuration.save
(self)
Save the current in-memory state.
Save the current in-memory state.
def save(self): # type: () -> None """Save the current in-memory state. """ self._ensure_have_load_only() for fname, parser in self._modified_parsers: logger.info("Writing to %s", fname) # Ensure directory exists. ensure_dir(os.path.dirname(f...
[ "def", "save", "(", "self", ")", ":", "# type: () -> None", "self", ".", "_ensure_have_load_only", "(", ")", "for", "fname", ",", "parser", "in", "self", ".", "_modified_parsers", ":", "logger", ".", "info", "(", "\"Writing to %s\"", ",", "fname", ")", "# En...
[ 216, 4 ]
[ 229, 31 ]
python
en
['en', 'en', 'en']
True
Configuration._dictionary
(self)
A dictionary representing the loaded configuration.
A dictionary representing the loaded configuration.
def _dictionary(self): # type: () -> Dict[str, Any] """A dictionary representing the loaded configuration. """ # NOTE: Dictionaries are not populated if not loaded. So, conditionals # are not needed here. retval = {} for variant in OVERRIDE_ORDER: ...
[ "def", "_dictionary", "(", "self", ")", ":", "# type: () -> Dict[str, Any]", "# NOTE: Dictionaries are not populated if not loaded. So, conditionals", "# are not needed here.", "retval", "=", "{", "}", "for", "variant", "in", "OVERRIDE_ORDER", ":", "retval", ".", "updat...
[ 242, 4 ]
[ 253, 21 ]
python
en
['en', 'en', 'en']
True
Configuration._load_config_files
(self)
Loads configuration from configuration files
Loads configuration from configuration files
def _load_config_files(self): # type: () -> None """Loads configuration from configuration files """ config_files = dict(self.iter_config_files()) if config_files[kinds.ENV][0:1] == [os.devnull]: logger.debug( "Skipping loading configuration files due ...
[ "def", "_load_config_files", "(", "self", ")", ":", "# type: () -> None", "config_files", "=", "dict", "(", "self", ".", "iter_config_files", "(", ")", ")", "if", "config_files", "[", "kinds", ".", "ENV", "]", "[", "0", ":", "1", "]", "==", "[", "os", ...
[ 255, 4 ]
[ 280, 62 ]
python
en
['en', 'en', 'en']
True
Configuration._load_environment_vars
(self)
Loads configuration from environment variables
Loads configuration from environment variables
def _load_environment_vars(self): # type: () -> None """Loads configuration from environment variables """ self._config[kinds.ENV_VAR].update( self._normalized_keys(":env:", self.get_environ_vars()) )
[ "def", "_load_environment_vars", "(", "self", ")", ":", "# type: () -> None", "self", ".", "_config", "[", "kinds", ".", "ENV_VAR", "]", ".", "update", "(", "self", ".", "_normalized_keys", "(", "\":env:\"", ",", "self", ".", "get_environ_vars", "(", ")", ")...
[ 316, 4 ]
[ 322, 9 ]
python
en
['en', 'en', 'en']
True
Configuration._normalized_keys
(self, section, items)
Normalizes items to construct a dictionary with normalized keys. This routine is where the names become keys and are made the same regardless of source - configuration files or environment.
Normalizes items to construct a dictionary with normalized keys.
def _normalized_keys(self, section, items): # type: (str, Iterable[Tuple[str, Any]]) -> Dict[str, Any] """Normalizes items to construct a dictionary with normalized keys. This routine is where the names become keys and are made the same regardless of source - configuration files or envi...
[ "def", "_normalized_keys", "(", "self", ",", "section", ",", "items", ")", ":", "# type: (str, Iterable[Tuple[str, Any]]) -> Dict[str, Any]", "normalized", "=", "{", "}", "for", "name", ",", "val", "in", "items", ":", "key", "=", "section", "+", "\".\"", "+", ...
[ 324, 4 ]
[ 335, 25 ]
python
en
['en', 'en', 'en']
True
Configuration.get_environ_vars
(self)
Returns a generator with all environmental vars with prefix PIP_
Returns a generator with all environmental vars with prefix PIP_
def get_environ_vars(self): # type: () -> Iterable[Tuple[str, str]] """Returns a generator with all environmental vars with prefix PIP_""" for key, val in os.environ.items(): if key.startswith("PIP_"): name = key[4:].lower() if name not in ENV_NAMES_IG...
[ "def", "get_environ_vars", "(", "self", ")", ":", "# type: () -> Iterable[Tuple[str, str]]", "for", "key", ",", "val", "in", "os", ".", "environ", ".", "items", "(", ")", ":", "if", "key", ".", "startswith", "(", "\"PIP_\"", ")", ":", "name", "=", "key", ...
[ 337, 4 ]
[ 344, 35 ]
python
en
['en', 'en', 'en']
True
Configuration.iter_config_files
(self)
Yields variant and configuration files associated with it. This should be treated like items of a dictionary.
Yields variant and configuration files associated with it.
def iter_config_files(self): # type: () -> Iterable[Tuple[Kind, List[str]]] """Yields variant and configuration files associated with it. This should be treated like items of a dictionary. """ # SMELL: Move the conditions out of this function # environment variables hav...
[ "def", "iter_config_files", "(", "self", ")", ":", "# type: () -> Iterable[Tuple[Kind, List[str]]]", "# SMELL: Move the conditions out of this function", "# environment variables have the lowest priority", "config_file", "=", "os", ".", "environ", ".", "get", "(", "'PIP_CONFIG_FILE...
[ 347, 4 ]
[ 376, 50 ]
python
en
['en', 'en', 'en']
True
Configuration.get_values_in_config
(self, variant)
Get values present in a config file
Get values present in a config file
def get_values_in_config(self, variant): # type: (Kind) -> Dict[str, Any] """Get values present in a config file""" return self._config[variant]
[ "def", "get_values_in_config", "(", "self", ",", "variant", ")", ":", "# type: (Kind) -> Dict[str, Any]", "return", "self", ".", "_config", "[", "variant", "]" ]
[ 378, 4 ]
[ 381, 36 ]
python
en
['en', 'en', 'en']
True
assertDsnEqual
(self, dsn1, dsn2, msg=None)
Check that two conninfo string have the same content
Check that two conninfo string have the same content
def assertDsnEqual(self, dsn1, dsn2, msg=None): """Check that two conninfo string have the same content""" self.assertEqual(set(dsn1.split()), set(dsn2.split()), msg)
[ "def", "assertDsnEqual", "(", "self", ",", "dsn1", ",", "dsn2", ",", "msg", "=", "None", ")", ":", "self", ".", "assertEqual", "(", "set", "(", "dsn1", ".", "split", "(", ")", ")", ",", "set", "(", "dsn2", ".", "split", "(", ")", ")", ",", "msg...
[ 78, 0 ]
[ 80, 63 ]
python
en
['en', 'en', 'en']
True
decorate_all_tests
(cls, *decorators)
Apply all the *decorators* to all the tests defined in the TestCase *cls*.
Apply all the *decorators* to all the tests defined in the TestCase *cls*.
def decorate_all_tests(cls, *decorators): """ Apply all the *decorators* to all the tests defined in the TestCase *cls*. """ for n in dir(cls): if n.startswith('test'): for d in decorators: setattr(cls, n, d(getattr(cls, n)))
[ "def", "decorate_all_tests", "(", "cls", ",", "*", "decorators", ")", ":", "for", "n", "in", "dir", "(", "cls", ")", ":", "if", "n", ".", "startswith", "(", "'test'", ")", ":", "for", "d", "in", "decorators", ":", "setattr", "(", "cls", ",", "n", ...
[ 191, 0 ]
[ 198, 51 ]
python
en
['en', 'error', 'th']
False
skip_if_no_uuid
(f)
Decorator to skip a test if uuid is not supported by Py/PG.
Decorator to skip a test if uuid is not supported by Py/PG.
def skip_if_no_uuid(f): """Decorator to skip a test if uuid is not supported by Py/PG.""" @wraps(f) def skip_if_no_uuid_(self): try: import uuid # noqa except ImportError: return self.skipTest("uuid not available in this Python version") try: ...
[ "def", "skip_if_no_uuid", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "skip_if_no_uuid_", "(", "self", ")", ":", "try", ":", "import", "uuid", "# noqa", "except", "ImportError", ":", "return", "self", ".", "skipTest", "(", "\"uuid not available...
[ 201, 0 ]
[ 222, 27 ]
python
en
['en', 'en', 'en']
True
skip_if_tpc_disabled
(f)
Skip a test if the server has tpc support disabled.
Skip a test if the server has tpc support disabled.
def skip_if_tpc_disabled(f): """Skip a test if the server has tpc support disabled.""" @wraps(f) def skip_if_tpc_disabled_(self): from psycopg2 import ProgrammingError cnn = self.connect() cur = cnn.cursor() try: cur.execute("SHOW max_prepared_transactions;") ...
[ "def", "skip_if_tpc_disabled", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "skip_if_tpc_disabled_", "(", "self", ")", ":", "from", "psycopg2", "import", "ProgrammingError", "cnn", "=", "self", ".", "connect", "(", ")", "cur", "=", "cnn", ".",...
[ 225, 0 ]
[ 247, 32 ]
python
en
['en', 'en', 'en']
True
skip_if_no_iobase
(f)
Skip a test if io.TextIOBase is not available.
Skip a test if io.TextIOBase is not available.
def skip_if_no_iobase(f): """Skip a test if io.TextIOBase is not available.""" @wraps(f) def skip_if_no_iobase_(self): try: from io import TextIOBase # noqa except ImportError: return self.skipTest("io.TextIOBase not found.") else: ...
[ "def", "skip_if_no_iobase", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "skip_if_no_iobase_", "(", "self", ")", ":", "try", ":", "from", "io", "import", "TextIOBase", "# noqa", "except", "ImportError", ":", "return", "self", ".", "skipTest", ...
[ 263, 0 ]
[ 274, 29 ]
python
en
['en', 'en', 'en']
True
skip_before_postgres
(*ver)
Skip a test on PostgreSQL before a certain version.
Skip a test on PostgreSQL before a certain version.
def skip_before_postgres(*ver): """Skip a test on PostgreSQL before a certain version.""" ver = ver + (0,) * (3 - len(ver)) def skip_before_postgres_(f): @wraps(f) def skip_before_postgres__(self): if self.conn.server_version < int("%d%02d%02d" % ver): return sel...
[ "def", "skip_before_postgres", "(", "*", "ver", ")", ":", "ver", "=", "ver", "+", "(", "0", ",", ")", "*", "(", "3", "-", "len", "(", "ver", ")", ")", "def", "skip_before_postgres_", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "skip...
[ 277, 0 ]
[ 291, 32 ]
python
en
['en', 'de', 'en']
True
skip_after_postgres
(*ver)
Skip a test on PostgreSQL after (including) a certain version.
Skip a test on PostgreSQL after (including) a certain version.
def skip_after_postgres(*ver): """Skip a test on PostgreSQL after (including) a certain version.""" ver = ver + (0,) * (3 - len(ver)) def skip_after_postgres_(f): @wraps(f) def skip_after_postgres__(self): if self.conn.server_version >= int("%d%02d%02d" % ver): r...
[ "def", "skip_after_postgres", "(", "*", "ver", ")", ":", "ver", "=", "ver", "+", "(", "0", ",", ")", "*", "(", "3", "-", "len", "(", "ver", ")", ")", "def", "skip_after_postgres_", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "skip_a...
[ 294, 0 ]
[ 308, 31 ]
python
en
['en', 'da', 'en']
True
skip_before_libpq
(*ver)
Skip a test if libpq we're linked to is older than a certain version.
Skip a test if libpq we're linked to is older than a certain version.
def skip_before_libpq(*ver): """Skip a test if libpq we're linked to is older than a certain version.""" ver = ver + (0,) * (3 - len(ver)) def skip_before_libpq_(f): @wraps(f) def skip_before_libpq__(self): v = libpq_version() if v < int("%d%02d%02d" % ver): ...
[ "def", "skip_before_libpq", "(", "*", "ver", ")", ":", "ver", "=", "ver", "+", "(", "0", ",", ")", "*", "(", "3", "-", "len", "(", "ver", ")", ")", "def", "skip_before_libpq_", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "skip_befor...
[ 319, 0 ]
[ 333, 29 ]
python
en
['en', 'en', 'en']
True
skip_after_libpq
(*ver)
Skip a test if libpq we're linked to is newer than a certain version.
Skip a test if libpq we're linked to is newer than a certain version.
def skip_after_libpq(*ver): """Skip a test if libpq we're linked to is newer than a certain version.""" ver = ver + (0,) * (3 - len(ver)) def skip_after_libpq_(f): @wraps(f) def skip_after_libpq__(self): v = libpq_version() if v >= int("%d%02d%02d" % ver): ...
[ "def", "skip_after_libpq", "(", "*", "ver", ")", ":", "ver", "=", "ver", "+", "(", "0", ",", ")", "*", "(", "3", "-", "len", "(", "ver", ")", ")", "def", "skip_after_libpq_", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "skip_after_l...
[ 336, 0 ]
[ 350, 28 ]
python
en
['en', 'en', 'en']
True
skip_before_python
(*ver)
Skip a test on Python before a certain version.
Skip a test on Python before a certain version.
def skip_before_python(*ver): """Skip a test on Python before a certain version.""" def skip_before_python_(f): @wraps(f) def skip_before_python__(self): if sys.version_info[:len(ver)] < ver: return self.skipTest("skipped because Python %s" % ".".j...
[ "def", "skip_before_python", "(", "*", "ver", ")", ":", "def", "skip_before_python_", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "skip_before_python__", "(", "self", ")", ":", "if", "sys", ".", "version_info", "[", ":", "len", "(", "ver", ...
[ 353, 0 ]
[ 365, 30 ]
python
en
['en', 'en', 'en']
True
skip_from_python
(*ver)
Skip a test on Python after (including) a certain version.
Skip a test on Python after (including) a certain version.
def skip_from_python(*ver): """Skip a test on Python after (including) a certain version.""" def skip_from_python_(f): @wraps(f) def skip_from_python__(self): if sys.version_info[:len(ver)] >= ver: return self.skipTest("skipped because Python %s" %...
[ "def", "skip_from_python", "(", "*", "ver", ")", ":", "def", "skip_from_python_", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "skip_from_python__", "(", "self", ")", ":", "if", "sys", ".", "version_info", "[", ":", "len", "(", "ver", ")",...
[ 368, 0 ]
[ 380, 28 ]
python
en
['en', 'en', 'en']
True
skip_if_no_superuser
(f)
Skip a test if the database user running the test is not a superuser
Skip a test if the database user running the test is not a superuser
def skip_if_no_superuser(f): """Skip a test if the database user running the test is not a superuser""" @wraps(f) def skip_if_no_superuser_(self): from psycopg2 import ProgrammingError try: return f(self) except ProgrammingError as e: import psycopg2.errorcode...
[ "def", "skip_if_no_superuser", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "skip_if_no_superuser_", "(", "self", ")", ":", "from", "psycopg2", "import", "ProgrammingError", "try", ":", "return", "f", "(", "self", ")", "except", "ProgrammingError"...
[ 383, 0 ]
[ 397, 32 ]
python
en
['en', 'en', 'en']
True
skip_if_windows
(f)
Skip a test if run on windows
Skip a test if run on windows
def skip_if_windows(f): """Skip a test if run on windows""" @wraps(f) def skip_if_windows_(self): if platform.system() == 'Windows': return self.skipTest("Not supported on Windows") else: return f(self) return skip_if_windows_
[ "def", "skip_if_windows", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "skip_if_windows_", "(", "self", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "'Windows'", ":", "return", "self", ".", "skipTest", "(", "\"Not supported on Wi...
[ 426, 0 ]
[ 434, 27 ]
python
en
['en', 'mt', 'en']
True
script_to_py3
(script)
Convert a script to Python3 syntax if required.
Convert a script to Python3 syntax if required.
def script_to_py3(script): """Convert a script to Python3 syntax if required.""" if sys.version_info[0] < 3: return script import tempfile f = tempfile.NamedTemporaryFile(suffix=".py", delete=False) f.write(script.encode()) f.flush() filename = f.name f.close() # 2to3 is wa...
[ "def", "script_to_py3", "(", "script", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", "<", "3", ":", "return", "script", "import", "tempfile", "f", "=", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "\".py\"", ",", "delete", "=",...
[ 437, 0 ]
[ 462, 27 ]
python
en
['en', 'en', 'en']
True
slow
(f)
Decorator to mark slow tests we may want to skip Note: in order to find slow tests you can run: make check 2>&1 | ts -i "%.s" | sort -n
Decorator to mark slow tests we may want to skip
def slow(f): """Decorator to mark slow tests we may want to skip Note: in order to find slow tests you can run: make check 2>&1 | ts -i "%.s" | sort -n """ @wraps(f) def slow_(self): if os.environ.get('PSYCOPG2_TEST_FAST'): return self.skipTest("slow test") return f...
[ "def", "slow", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "slow_", "(", "self", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "'PSYCOPG2_TEST_FAST'", ")", ":", "return", "self", ".", "skipTest", "(", "\"slow test\"", ")", "ret...
[ 475, 0 ]
[ 487, 16 ]
python
en
['en', 'en', 'en']
True
ConnectingTestCase.assertQuotedEqual
(self, first, second, msg=None)
Compare two quoted strings disregarding eventual E'' quotes
Compare two quoted strings disregarding eventual E'' quotes
def assertQuotedEqual(self, first, second, msg=None): """Compare two quoted strings disregarding eventual E'' quotes""" def f(s): if isinstance(s, str): return re.sub(r"\bE'", "'", s) elif isinstance(first, bytes): return re.sub(br"\bE'", b"'", s) ...
[ "def", "assertQuotedEqual", "(", "self", ",", "first", ",", "second", ",", "msg", "=", "None", ")", ":", "def", "f", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "str", ")", ":", "return", "re", ".", "sub", "(", "r\"\\bE'\"", ",", "\"'\...
[ 103, 4 ]
[ 113, 57 ]
python
en
['pt', 'en', 'en']
True