code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if isinstance(destination, six.string_types):
with open(destination, 'w', encoding='utf-8') as f:
self._rw.dump_config_to_file(self._config, f, with_defaults=with_defaults)
else:
self._rw.dump_config_to_file(self._config, destination, with_defaults=with_d... | def dump(self, destination, with_defaults=False) | Write configuration values to the specified destination.
Args:
destination:
with_defaults (bool): if ``True``, values of items with no custom values will be included in the output
if they have a default value set. | 2.133311 | 2.317404 | 0.920561 |
return self._rw.dump_config_to_string(self._config, with_defaults=with_defaults) | def dumps(self, with_defaults=False) | Generate a string representing all the configuration values.
Args:
with_defaults (bool): if ``True``, values of items with no custom values will be included in the output
if they have a default value set. | 7.382938 | 8.47162 | 0.871491 |
if is_config_item(subject):
self.add_item(name, subject)
elif is_config_section(subject):
self.add_section(name, subject)
else:
raise TypeError(
'Section items can only be replaced with items, '
'got {type}. To set item... | def _default_key_setter(self, name, subject) | This method is used only when there is a custom key_setter set.
Do not override this method. | 4.632666 | 5.081482 | 0.911676 |
if is_config_section(value):
self.add_section(key, value)
return
if key not in self._tree or self.settings.key_setter is None:
if is_config_item(value):
self.add_item(key, value)
return
raise TypeError(
... | def _set_key(self, key, value) | This method must NOT be called from outside the Section class.
Do not override this method. | 4.421598 | 4.281811 | 1.032647 |
resolution = self._get_item_or_section(key, handle_not_found=handle_not_found)
if self.settings.key_getter:
return self.settings.key_getter(parent=self, subject=resolution)
else:
return resolution | def _get_by_key(self, key, handle_not_found=True) | This method must NOT be called from outside the Section class.
Do not override this method. | 5.105816 | 5.106606 | 0.999845 |
if isinstance(key, six.string_types):
if self.settings.str_path_separator in key:
return self._get_item_or_section(key.split(self.settings.str_path_separator))
if key.endswith('_') and keyword.iskeyword(key[:-1]):
key = key[:-1]
if k... | def _get_item_or_section(self, key, handle_not_found=True) | This method must NOT be called from outside the Section class.
Do not override this method.
If handle_not_found is set to False, hooks won't be called.
This is needed when checking key existence -- the whole
purpose of key existence checking is to avoid errors (and error handling). | 2.20377 | 2.186987 | 1.007674 |
item = self._get_item_or_section(key)
if not item.is_item:
raise RuntimeError('{} is a section, not an item'.format(key))
return item | def get_item(self, *key) | The recommended way of retrieving an item by key when extending configmanager's behaviour.
Attribute and dictionary key access is configurable and may not always return items
(see PlainConfig for example), whereas this method will always return the corresponding
Item as long as NOT_FOUND hook ca... | 4.387893 | 5.437438 | 0.806978 |
section = self._get_item_or_section(key)
if not section.is_section:
raise RuntimeError('{} is an item, not a section'.format(key))
return section | def get_section(self, *key) | The recommended way of retrieving a section by key when extending configmanager's behaviour. | 4.390511 | 4.395088 | 0.998959 |
if not isinstance(alias, six.string_types):
raise TypeError('Item name must be a string, got a {!r}'.format(type(alias)))
item = copy.deepcopy(item)
if item.name is not_set:
item.name = alias
if self.settings.str_path_separator in item.name:
... | def add_item(self, alias, item) | Add a config item to this section. | 3.458596 | 3.249935 | 1.064205 |
if not isinstance(alias, six.string_types):
raise TypeError('Section name must be a string, got a {!r}'.format(type(alias)))
self._tree[alias] = section
if self.settings.str_path_separator in alias:
raise ValueError(
'Section alias must not cont... | def add_section(self, alias, section) | Add a sub-section to this section. | 5.108028 | 4.711031 | 1.08427 |
names_yielded = set()
for obj_alias, obj in self._tree.items():
if obj.is_section:
if obj.alias in names_yielded:
continue
names_yielded.add(obj.alias)
yield (obj.alias,), obj
if not recursive:
... | def _get_recursive_iterator(self, recursive=False) | Basic recursive iterator whose only purpose is to yield all items
and sections in order, with their full paths as keys.
Main challenge is to de-duplicate items and sections which
have aliases.
Do not add any new features to this iterator, instead
build others that extend this o... | 3.460893 | 3.118203 | 1.1099 |
if isinstance(key, six.string_types) or key is None:
if key in _iter_emitters:
emitter = _iter_emitters[key]
else:
raise ValueError('Invalid key {!r}'.format(key))
else:
emitter = lambda k, v, _, f=key: (f(k, v), v)
fo... | def iter_all(self, recursive=False, path=None, key='path') | Args:
recursive: if ``True``, recurse into sub-sections
path (tuple or string): optional path to limit iteration over.
key: ``path`` (default), ``str_path``, ``name``, ``None``, or a function to calculate the key from
``(k, v)`` tuple.
Returns:
... | 4.567039 | 4.048235 | 1.128156 |
for x in self.iter_all(recursive=recursive, path=path, key=key):
if key is None:
if x.is_section:
yield x
elif x[1].is_section:
yield x | def iter_sections(self, recursive=False, path=None, key='path') | See :meth:`.iter_all` for standard iterator argument descriptions.
Returns:
iterator: iterator over ``(key, section)`` pairs of all sections
in this section (and sub-sections if ``recursive=True``). | 3.679584 | 3.835903 | 0.959248 |
for _, item in self.iter_items(recursive=True):
item.reset() | def reset(self) | Recursively resets values of all items contained in this section
and its subsections to their default values. | 9.588188 | 7.221699 | 1.327691 |
for _, item in self.iter_items(recursive=True):
if not item.is_default:
return False
return True | def is_default(self) | ``True`` if values of all config items in this section and its subsections
have their values equal to defaults or have no value set. | 5.872756 | 5.467224 | 1.074175 |
values = dict_cls()
if flat:
for str_path, item in self.iter_items(recursive=True, key='str_path'):
if item.has_value:
if with_defaults or not item.is_default:
values[str_path] = item.value
else:
for it... | def dump_values(self, with_defaults=True, dict_cls=dict, flat=False) | Export values of all items contained in this section to a dictionary.
Items with no values set (and no defaults set if ``with_defaults=True``) will be excluded.
Returns:
dict: A dictionary of key-value pairs, where for sections values are dictionaries
of their contents. | 2.470925 | 2.48481 | 0.994412 |
if flat:
# Deflatten the dictionary and then pass on to the normal case.
separator = self.settings.str_path_separator
flat_dictionary = dictionary
dictionary = collections.OrderedDict()
for k, v in flat_dictionary.items():
k_pa... | def load_values(self, dictionary, as_defaults=False, flat=False) | Import config values from a dictionary.
When ``as_defaults`` is set to ``True``, the values
imported will be set as defaults. This can be used to
declare the sections and items of configuration.
Values of sections and items in ``dictionary`` can be
dictionaries as well as instan... | 2.924464 | 3.037018 | 0.962939 |
kwargs.setdefault('section', self)
return self.settings.section_factory(*args, **kwargs) | def create_section(self, *args, **kwargs) | Internal factory method used to create an instance of configuration section.
Should only be used when extending or modifying configmanager's functionality.
Under normal circumstances you should let configmanager create sections
and items when parsing configuration schemas.
Do not overr... | 6.565073 | 7.96285 | 0.824463 |
if not self.alias:
return ()
if self.section:
return self.section.get_path() + (self.alias,)
else:
return self.alias, | def get_path(self) | Calculate section's path in configuration tree.
Use this sparingly -- path is calculated by going up the configuration tree.
For a large number of sections, it is more efficient to use iterators that return paths
as keys.
Path value is stable only once the configuration tree is complete... | 5.409112 | 4.373207 | 1.236876 |
def decorator(func):
attr_name = name or func.__name__
if attr_name.startswith('_'):
raise RuntimeError('Invalid dynamic item attribute name -- should not start with an underscore')
self.__item_attributes[attr_name] = func
return func
... | def item_attribute(self, f=None, name=None) | A decorator to register a dynamic item attribute provider.
By default, uses function name for attribute name. Override that with ``name=``. | 3.260915 | 3.016027 | 1.081195 |
if name in self.__item_attributes:
return self.__item_attributes[name](item)
elif self.section:
return self.section.get_item_attribute(item, name)
else:
raise AttributeError(name) | def get_item_attribute(self, item, name) | Method called by item when an attribute is not found. | 2.622795 | 2.551876 | 1.027791 |
if self.settings.hooks_enabled:
result = self.hooks.dispatch_event(event_, **kwargs)
if result is not None:
return result
# Must also dispatch the event in parent section
if self.section:
return self.section.dispatch_event... | def dispatch_event(self, event_, **kwargs) | Dispatch section event.
Notes:
You MUST NOT call event.trigger() directly because
it will circumvent the section settings as well
as ignore the section tree.
If hooks are disabled somewhere up in the tree, and enabled
down below, events will still be... | 4.959603 | 4.37955 | 1.132446 |
if self._configparser_adapter is None:
self._configparser_adapter = ConfigPersistenceAdapter(
config=self,
reader_writer=ConfigParserReaderWriter(
config_parser_factory=self.settings.configparser_factory,
),
)
... | def configparser(self) | Adapter to dump/load INI format strings and files using standard library's
``ConfigParser`` (or the backported configparser module in Python 2).
Returns:
ConfigPersistenceAdapter | 5.589987 | 4.565653 | 1.224356 |
if self._json_adapter is None:
self._json_adapter = ConfigPersistenceAdapter(
config=self,
reader_writer=JsonReaderWriter(),
)
return self._json_adapter | def json(self) | Adapter to dump/load JSON format strings and files.
Returns:
ConfigPersistenceAdapter | 6.859921 | 4.695167 | 1.46106 |
if self._yaml_adapter is None:
self._yaml_adapter = ConfigPersistenceAdapter(
config=self,
reader_writer=YamlReaderWriter(),
)
return self._yaml_adapter | def yaml(self) | Adapter to dump/load YAML format strings and files.
Returns:
ConfigPersistenceAdapter | 6.709298 | 4.689507 | 1.430705 |
if self._click_extension is None:
from .click_ext import ClickExtension
self._click_extension = ClickExtension(
config=self
)
return self._click_extension | def click(self) | click extension
Returns:
ClickExtension | 5.564376 | 4.172267 | 1.333658 |
# Must reverse because we want the sources assigned to higher-up Config instances
# to overrides sources assigned to lower Config instances.
for section in reversed(list(self.iter_sections(recursive=True, key=None))):
if section.is_config:
section.load()
... | def load(self) | Load user configuration based on settings. | 10.552631 | 10.179241 | 1.036682 |
args, kwargs = _config_parameter(args, kwargs)
return self._click.option(*args, **kwargs) | def option(self, *args, **kwargs) | Registers a click.option which falls back to a configmanager Item
if user hasn't provided a value in the command line.
Item must be the last of ``args``.
Examples::
config = Config({'greeting': 'Hello'})
@click.command()
@config.click.option('--greeting', ... | 8.491962 | 8.319504 | 1.020729 |
if kwargs.get('required', True):
raise TypeError(
'In click framework, arguments are mandatory, unless marked required=False. '
'Attempt to use configmanager as a fallback provider suggests that this is an optional option, '
'not a mandatory ... | def argument(self, *args, **kwargs) | Registers a click.argument which falls back to a configmanager Item
if user hasn't provided a value in the command line.
Item must be the last of ``args``. | 13.588892 | 10.055964 | 1.351327 |
at_name = '@{}'.format(name)
if name in kwargs:
if at_name in kwargs:
raise ValueError('Both {!r} and {!r} specified in kwargs'.format(name, at_name))
return kwargs[name]
if at_name in kwargs:
return kwargs[at_name]
return n... | def _get_kwarg(self, name, kwargs) | Helper to get value of a named attribute irrespective of whether it is passed
with or without "@" prefix. | 3.082606 | 2.802347 | 1.100009 |
envvar_name = None
if self.envvar is True:
envvar_name = self.envvar_name
if envvar_name is None:
envvar_name = '_'.join(self.get_path()).upper()
elif self.envvar:
envvar_name = self.envvar
if envvar_name and envvar_name in o... | def _get_envvar_value(self) | Internal helper to get item value from an environment variable
if item is controlled by one, and if the variable is set.
Returns not_set otherwise. | 2.705666 | 2.559029 | 1.057302 |
envvar_value = self._get_envvar_value()
if envvar_value is not not_set:
return envvar_value
if self.has_value:
if self._value is not not_set:
return self._value
else:
return copy.deepcopy(self.default)
elif fa... | def get(self, fallback=not_set) | Returns config value.
See Also:
:meth:`.set` and :attr:`.value` | 3.174508 | 3.190577 | 0.994964 |
old_value = self._value
old_raw_str_value = self.raw_str_value
self.type.set_item_value(self, value)
new_value = self._value
if old_value is not_set and new_value is not_set:
# Nothing to report
return
if self.section:
self... | def set(self, value) | Sets config value. | 3.056722 | 3.01038 | 1.015394 |
old_value = self._value
old_raw_str_value = self.raw_str_value
self._value = not_set
self.raw_str_value = not_set
new_value = self._value
if old_value is not_set:
# Nothing to report
return
if self.section:
self.sec... | def reset(self) | Resets the value of config item to its default value. | 3.017964 | 2.744636 | 1.099587 |
envvar_value = self._get_envvar_value()
if envvar_value is not not_set:
return envvar_value == self.default
else:
return self._value is not_set or self._value == self.default | def is_default(self) | ``True`` if the item's value is its default value or if no value and no default value are set.
If the item is backed by an environment variable, this will be ``True`` only
if the environment variable is set and is different to the
default value of the item. | 3.756361 | 3.404493 | 1.103354 |
if self._get_envvar_value() is not not_set:
return True
else:
return self.default is not not_set or self._value is not not_set | def has_value(self) | ``True`` if item has a default value or custom value set. | 6.423547 | 5.356299 | 1.199251 |
if self.section:
return self.section.get_path() + (self.name,)
else:
return self.name, | def get_path(self) | Calculate item's path in configuration tree.
Use this sparingly -- path is calculated by going up the configuration tree.
For a large number of items, it is more efficient to use iterators that return paths
as keys.
Path value is stable only once the configuration tree is completely ini... | 4.406723 | 4.545712 | 0.969424 |
if self.required and not self.has_value:
raise RequiredValueMissing(name=self.name, item=self) | def validate(self) | Validate item. | 6.281875 | 4.392702 | 1.430071 |
if isinstance(type_, six.string_types):
for t in self.all_types:
if type_ in t.aliases:
return t
raise ValueError('Failed to recognise type by name {!r}'.format(type_))
for t in self.all_types:
if type_ in t.builtin_types:... | def translate(self, type_) | Given a built-in, an otherwise known type, or a name of known type, return its corresponding wrapper type::
>>> Types.translate(int)
<_IntType ('int', 'integer')>
>>> Types.translate('string')
<_StrType ('str', 'string', 'unicode')> | 3.627084 | 4.150348 | 0.873923 |
template = 'filebrowser.html'
upload_form = FileUploadForm()
uploaded_file = None
upload_tab_active = False
is_images_dialog = (file_type == 'img')
is_documents_dialog = (file_type == 'doc')
files = FileBrowserFile.objects.filter(file_type=file_type)
if request.POST:
... | def filebrowser(request, file_type) | Trigger view for filebrowser | 2.129513 | 2.122991 | 1.003072 |
fobj = get_object_or_404(FileBrowserFile, file_type=file_type, id=item_id)
fobj.delete()
if file_type == 'doc':
return HttpResponseRedirect(reverse('mce-filebrowser-documents'))
return HttpResponseRedirect(reverse('mce-filebrowser-images')) | def filebrowser_remove_file(request, item_id, file_type) | Remove file | 2.885434 | 2.989764 | 0.965104 |
if not hasattr(self, '_available_domains'):
url = 'http://{0}/request/domains/format/json/'.format(
self.api_domain)
req = requests.get(url)
domains = req.json()
setattr(self, '_available_domains', domains)
return self._available_d... | def available_domains(self) | Return list of available domains for use in email address. | 3.532403 | 3.244445 | 1.088754 |
chars = string.ascii_lowercase
if digits:
chars += string.digits
length = random.randint(min_length, max_length)
return ''.join(random.choice(chars) for x in range(length)) | def generate_login(self, min_length=6, max_length=10, digits=True) | Generate string for email address login with defined length and
alphabet.
:param min_length: (optional) min login length.
Default value is ``6``.
:param max_length: (optional) max login length.
Default value is ``10``.
:param digits: (optional) use digits in login genera... | 1.961491 | 2.290991 | 0.856176 |
if self.login is None:
self.login = self.generate_login()
available_domains = self.available_domains
if self.domain is None:
self.domain = random.choice(available_domains)
elif self.domain not in available_domains:
raise ValueError('Domain no... | def get_email_address(self) | Return full email address from login and domain from params in class
initialization or generate new. | 3.320587 | 2.725738 | 1.218234 |
if email is None:
email = self.get_email_address()
if email_hash is None:
email_hash = self.get_hash(email)
url = 'http://{0}/request/mail/id/{1}/format/json/'.format(
self.api_domain, email_hash)
req = requests.get(url)
return req.js... | def get_mailbox(self, email=None, email_hash=None) | Return list of emails in given email address
or dict with `error` key if mail box is empty.
:param email: (optional) email address.
:param email_hash: (optional) md5 hash from email address. | 3.136386 | 3.362447 | 0.932769 |
'''
Connect
Setup a socket connection to the specified telegram-cli socket
--
@return None
'''
if self.connection_type.lower() == 'tcp':
self.connection = sockets.setup_tcp_socket(self.location, self.port)
elif self.connect... | def _connect(self) | Connect
Setup a socket connection to the specified telegram-cli socket
--
@return None | 5.939244 | 3.113077 | 1.907837 |
'''
Send
Send a payload to a telegram-cli socket.
--
@param payload:str The Payload to send over a socket connection.
@return bool
'''
if not self.connection:
self._connect()
# Send the payload, adding a ne... | def _send(self, payload) | Send
Send a payload to a telegram-cli socket.
--
@param payload:str The Payload to send over a socket connection.
@return bool | 5.724662 | 3.630219 | 1.576947 |
'''
Setup Domain Socket
Setup a connection to a Unix Domain Socket
--
@param location:str The path to the Unix Domain Socket to connect to.
@return <class 'socket._socketobject'>
'''
clientsocket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
clientso... | def setup_domain_socket(location) | Setup Domain Socket
Setup a connection to a Unix Domain Socket
--
@param location:str The path to the Unix Domain Socket to connect to.
@return <class 'socket._socketobject'> | 3.882277 | 1.84863 | 2.100084 |
'''
Setup TCP Socket
Setup a connection to a TCP Socket
--
@param location:str The Hostname / IP Address of the remote TCP Socket.
@param port:int The TCP Port the remote Socket is listening on.
@return <class 'socket._socketobject'>
'''
client... | def setup_tcp_socket(location, port) | Setup TCP Socket
Setup a connection to a TCP Socket
--
@param location:str The Hostname / IP Address of the remote TCP Socket.
@param port:int The TCP Port the remote Socket is listening on.
@return <class 'socket._socketobject'> | 3.352362 | 1.627865 | 2.059361 |
zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"}
primary_zone_info = {"forceImport": True, "createType": "NEW"}
zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info}
return self.rest_api_connection.post("/v1/zone... | def create_primary_zone(self, account_name, zone_name) | Creates a new primary zone.
Arguments:
account_name -- The name of the account that will contain this zone.
zone_name -- The name of the zone. It must be unique. | 4.319673 | 4.785666 | 0.902627 |
zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"}
primary_zone_info = {"forceImport": True, "createType": "UPLOAD"}
zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info}
files = {'zone': ('', json.dumps(zone_data)... | def create_primary_zone_by_upload(self, account_name, zone_name, bind_file) | Creates a new primary zone by uploading a bind file
Arguments:
account_name -- The name of the account that will contain this zone.
zone_name -- The name of the zone. It must be unique.
bind_file -- The file to upload. | 3.442011 | 3.887996 | 0.885292 |
zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"}
if tsig_key is not None and key_value is not None:
name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value}
else:
name_server_info = {"ip": master}
... | def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None) | Creates a new primary zone by zone transferring off a master.
Arguments:
account_name -- The name of the account that will contain this zone.
zone_name -- The name of the zone. It must be unique.
master -- Primary name server IP address.
Keyword Arguments:
tsig_key -- ... | 2.98712 | 3.199037 | 0.933756 |
zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"}
if tsig_key is not None and key_value is not None:
name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value}
else:
name_server_info = {"ip": master}
... | def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None) | Creates a new secondary zone.
Arguments:
account_name -- The name of the account.
zone_name -- The name of the zone.
master -- Primary name server IP address.
Keyword Arguments:
tsig_key -- For TSIG-enabled zones: The transaction signature key.
NOTE:... | 2.670798 | 2.73998 | 0.974751 |
uri = "/v1/accounts/" + account_name + "/zones"
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) | def get_zones_of_account(self, account_name, q=None, **kwargs) | Returns a list of zones for the specified account.
Arguments:
account_name -- The name of the account.
Keyword Arguments:
q -- The search parameters, in a dict. Valid keys are:
name - substring match of the zone name
zone_type - one of:
PRIMAR... | 4.520092 | 6.305421 | 0.716858 |
uri = "/v1/zones"
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) | def get_zones(self, q=None, **kwargs) | Returns a list of zones across all of the user's accounts.
Keyword Arguments:
q -- The search parameters, in a dict. Valid keys are:
name - substring match of the zone name
zone_type - one of:
PRIMARY
SECONDARY
ALIAS
sor... | 6.580202 | 9.228004 | 0.713069 |
name_server_info = {}
if primary is not None:
name_server_info['nameServerIp1'] = {'ip':primary}
if backup is not None:
name_server_info['nameServerIp2'] = {'ip':backup}
if second_backup is not None:
name_server_info['nameServerIp3'] = {'ip':s... | def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None) | Edit the axfr name servers of a secondary zone.
Arguments:
zone_name -- The name of the secondary zone being edited.
primary -- The primary name server value.
Keyword Arguments:
backup -- The backup name server if any.
second_backup -- The second backup name server. | 2.416595 | 2.671841 | 0.904468 |
uri = "/v1/zones/" + zone_name + "/rrsets"
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) | def get_rrsets(self, zone_name, q=None, **kwargs) | Returns the list of RRSets in the specified zone.
Arguments:
zone_name -- The name of the zone.
Keyword Arguments:
q -- The search parameters, in a dict. Valid keys are:
ttl - must match the TTL for the rrset
owner - substring match of the owner name
... | 4.478746 | 6.097012 | 0.734581 |
uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) | def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs) | Returns the list of RRSets in the specified zone of the specified type.
Arguments:
zone_name -- The name of the zone.
rtype -- The type of the RRSets. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
Keyword Argument... | 4.115648 | 5.419434 | 0.759424 |
uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) | def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs) | Returns the list of RRSets in the specified zone of the specified type.
Arguments:
zone_name -- The name of the zone.
rtype -- The type of the RRSets. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
owner_name -- The... | 3.461228 | 4.598605 | 0.752669 |
if type(rdata) is not list:
rdata = [rdata]
rrset = {"ttl": ttl, "rdata": rdata}
return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) | def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata) | Creates a new RRSet in the specified zone.
Arguments:
zone_name -- The zone that will contain the new RRSet. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
... | 2.989094 | 3.380888 | 0.884115 |
if type(rdata) is not list:
rdata = [rdata]
rrset = {"ttl": ttl, "rdata": rdata}
if profile:
rrset["profile"] = profile
uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name
return self.rest_api_connection.put(uri, json.dumps(rrse... | def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None) | Updates an existing RRSet in the specified zone.
Arguments:
zone_name -- The zone that contains the RRSet. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
... | 2.52312 | 3.00255 | 0.840326 |
if type(rdata) is not list:
rdata = [rdata]
rrset = {"rdata": rdata}
method = "patch"
if profile:
rrset["profile"] = profile
method = "put"
uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name
return getattr(s... | def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None) | Updates an existing RRSet's Rdata in the specified zone.
Arguments:
zone_name -- The zone that contains the RRSet. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead... | 3.055426 | 3.582191 | 0.852949 |
return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) | def delete_rrset(self, zone_name, rtype, owner_name) | Deletes an RRSet.
Arguments:
zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
owner_name -- The ... | 3.687521 | 4.625913 | 0.797144 |
web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type}
return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) | def create_web_forward(self, zone_name, request_to, redirect_to, forward_type) | Create a web forward record.
Arguments:
zone_name -- The zone in which the web forward is to be created.
request_to -- The URL to be redirected. You may use http:// and ftp://.
forward_type -- The type of forward. Valid options include:
Framed
... | 3.220998 | 4.412402 | 0.729987 |
rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl)
return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) | def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list) | Creates a new SB Pool.
Arguments:
zone_name -- The zone that contains the RRSet. The trailing dot is optional.
owner_name -- The owner name for the RRSet.
If no trailing dot is supplied, the owner_name is assumed to be relative (foo).
If a trailing d... | 3.991264 | 4.344781 | 0.918634 |
rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl)
return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) | def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list) | Updates an existing SB Pool in the specified zone.
:param zone_name: The zone that contains the RRSet. The trailing dot is optional.
:param owner_name: The owner name for the RRSet.
If no trailing dot is supplied, the owner_name is assumed to be relative (foo).
... | 3.943176 | 4.12521 | 0.955873 |
rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl)
return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) | def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record) | Creates a new TC Pool.
Arguments:
zone_name -- The zone that contains the RRSet. The trailing dot is optional.
owner_name -- The owner name for the RRSet.
If no trailing dot is supplied, the owner_name is assumed to be relative (foo).
If a trailing d... | 4.447572 | 4.762313 | 0.93391 |
rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl)
return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) | def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record) | Updates an existing TC Pool in the specified zone.
:param zone_name: The zone that contains the RRSet. The trailing dot is optional.
:param owner_name: The owner name for the RRSet.
If no trailing dot is supplied, the owner_name is assumed to be relative (foo).
... | 4.26317 | 4.448152 | 0.958414 |
path = str(path)
if path.endswith('.gz'):
with gzip.open(path, mode='wt', encoding=encoding) as f:
return dump(obj, f)
else:
with open(path, mode='wt', encoding=encoding) as f:
dump(obj, f) | def dumpf(obj, path, encoding=None) | Serialize obj to path in ARPA format (.arpa, .gz). | 2.014289 | 1.965257 | 1.024949 |
if not model:
model = 'simple'
if not parser:
parser = 'quick'
if model not in ['simple']:
raise ValueError
if parser not in ['quick']:
raise ValueError
if model == 'simple' and parser == 'quick':
return ARPAParserQuick(ARPAModelSimple).parse(fp)
el... | def load(fp, model=None, parser=None) | Deserialize fp (a file-like object) to a Python object. | 4.437087 | 4.491998 | 0.987776 |
path = str(path)
if path.endswith('.gz'):
with gzip.open(path, mode='rt', encoding=encoding) as f:
return load(f, model=model, parser=parser)
else:
with open(path, mode='rt', encoding=encoding) as f:
return load(f, model=model, parser=parser) | def loadf(path, encoding=None, model=None, parser=None) | Deserialize path (.arpa, .gz) to a Python object. | 1.632009 | 1.596618 | 1.022166 |
with StringIO(s) as f:
return load(f, model=model, parser=parser) | def loads(s, model=None, parser=None) | Deserialize s (a str) to a Python object. | 3.290882 | 3.466141 | 0.949437 |
'''
Send Message
Sends a message to a Telegram Recipient.
From telegram-cli:
msg <peer> <text> Sends text message to peer
--
@param recipient:str The telegram recipient the message is intended
... | def send_message(self, recipient, message) | Send Message
Sends a message to a Telegram Recipient.
From telegram-cli:
msg <peer> <text> Sends text message to peer
--
@param recipient:str The telegram recipient the message is intended
for. Can be either a... | 6.89523 | 2.132088 | 3.234027 |
'''
Send Image
Sends a an image to a Telegram Recipient. The image needs
to be readable to the telegram-cli instance where the
socket is created.
From telegram-cli:
send_photo <peer> <file> Sends photo to peer
--
... | def send_image(self, recipient, path) | Send Image
Sends a an image to a Telegram Recipient. The image needs
to be readable to the telegram-cli instance where the
socket is created.
From telegram-cli:
send_photo <peer> <file> Sends photo to peer
--
@param recipi... | 8.261127 | 1.816507 | 4.547809 |
if other == FullSpace:
return False
else:
for ls in self.local_factors:
if isinstance(ls.label, StrLabel):
return False
for ls in other.local_factors:
if isinstance(ls.label, StrLabel):
r... | def isdisjoint(self, other) | Check whether two Hilbert spaces are disjoint (do not have any
common local factors). Note that `FullSpace` is *not* disjoint with any
other Hilbert space, while `TrivialSpace` *is* disjoint with any other
HilbertSpace (even itself) | 3.681952 | 2.94758 | 1.249144 |
if not isinstance(label_or_index, cls._basis_label_types):
raise TypeError(
"label_or_index must be an instance of one of %s; not %s" % (
", ".join([t.__name__ for t in cls._basis_label_types]),
label_or_index.__class__.__name__)) | def _check_basis_label_type(cls, label_or_index) | Every object (BasisKet, LocalSigma) that contains a label or index
for an eigenstate of some LocalSpace should call this routine to check
the type of that label or index (or, use
:meth:`_unpack_basis_label_or_index` | 2.168587 | 2.536352 | 0.855002 |
self._check_basis_label_type(label_or_index)
if isinstance(label_or_index, str):
label = label_or_index
try:
ind = self.basis_labels.index(label)
# the above line may also raise BasisNotSetError, which we
# don't want to ca... | def _unpack_basis_label_or_index(self, label_or_index) | return tuple (label, ind) from `label_or_index`
If `label_or_int` is a :class:`.SymbolicLabelBase` sub-instance, it
will be stored in the `label` attribute, and the `ind` attribute will
return the value of the label's :attr:`.FockIndex.fock_index`
attribute. No checks are performed for... | 2.673786 | 2.185676 | 1.223322 |
from qnet.algebra.core.state_algebra import BasisKet # avoid circ. import
for label in self.basis_labels:
yield BasisKet(label, hs=self) | def basis_states(self) | Yield an iterator over the states (:class:`.BasisKet` instances)
that form the canonical basis of the Hilbert space
Raises:
.BasisNotSetError: if the Hilbert space has no defined basis | 8.638841 | 7.786636 | 1.109444 |
from qnet.algebra.core.state_algebra import BasisKet # avoid circ. import
try:
return BasisKet(index_or_label, hs=self)
except ValueError as exc_info:
if isinstance(index_or_label, int):
raise IndexError(str(exc_info))
else:
... | def basis_state(self, index_or_label) | Return the basis state with the given index or label.
Raises:
.BasisNotSetError: if the Hilbert space has no defined basis
IndexError: if there is no basis state with the given index
KeyError: if there is not basis state with the given label | 4.044044 | 4.17872 | 0.967771 |
if isinstance(label_or_index, int):
new_index = label_or_index + n
if new_index < 0:
raise IndexError("index %d < 0" % new_index)
if self.has_basis:
if new_index >= self.dimension:
raise IndexError("index %d out of ... | def next_basis_label_or_index(self, label_or_index, n=1) | Given the label or index of a basis state, return the label/index of
the next basis state.
More generally, if `n` is given, return the `n`'th next basis state
label/index; `n` may also be negative to obtain previous basis state
labels/indices.
The return type is the same as the... | 1.989888 | 1.905792 | 1.044127 |
from qnet.algebra.core.state_algebra import BasisKet, TensorKet
# importing locally avoids circular import
ls_bases = [ls.basis_labels for ls in self.local_factors]
for label_tuple in cartesian_product(*ls_bases):
yield TensorKet(
*[BasisKet(label, hs... | def basis_states(self) | Yield an iterator over the states (:class:`.TensorKet` instances)
that form the canonical basis of the Hilbert space
Raises:
.BasisNotSetError: if the Hilbert space has no defined basis | 7.308219 | 7.000923 | 1.043894 |
from qnet.algebra.core.state_algebra import BasisKet, TensorKet
if isinstance(index_or_label, int): # index
ls_bases = [ls.basis_labels for ls in self.local_factors]
label_tuple = list(cartesian_product(*ls_bases))[index_or_label]
try:
return... | def basis_state(self, index_or_label) | Return the basis state with the given index or label.
Raises:
.BasisNotSetError: if the Hilbert space has no defined basis
IndexError: if there is no basis state with the given index
KeyError: if there is not basis state with the given label | 3.109686 | 3.133768 | 0.992315 |
if other is FullSpace:
return TrivialSpace
if other is TrivialSpace:
return self
if isinstance(other, ProductSpace):
oops = set(other.operands)
else:
oops = {other}
return ProductSpace.create(
*sorted(set(se... | def remove(self, other) | Remove a particular factor from a tensor product space. | 4.90156 | 4.138687 | 1.184327 |
if other is FullSpace:
return self
if other is TrivialSpace:
return TrivialSpace
if isinstance(other, ProductSpace):
other_ops = set(other.operands)
else:
other_ops = {other}
return ProductSpace.create(
*sor... | def intersect(self, other) | Find the mutual tensor factors of two Hilbert spaces. | 3.922012 | 3.715648 | 1.055539 |
identifier = self._hs._local_identifiers.get(
self.__class__.__name__, self._hs._local_identifiers.get(
'Create', self._identifier))
if not self._rx_identifier.match(identifier):
raise ValueError(
"identifier '%s' does not match pattern '%... | def identifier(self) | The identifier (symbol) that is used when printing the annihilation
operator. This is identical to the identifier of :class:`Create`. A
custom identifier for both :class:`Destroy` and :class:`Create` can be
set through the `local_identifiers` parameter of the associated Hilbert
space::
... | 4.542749 | 3.609168 | 1.258669 |
for cls in type(expr).__mro__:
if cls.__name__ == classname:
return True
return False | def _isinstance(expr, classname) | Check whether `expr` is an instance of the class with name
`classname`
This is like the builtin `isinstance`, but it take the `classname` a
string, instead of the class directly. Useful for when we don't want to
import the class for which we want to check (also, remember that
pr... | 2.755133 | 3.492811 | 0.788801 |
# The reason method this is separated out from `doprint` is that
# printers that use identation, e.g. IndentedSReprPrinter, need to
# override how caching is handled, applying variable indentation even
# for cached results
try:
is_cached = expr in self.cache
... | def _get_from_cache(self, expr) | Get the result of :meth:`doprint` from the internal cache | 11.657165 | 10.130786 | 1.150667 |
adjoint = kwargs.get('adjoint', False)
if adjoint:
expr = expr.conjugate()
if isinstance(expr, SympyBasic):
self._sympy_printer._print_level = self._print_level + 1
res = self._sympy_printer.doprint(expr)
else: # numeric type
try:... | def _print_SCALAR_TYPES(self, expr, *args, **kwargs) | Render scalars | 4.065485 | 4.018332 | 1.011734 |
allow_caching = self._allow_caching
is_cached = False
if len(args) > 0 or len(kwargs) > 0:
# we don't want to cache "custom" rendering, such as the adjoint of
# the actual expression (kwargs['adjoint'] is True). Otherwise, we
# might return a cached v... | def doprint(self, expr, *args, **kwargs) | Returns printer's representation for expr (as a string)
The representation is obtained by the following methods:
1. from the :attr:`cache`
2. If `expr` is a Sympy object, delegate to the
:meth:`~sympy.printing.printer.Printer.doprint` method of
:attr:`_sympy_printer`
... | 6.218782 | 6.137594 | 1.013228 |
r'''Given a :class:`.LocalSpace` `ls` to take the partial trace over and an
operator `op`, factor the trace such that operators acting on disjoint
degrees of freedom are pulled out of the trace. If the operator acts
trivially on ls the trace yields only a pre-factor equal to the dimension
of ls. If ... | def factor_for_trace(ls: HilbertSpace, op: Operator) -> Operator | r'''Given a :class:`.LocalSpace` `ls` to take the partial trace over and an
operator `op`, factor the trace such that operators acting on disjoint
degrees of freedom are pulled out of the trace. If the operator acts
trivially on ls the trace yields only a pre-factor equal to the dimension
of ls. If ther... | 5.425573 | 2.176936 | 2.492297 |
return OperatorTrace.create(
OperatorTrace.create(A, over_space=H.operands[-1]),
over_space=ProductSpace.create(*H.operands[:-1])) | def decompose_space(H, A) | Simplifies OperatorTrace expressions over tensor-product spaces by
turning it into iterated partial traces.
Args:
H (ProductSpace): The full space.
A (Operator):
Returns:
Operator: Iterative partial trace expression | 12.9908 | 10.146256 | 1.280354 |
if expand:
expr = expr.expand()
ret = defaultdict(int)
operands = expr.operands if isinstance(expr, OperatorPlus) else [expr]
for e in operands:
c, t = _coeff_term(e)
try:
if abs(complex(c)) < epsilon:
continue
except TypeError:
... | def get_coeffs(expr, expand=False, epsilon=0.) | Create a dictionary with all Operator terms of the expression
(understood as a sum) as keys and their coefficients as values.
The returned object is a defaultdict that return 0. if a term/key
doesn't exist.
Args:
expr: The operator expression to get all coefficients from.
expand: Wheth... | 4.134037 | 4.216616 | 0.980416 |
coeffs, nops = zip(*map(_coeff_term, ops))
coeff = 1
for c in coeffs:
coeff *= c
if coeff == 1:
return nops, coeffs
else:
return coeff * cls.create(*nops, **kwargs) | def factor_coeff(cls, ops, kwargs) | Factor out coefficients of all factors. | 5.187166 | 5.634328 | 0.920636 |
# TODO: move this to the toolbox
from qnet.algebra.toolbox.core import temporary_rules
def _combine_operator_p_cc(A, B):
if B.adjoint() == A:
return OperatorPlusMinusCC(A, sign=+1)
else:
raise CannotSimplify
def _combine_operator_m_cc(A, B):
if B.ad... | def rewrite_with_operator_pm_cc(expr) | Try to rewrite expr using :class:`OperatorPlusMinusCC`
Example:
>>> A = OperatorSymbol('A', hs=1)
>>> sum = A + A.dag()
>>> sum2 = rewrite_with_operator_pm_cc(sum)
>>> print(ascii(sum2))
A^(1) + c.c. | 3.299336 | 3.322723 | 0.992961 |
from qnet.algebra.core.state_algebra import KetBra
# KetBra is imported locally to avoid circular imports
if basis_states is None:
basis_states = list(self.space.basis_states)
else:
basis_states = list(basis_states)
diag_terms = []
terms =... | def expand_in_basis(self, basis_states=None, hermitian=False) | Write the operator as an expansion into all
:class:`KetBras <.KetBra>`
spanned by `basis_states`.
Args:
basis_states (list or None): List of basis states (:class:`.State`
instances) into which to expand the operator. If None, use the
operator's `space... | 3.01248 | 2.681856 | 1.123282 |
return super().doit(classes, recursive, **kwargs) | def doit(self, classes=None, recursive=True, **kwargs) | Write out commutator
Write out the commutator according to its definition
$[\Op{A}, \Op{B}] = \Op{A}\Op{B} - \Op{A}\Op{B}$.
See :meth:`.Expression.doit`. | 4.666437 | 6.050922 | 0.771194 |
return delimiter.join(('"%s"="%s"' % item) for item in sorted(d.items())) | def _attrprint(d, delimiter=', ') | Print a dictionary of attributes in the DOT format | 4.805996 | 4.596556 | 1.045565 |
style = dict()
for expr_filter, sty in styles:
if expr_filter(expr):
style.update(sty)
return style | def _styleof(expr, styles) | Merge style dictionaries in order | 4.919792 | 5.0783 | 0.968787 |
def _labelfunc(expr, is_leaf):
if is_leaf:
label = leaf_renderer(expr)
elif isinstance(expr, Expression):
if len(expr.kwargs) == 0:
label = expr.__class__.__name__
else:
label = "%s(..., %s)" % (
expr.__cla... | def expr_labelfunc(leaf_renderer=str, fallback=str) | Factory for function ``labelfunc(expr, is_leaf)``
It has the following behavior:
* If ``is_leaf`` is True, return ``leaf_renderer(expr)``.
* Otherwise,
- if `expr` is an Expression, return a custom string similar to
:func:`~qnet.printing.srepr`, but with an ellipsis for ``args``
- ot... | 2.418448 | 2.149381 | 1.125184 |
import subprocess
import os
def _minimal_ext_cmd(cmd):
# construct minimal environment
env = {}
for k in ['SYSTEMROOT', 'PATH']:
v = os.environ.get(k)
if v is not None:
env[k] = v
# LANGUAGE is used on win32
env['LANGUAGE... | def _git_version() | If installed with 'pip installe -e .' from inside a git repo, the
current git revision as a string | 1.588806 | 1.512653 | 1.050344 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.