Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
14,000 | def process_exception_message(exception):
exception_message = str(exception)
for replace_char in [, , ]:
exception_message = exception_message.replace(replace_char, if replace_char != else )
return exception_message.replace(, ) | Process an exception message.
Args:
exception: The exception to process.
Returns:
A filtered string summarizing the exception. |
14,001 | def endStep(self,key):
ptime = _ptime()
if key is not None:
self.steps[key][] = ptime
self.steps[key][] = ptime[1] - self.steps[key][][1]
self.end = ptime
print(,key,,ptime[0])
print() | Record the end time for the step.
If key==None, simply record ptime as end time for class to represent
the overall runtime since the initialization of the class. |
14,002 | def change_email(*_, user_id=None, new_email=None):
click.echo(green())
click.echo(green( * 40))
with get_app().app_context():
user = find_user(dict(id=user_id))
if not user:
click.echo(red())
return
user.email = new_email
result = user_service.... | Change email for a user |
14,003 | def create_widget(self):
d = self.declaration
self.widget = TabLayout(self.get_context(), None, d.style) | Create the underlying widget. |
14,004 | def getStatus(self) :
if self.status == CONST.COLLECTION_LOADING_STATUS :
return "loading"
elif self.status == CONST.COLLECTION_LOADED_STATUS :
return "loaded"
elif self.status == CONST.COLLECTION_DELETED_STATUS :
return "deleted"
elif self.st... | returns a word describing the status of the collection (loaded, loading, deleted, unloaded, newborn) instead of a number, if you prefer the number it's in self.status |
14,005 | def async_save_result(self):
if hasattr(self, "_async_future") and self._async_future.done():
self._async_future.result()
return True
else:
return False | Retrieves the result of this subject's asynchronous save.
- Returns `True` if the subject was saved successfully.
- Raises `concurrent.futures.CancelledError` if the save was cancelled.
- If the save failed, raises the relevant exception.
- Returns `False` if the subject hasn't finished... |
14,006 | def extra_create_kwargs(self):
user = self.get_agnocomplete_context()
if user:
_, domain = user.email.split()
return {
: domain
}
return {} | Inject the domain of the current user in the new model instances. |
14,007 | def _request(self, service, **kw):
fb_request = {
: service,
}
for key in [, , , ]:
fb_request[key] = kw.pop(key, None)
if kw:
raise _exc.FastbillRequestError("Unknown arguments: %s" %
", ".join(kw.... | Do the actual request to Fastbill's API server.
If successful returns the RESPONSE section the of response, in
case of an error raises a subclass of FastbillError. |
14,008 | def create(gandi, resource, domain, duration, owner, admin, tech, bill,
nameserver, extra_parameter, background):
if domain:
gandi.echo(
)
gandi.echo("You should use instead." % domain)
if (domain and resource) and (domain != resource):
gandi.echo(
... | Buy a domain. |
14,009 | def headerHTML(header,fname):
html="<html><body><code>"
html+="<h2>%s</h2>"%(fname)
html+=pprint.pformat(header, indent=1)
html=html.replace("\n",).replace(" "," ")
html=html.replace(r"\x00","")
html+="</code></body></html>"
print("saving header file... | given the bytestring ABF header, make and launch HTML. |
14,010 | def parse_args(spectypes):
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument(
"-c", "--constants",
help="emit constants instead of spec dict",
action="store_true"
)
arg_parser.add_argument(
"spectype",
help="specifies the spec type to be generate... | Return arguments object formed by parsing the command line used to launch
the program. |
14,011 | def import_domaindump():
parser = argparse.ArgumentParser(
description="Imports users, groups and computers result files from the ldapdomaindump tool, will resolve the names from domain_computers output for IPs")
parser.add_argument("files", nargs=,
help="The domaindump file... | Parses ldapdomaindump files and stores hosts and users in elasticsearch. |
14,012 | def _tile(self, n):
pos = self._trans(self.pos[n])
return Tile(pos, pos).pad(self.support_pad) | Get the update tile surrounding particle `n` |
14,013 | def perform_command(self):
if len(self.actual_arguments) < 1:
return self.print_help(short=True)
for cls, switches in self.TOOLS:
if self.has_option(switches):
arguments = [a for a in sys.argv if a not in switches]
retur... | Perform command and return the appropriate exit code.
:rtype: int |
14,014 | def _query_zendesk(self, endpoint, object_type, *endpoint_args, **endpoint_kwargs):
_id = endpoint_kwargs.get(, None)
if _id:
item = self.cache.get(object_type, _id)
if item:
return item
else:
return self._get(url=self._build_... | Query Zendesk for items. If an id or list of ids are passed, attempt to locate these items
in the relevant cache. If they cannot be found, or no ids are passed, execute a call to Zendesk
to retrieve the items.
:param endpoint: target endpoint.
:param object_type: object type we are ex... |
14,015 | def propagate_defaults(config_doc):
for group_name, group_doc in config_doc.items():
if isinstance(group_doc, dict):
defaults = group_doc.get(, {})
for item_name, item_doc in group_doc.items():
if item_name == :
continue
if is... | Propagate default values to sections of the doc. |
14,016 | def server(self):
try:
tar = urllib2.urlopen(self.registry)
meta = tar.info()
return int(meta.getheaders("Content-Length")[0])
except (urllib2.URLError, IndexError):
return " " | Returns the size of remote files |
14,017 | def menucheck(self, window_name, object_name):
menu_handle = self._get_menu_handle(window_name, object_name)
if not menu_handle.AXEnabled:
raise LdtpServerException(u"Object %s state disabled" % object_name)
try:
if menu_handle.AXMenuItemMarkChar:
... | Check (click) a menu item.
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, either full name,
LDTP's name convention, or a Unix glob. Or menu heirarchy
... |
14,018 | def makeAsn(segID,N, CA, C, O, geo):
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle=geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_CG_length=geo.CB_CG_length
CA_CB_CG_angle=geo.CA_CB_CG_angle
N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle
CG_OD1_length=geo.CG_OD1_le... | Creates an Asparagine residue |
14,019 | def get_ad_via_hitid(hit_id):
username = CONFIG.get(, )
password = CONFIG.get(, )
try:
req = requests.get( + hit_id,
auth=(username, password))
except:
raise ExperimentError()
else:
if req.status_code == 200:
return req.json()[]
... | Get ad via HIT id |
14,020 | def user_remove(name,
database=None,
user=None,
password=None,
host=None,
port=None):
***
if not user_exists(name, database, user, password, host, port):
if database:
log.info(%s\%s\, name, database)
else... | Remove a cluster admin or a database user.
If a database is specified: it will remove the database user.
If a database is not specified: it will remove the cluster admin.
name
User name to remove
database
The database to remove the user from
user
User name for the new use... |
14,021 | def _parse_reserved_marker(self, fptr):
the_id = .format(self._marker_id)
segment = Segment(marker_id=the_id, offset=self._offset, length=0)
return segment | Marker range between 0xff30 and 0xff39. |
14,022 | def step_undefined_step_snippets_should_not_exist_for_table(context):
assert context.table, "REQUIRES: table"
for row in context.table.rows:
step = row["Step"]
step_undefined_step_snippet_should_not_exist_for(context, step) | Checks if undefined-step snippets are not provided.
EXAMPLE:
Then undefined-step snippets should not exist for:
| Step |
| When an known step is used |
| Then another known step is used | |
14,023 | def _format_regular_value(self, str_in):
try:
value = int(str_in, base=10)
return str(value)
except ValueError as e:
msg = "Invalid integer. Read .".format(str_in)
e_new = InvalidEntryError(msg)
e_new.field_spec = self
... | we need to reformat integer strings, as there can be different
strings for the same integer. The
strategy of unification here is to first parse the integer
string to an Integer type. Thus all of
'+13', ' 13', '13' will be parsed to 13. We then convert the
integer ... |
14,024 | def matches(self, name):
return ((self.match.search(name)
or (self.include and
filter(None,
[inc.search(name) for inc in self.include])))
and ((not self.exclude)
or not filter(None,
... | Does the name match my requirements?
To match, a name must match config.testMatch OR config.include
and it must not match config.exclude |
14,025 | def restart(name, timeout=90, with_deps=False, with_parents=False):
*
if in name:
create_win_salt_restart_task()
return execute_salt_restart_task()
ret = set()
ret.add(stop(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents))
ret.add(start(name=name, timeout... | Restart the named service. This issues a stop command followed by a start.
Args:
name: The name of the service to restart.
.. note::
If the name passed is ``salt-minion`` a scheduled task is
created and executed to restart the salt-minion service.
timeo... |
14,026 | def reset(self):
self.activeCells = np.empty(0, dtype="uint32")
self.activeDeltaSegments = np.empty(0, dtype="uint32")
self.activeFeatureLocationSegments = np.empty(0, dtype="uint32") | Deactivate all cells. |
14,027 | def get_commands_from(self, args):
commands = []
for i in itertools.count(0):
try:
commands.append(getattr(args, self.arg_label_fmt % i))
except AttributeError:
break
return commands | We have to code the key names for each depth. This method scans
for each level and returns a list of the command arguments. |
14,028 | def create_df_file_with_query(self, query, output):
chunk_size = 100000
offset = 0
data = defaultdict(lambda : defaultdict(list))
with open(output, ) as outfile:
query = query.replace(, )
query +=
while True:
print(offset)
... | Dumps in df in chunks to avoid crashes. |
14,029 | def _do_identity_role_list(args):
rest_client = RestClient(args.url)
state = rest_client.list_state(subtree=IDENTITY_NAMESPACE + _ROLE_PREFIX)
head = state[]
state_values = state[]
printable_roles = []
for state_value in state_values:
role_list = RoleList()
decoded = b64dec... | Lists the current on-chain configuration values. |
14,030 | def numdiff(fun, args):
epsilon = 1e-8
args = list(args)
v0 = fun(*args)
N = v0.shape[0]
l_v = len(v0)
dvs = []
for i, a in enumerate(args):
l_a = (a).shape[1]
dv = numpy.zeros((N, l_v, l_a))
nargs = list(args)
for j in range(l_a):
xx... | Vectorized numerical differentiation |
14,031 | def locations(self, exists=True):
result = []
for config_files in self.config_paths:
if not config_files:
continue
if os.path.isdir(config_files):
config_files = [os.path.join(config_files, i)
for i in sorte... | Return the location of the config file(s).
A given directory will be scanned for ``*.conf`` files, in alphabetical order.
Any duplicates will be eliminated.
If ``exists`` is True, only existing configuration locations are returned. |
14,032 | def get_videos_for_ids(
edx_video_ids,
sort_field=None,
sort_dir=SortDirection.asc
):
videos, __ = _get_videos_for_filter(
{"edx_video_id__in":edx_video_ids},
sort_field,
sort_dir,
)
return videos | Returns an iterator of videos that match the given list of ids.
Args:
edx_video_ids (list)
sort_field (VideoSortField)
sort_dir (SortDirection)
Returns:
A generator expression that contains the videos found, sorted by the
given field and direction, with ties broken by e... |
14,033 | def getmembers(obj, *predicates):
if not predicates or predicates[0] is not None:
predicates = (lambda key, value: not key.startswith(),) + predicates
def predicate(key_value_tuple):
key, value = key_value_tuple
for p in predicates:
if p is not None and not p(k... | Return all the members of an object as a list of `(key, value)` tuples, sorted by name.
The optional list of predicates can be used to filter the members.
The default predicate drops members whose name starts with '_'. To disable it, pass `None` as the first predicate.
:param obj: Object to list the memb... |
14,034 | def quote_single_identifier(self, string):
c = self.get_identifier_quote_character()
return "%s%s%s" % (c, string.replace(c, c + c), c) | Quotes a single identifier (no dot chain separation).
:param string: The identifier name to be quoted.
:type string: str
:return: The quoted identifier string.
:rtype: str |
14,035 | def run(self, command):
boto.log.debug( % (command, self.server.instance_id))
status = 0
try:
t = self._ssh_client.exec_command(command)
except paramiko.SSHException:
status = 1
std_out = t[1].read()
std_err = t[2].read()
t[0].clos... | Execute a command on the remote host. Return a tuple containing
an integer status and a two strings, the first containing stdout
and the second containing stderr from the command. |
14,036 | def attach_network_interface(device_index, name=None, network_interface_id=None,
instance_name=None, instance_id=None,
region=None, key=None, keyid=None, profile=None):
if not salt.utils.data.exactly_one((name, network_interface_id)):
raise Salt... | Attach an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.attach_network_interface my_eni instance_name=salt-master device_index=0 |
14,037 | def get(self, *args, **kwargs):
if args:
kwargs = {: str(args[0])}
key, value = kwargs.popitem()
for item in self:
if in key and getattr(item, key, None) == value:
return item
for vlan in item.interfaces:
if getattr(vl... | Get the sub interfaces for this VlanInterface
>>> itf = engine.interface.get(3)
>>> list(itf.vlan_interface)
[Layer3PhysicalInterfaceVlan(name=VLAN 3.3), Layer3PhysicalInterfaceVlan(name=VLAN 3.5),
Layer3PhysicalInterfaceVlan(name=VLAN 3.4)]
:par... |
14,038 | def flatten(repertoire, big_endian=False):
if repertoire is None:
return None
order = if big_endian else
return repertoire.squeeze().ravel(order=order) | Flatten a repertoire, removing empty dimensions.
By default, the flattened repertoire is returned in little-endian order.
Args:
repertoire (np.ndarray or None): A repertoire.
Keyword Args:
big_endian (boolean): If ``True``, flatten the repertoire in big-endian
order.
Retu... |
14,039 | def _init_rgb(self, r: int, g: int, b: int) -> None:
if self.rgb_mode:
self.rgb = (r, g, b)
self.hexval = rgb2hex(r, g, b)
else:
self.rgb = hex2rgb(rgb2termhex(r, g, b))
self.hexval = rgb2termhex(r, g, b)
self.code = hex2term(self.hexval) | Initialize from red, green, blue args. |
14,040 | def save(self, filename=None):
content = self.data.yaml()
with open(Config.path_expand(ConfigDict.filename), ) as f:
f.write(content) | saves the configuration in the given filename,
if it is none the filename at load time is used.
:param filename: the file name
:type filename: string
:return: |
14,041 | def delete_invalid_route(self):
try:
routing = self._engine.routing.get(self.interface_id)
for route in routing:
if route.invalid or route.to_delete:
route.delete()
except InterfaceNotFound:
pass | Delete any invalid routes for this interface. An invalid route is
a left over when an interface is changed to a different network.
:return: None |
14,042 | def chgrp(path, group):
primary groupprimary group*
func_name = .format(__virtualname__)
if __opts__.get(, ) == func_name:
log.info(
, func_name)
log.debug(, func_name, path)
return None | Change the group of a file
Under Windows, this will do nothing.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on permissions unless intentionally
configured and is only used to support Unix compatibility features (e.g.
Services For Unix, N... |
14,043 | def getrawpart(self, msgid, stream=sys.stdout):
for hdr, part in self._get(msgid):
pl = part.get_payload(decode=True)
if pl != None:
print(pl, file=stream)
break | Get the first part from the message and print it raw. |
14,044 | def stop(self):
self._running.clear()
with self._lock:
if self._timer:
self._timer.cancel()
self._timer = None | Stop the Heartbeat Checker.
:return: |
14,045 | def on(self):
isOK = True
try:
if self.channelR!=None:
sub.call(["gpio", "-g", "mode", "{}".format(self.channelR), self.PIN_MODE_AUDIO ])
except:
isOK = False
print("Open audio right channel failed.")
try:
if self.... | !
\~english
Open Audio output. set pin mode to ALT0
@return a boolean value. if True means open audio output is OK otherwise failed to open.
\~chinese
打开音频输出。 将引脚模式设置为ALT0
@return 布尔值。 如果 True 表示打开音频输出成功,否则不成功。 |
14,046 | def records(self):
if self._records is None:
self._records = RecordList(self._version, account_sid=self._solution[], )
return self._records | Access the records
:returns: twilio.rest.api.v2010.account.usage.record.RecordList
:rtype: twilio.rest.api.v2010.account.usage.record.RecordList |
14,047 | def _estimate_AICc(self, y, mu, weights=None):
edof = self.statistics_[]
if self.statistics_[] is None:
self.statistics_[] = self._estimate_AIC(y, mu, weights)
return self.statistics_[] + 2*(edof + 1)*(edof + 2)/(y.shape[0] - edof -2) | estimate the corrected Akaike Information Criterion
relies on the estimated degrees of freedom, which must be computed
before.
Parameters
----------
y : array-like of shape (n_samples,)
output data vector
mu : array-like of shape (n_samples,)
exp... |
14,048 | def serial(self, may_block=True):
if not self.capabilities.have_serial_number():
raise yubikey_base.YubiKeyVersionError("Serial number unsupported in YubiKey %s" % self.version() )
return self._read_serial(may_block) | Get the YubiKey serial number (requires YubiKey 2.2). |
14,049 | def width(self, level):
return self.x_at_y(level, reverse=True) - self.x_at_y(level) | Width at given level
:param level:
:return: |
14,050 | def split_signature(klass, signature):
if signature == :
return []
if not signature.startswith():
return [signature]
result = []
head =
tail = signature[1:-1]
while tail:
c = tail[0]
head += c
tail ... | Return a list of the element signatures of the topmost signature tuple.
If the signature is not a tuple, it returns one element with the entire
signature. If the signature is an empty tuple, the result is [].
This is useful for e. g. iterating over method parameters which are
passed as... |
14,051 | def lm_deltat(freqs, damping_times, modes):
dt = {}
for lmn in modes:
l, m, nmodes = int(lmn[0]), int(lmn[1]), int(lmn[2])
for n in range(nmodes):
dt[ %(l,m,n)] = 1. / qnm_freq_decay(freqs[ %(l,m,n)],
damping_times[ %(l,m,n)], 1./1000)
... | Return the minimum delta_t of all the modes given, with delta_t given by
the inverse of the frequency at which the amplitude of the ringdown falls to
1/1000 of the peak amplitude. |
14,052 | def clone(self, **kwargs):
parent = self.parent()
return self._client._create_clone(parent, self, **kwargs) | Clone a part.
.. versionadded:: 2.3
:param kwargs: (optional) additional keyword=value arguments
:type kwargs: dict
:return: cloned :class:`models.Part`
:raises APIError: if the `Part` could not be cloned
Example
-------
>>> bike = client.model('Bike')
... |
14,053 | def register_event(self, event_type, pattern, handler):
if event_type not in self._supported_events:
raise ValueError("Unsupported event type {}".format(event_type))
if event_type != "CHANGE" and not isinstance(pattern, Pattern) and not isinstance(pattern, basestring):
r... | When ``event_type`` is observed for ``pattern``, triggers ``handler``.
For "CHANGE" events, ``pattern`` should be a tuple of ``min_changed_pixels`` and
the base screen state. |
14,054 | def add_relationship(self, rel_uri, obj):
if isinstance(rel_uri, URIRef):
rel_uri = force_text(rel_uri)
obj_is_literal = True
if isinstance(obj, DigitalObject):
obj = obj.uri
obj_is_literal = False
elif (isinstance(obj, str) or isinstance(obj... | Add a new relationship to the RELS-EXT for this object.
Calls :meth:`API_M.addRelationship`.
Example usage::
isMemberOfCollection = 'info:fedora/fedora-system:def/relations-external#isMemberOfCollection'
collection_uri = 'info:fedora/foo:456'
object.add_relationship... |
14,055 | def observed_data_to_xarray(self):
posterior_model = self.posterior_model
if self.dims is None:
dims = {}
else:
dims = self.dims
observed_names = self.observed_data
if isinstance(observed_names, str):
observed_names = [observe... | Convert observed data to xarray. |
14,056 | def init(self, context):
self.cache = Cache()
self.current_page_context = context
self.current_request = context.get(, None) if context else None
self.current_lang = get_language()
self._current_app_is_admin = None
self._current_user_permissions = _UNSET
... | Initializes sitetree to handle new request.
:param Context|None context: |
14,057 | def _Close(self):
self._vslvm_volume_group = None
self._vslvm_handle.close()
self._vslvm_handle = None
self._file_object.close()
self._file_object = None | Closes the file system object.
Raises:
IOError: if the close failed. |
14,058 | def init(options=None, ini_paths=None, argv=None,
strict=False, **parser_kwargs):
global SINGLETON
SINGLETON = Config(
options=options,
ini_paths=ini_paths,
argv=argv,
**parser_kwargs)
SINGLETON.parse(argv, strict=strict)
return SINGLETON | Initialize singleton config and read/parse configuration.
:keyword bool strict: when true, will error out on invalid arguments
(default behavior is to ignore them)
:returns: the loaded configuration. |
14,059 | def preview_email_marketing_campaign(self, email_marketing_campaign):
url = self.api.join(.join([
self.EMAIL_MARKETING_CAMPAIGN_URL,
str(email_marketing_campaign.constant_contact_id),
]))
response = url.get()
self.handle_response_status(response)
... | Returns HTML and text previews of an EmailMarketingCampaign. |
14,060 | def get (self, key, def_val=None):
assert isinstance(key, basestring)
return dict.get(self, key.lower(), def_val) | Return lowercase key value. |
14,061 | def dump(result):
if isinstance(result, dict):
statuses = result[]
else:
statuses = result
status_str_list = []
for status in statuses:
status_str_list.append(textwrap.dedent(u).strip().format(
screen_... | Dump result into a string, useful for debugging. |
14,062 | def setup(docker_mount=None, force=False):
if not is_ubuntu() and not is_boot2docker():
raise Exception()
if os.path.exists() and not fabric.contrib.files.exists():
put(, )
if not fabric.contrib.files.exists():
fab.run()
if docker_is_installed() and not force:
... | Prepare a vanilla server by installing docker, curl, and sshpass. If a file called ``dot_dockercfg``
exists in the current working directory, it is uploaded as ``~/.dockercfg``.
Args:
* docker_mount=None: Partition that will be mounted as /var/lib/docker |
14,063 | def new_dxworkflow(title=None, summary=None, description=None, output_folder=None, init_from=None, **kwargs):
dxworkflow = DXWorkflow()
dxworkflow.new(title=title, summary=summary, description=description, output_folder=output_folder, init_from=init_from, **kwargs)
return dxworkflow | :param title: Workflow title (optional)
:type title: string
:param summary: Workflow summary (optional)
:type summary: string
:param description: Workflow description (optional)
:type description: string
:param output_folder: Default output folder of the workflow (optional)
:type output_fold... |
14,064 | def telnet_config(self, status):
ret = self.command(
.format(
status)
)
return ret.content.decode() | status:
false - Telnet is disabled
true - Telnet is enabled |
14,065 | def incr(self, name, amount=1):
amount = get_integer(, amount)
return self.execute_command(, name, amount) | Increase the value at key ``name`` by ``amount``. If no key exists, the value
will be initialized as ``amount`` .
Like **Redis.INCR**
:param string name: the key name
:param int amount: increments
:return: the integer value at key ``name``
:rtype: int
>>> ssdb.... |
14,066 | def ping(dest_ip=None, **kwargs):
device_name8.8.8.8device_name8.8.8.8
conn = __proxy__[]()
ret = {}
if dest_ip is None:
ret[] =
ret[] = False
return ret
op = {: dest_ip}
if in kwargs:
if kwargs[]:
if isinstance(kwargs[][-1], dict):
... | Send a ping RPC to a device
dest_ip
The IP of the device to ping
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
rapid : False
When ``True``, executes ping at 100pps instead of 1pps
ttl
Maximum number of IP routers (IP hops) allowed between source and
dest... |
14,067 | def from_custom_template(cls, searchpath, name):
loader = ChoiceLoader([
FileSystemLoader(searchpath),
cls.loader,
])
class MyStyler(cls):
env = Environment(loader=loader)
template = env.get_template(name)
return MyStyler | Factory function for creating a subclass of ``Styler``
with a custom template and Jinja environment.
Parameters
----------
searchpath : str or list
Path or paths of directories containing the templates
name : str
Name of your custom template to use for re... |
14,068 | def load(self, config_data):
if not isinstance(config_data, dict):
raise ConfigurationError(
"Configuration data is %s instead of dict." % (
type(config_data),
)
)
self.load_addon_packages(config_data)
self.loa... | Loads sanitizers according to rulesets defined in given already parsed
configuration file.
:param config_data: Already parsed configuration data, as dictionary.
:type config_data: dict[str,any] |
14,069 | def next(self):
if not self._filestream:
if not self._zip:
self._zip = zipfile.ZipFile(self._reader(self._blob_key))
self._entries = self._zip.infolist()[self._start_file_index:
self._end_file_index]
self._entries.reverse()
... | Returns the next line from this input reader as (lineinfo, line) tuple.
Returns:
The next input from this input reader, in the form of a 2-tuple.
The first element of the tuple describes the source, it is itself
a tuple (blobkey, filenumber, byteoffset).
The second element of the tuple is... |
14,070 | def read_ttl(path):
~/data/myfilemyfile~/data/
warnings.warn("Document.read_ttl() is deprecated and will be removed in near future. Use read() instead", DeprecationWarning)
doc_path = os.path.dirname(path)
doc_name = os.path.basename(path)
return Document(doc_name, doc_path).read... | Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt)
E.g. Document.read_ttl('~/data/myfile') is the same as Document('myfile', '~/data/').read() |
14,071 | def create(self, fname, lname, group, type, group_api):
self.__username(fname, lname)
self.client.add(
self.__distinguished_name(type, fname=fname, lname=lname),
API.__object_class(),
self.__ldap_attr(fname, lname, type, group, group_api)) | Create an LDAP User. |
14,072 | def get_environ(self, sock):
cipher = sock.cipher()
ssl_environ = {
"wsgi.url_scheme": "https",
"HTTPS": "on",
: cipher[1],
: cipher[0]
}
return ssl_environ | Create WSGI environ entries to be merged into each request. |
14,073 | def process_results(self):
for result in self._results:
provider = result.provider
self.providers.append(provider)
if result.error:
self.failed_providers.append(provider)
continue
if not result.response:
con... | Process results by providers |
14,074 | def lpc(blk, order=None):
phi = lag_matrix(blk, order)
order = len(phi) - 1
def inner(a, b):
return sum(phi[i][j] * ai * bj
for i, ai in enumerate(a.numlist)
for j, bj in enumerate(b.numlist)
)
A = ZFilter(1)
B = [z ** -1]
beta = [inner(B[0], B[0])]... | Find the Linear Predictive Coding (LPC) coefficients as a ZFilter object,
the analysis whitening filter. This implementation is based on the
covariance method, assuming a zero-mean stochastic process, finding
the coefficients iteratively and greedily like the lattice implementation
in Levinson-Durbin algorithm,... |
14,075 | def transpose(self):
kraus_l, kraus_r = self._data
kraus_l = [k.T for k in kraus_l]
if kraus_r is not None:
kraus_r = [k.T for k in kraus_r]
return Kraus((kraus_l, kraus_r),
input_dims=self.output_dims(),
output_dims=self.inp... | Return the transpose of the QuantumChannel. |
14,076 | def arc(pRA, pDecl, sRA, sDecl, mcRA, lat):
pDArc, pNArc = utils.dnarcs(pDecl, lat)
sDArc, sNArc = utils.dnarcs(sDecl, lat)
mdRA = mcRA
sArc = sDArc
pArc = pDArc
if not utils.isAboveHorizon(sRA, sDecl, mcRA, lat):
mdRA = angle.norm(mcRA + 180)
sArc = ... | Returns the arc of direction between a Promissor
and Significator. It uses the generic proportional
semi-arc method. |
14,077 | def put(self, request, bot_id, id, format=None):
return super(MessengerBotDetail, self).put(request, bot_id, id, format) | Update existing MessengerBot
---
serializer: MessengerBotUpdateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request |
14,078 | def editText(self, y, x, w, record=True, **kwargs):
v = self.callHook() if record else None
if not v or v[0] is None:
with EnableCursor():
v = editText(self.scr, y, x, w, **kwargs)
else:
v = v[0]
if kwargs.get(, True):
status(... | Wrap global editText with `preedit` and `postedit` hooks. |
14,079 | def DragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None:
PressMouse(x1, y1, 0.05)
MoveTo(x2, y2, moveSpeed, 0.05)
ReleaseMouse(waitTime) | Simulate mouse left button drag from point x1, y1 drop to point x2, y2.
x1: int.
y1: int.
x2: int.
y2: int.
moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster.
waitTime: float. |
14,080 | def ordered_storage(config, name=None):
typedictredisredisenvREDIS_HOSTNAMEdefaultlocalhost
tp = config[]
if tp == :
return DictListStorage(config)
if tp == :
return RedisListStorage(config, name=name) | Return ordered storage system based on the specified config.
The canonical example of such a storage container is
``defaultdict(list)``. Thus, the return value of this method contains
keys and values. The values are ordered lists with the last added
item at the end.
Args:
config (dict): De... |
14,081 | def compact(self):
self.docFactory = webtheme.getLoader(self.compactFragmentName)
for param in self.parameters:
param.compact() | Switch to the compact variant of the live form template.
By default, this will simply create a loader for the
C{self.compactFragmentName} template and compact all of this form's
parameters. |
14,082 | def get_memory_info(self):
rss, vms = _psutil_osx.get_process_memory_info(self.pid)[:2]
return nt_meminfo(rss, vms) | Return a tuple with the process' RSS and VMS size. |
14,083 | def delete(self, name):
if name in self._cache:
del self._cache[name]
self.writeCache()
return True
return False | Deletes the named entry in the cache.
:param name: the name.
:return: true if it is deleted. |
14,084 | def update(self, portfolio, date, perfs=None):
self.portfolio = portfolio
self.perfs = perfs
self.date = date | Actualizes the portfolio universe with the alog state |
14,085 | def remove_item(self, item_id, assessment_part_id):
if (not isinstance(assessment_part_id, ABCId) and
assessment_part_id.get_identifier_namespace() != ):
raise errors.InvalidArgument()
assessment_part_map, collection = self._get_assessment_part_collection(assessment_... | Removes an ``Item`` from an ``AssessmentPartId``.
arg: item_id (osid.id.Id): ``Id`` of the ``Item``
arg: assessment_part_id (osid.id.Id): ``Id`` of the
``AssessmentPartId``
raise: NotFound - ``item_id`` ``not found in
assessment_part_id``
raise: ... |
14,086 | def endpoint_from_model_data(self, model_s3_location, deployment_image, initial_instance_count, instance_type,
name=None, role=None, wait=True, model_environment_vars=None, model_vpc_config=None,
accelerator_type=None):
model_environmen... | Create and deploy to an ``Endpoint`` using existing model data stored in S3.
Args:
model_s3_location (str): S3 URI of the model artifacts to use for the endpoint.
deployment_image (str): The Docker image which defines the runtime code to be used as
the entry point for ac... |
14,087 | def check_slice_perms(self, slice_id):
form_data, slc = get_form_data(slice_id, use_slice_data=True)
datasource_type = slc.datasource.type
datasource_id = slc.datasource.id
viz_obj = get_viz(
datasource_type=datasource_type,
datasource_id=datasource_id,
form_data=form_data,
... | Check if user can access a cached response from slice_json.
This function takes `self` since it must have the same signature as the
the decorated method. |
14,088 | def expand_config(d, dirs):
context = {
: dirs.user_cache_dir,
: dirs.user_config_dir,
: dirs.user_data_dir,
: dirs.user_log_dir,
: dirs.site_config_dir,
: dirs.site_data_dir,
}
for k, v in d.items():
if isinstance(v, dict):
expand_co... | Expand configuration XDG variables, environmental variables, and tildes.
Parameters
----------
d : dict
config information
dirs : appdirs.AppDirs
XDG application mapping
Notes
-----
*Environmentable variables* are expanded via :py:func:`os.path.expandvars`.
So ``${PWD}`... |
14,089 | def next_token(self, tok, include_extra=False):
i = tok.index + 1
if not include_extra:
while is_non_coding_token(self._tokens[i].type):
i += 1
return self._tokens[i] | Returns the next token after the given one. If include_extra is True, includes non-coding
tokens from the tokenize module, such as NL and COMMENT. |
14,090 | def write_int8(self, value, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.pack( % endian, value) | Pack the value as a signed byte and write 1 byte to the stream.
Args:
value:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: the number of bytes written. |
14,091 | def rewrite_elife_authors_json(json_content, doi):
article_doi = elifetools.utils.convert_testing_doi(doi)
if article_doi == "10.7554/eLife.06956":
for i, ref in enumerate(json_content):
if ref.get("orcid") and ref.get("orcid") == "0000-0001-6798-0064":
json_... | this does the work of rewriting elife authors json |
14,092 | def remove_server_data(server_id):
logger.debug("Removing server from serverdata")
data = datatools.get_data()
if server_id in data["discord"]["servers"]:
data["discord"]["servers"].pop(server_id)
datatools.write_data(data) | Remove a server from the server data
Args:
server_id (int): The server to remove from the server data |
14,093 | def force_invalidate(self, vts):
for vt in vts.versioned_targets:
self._invalidator.force_invalidate(vt.cache_key)
vt.valid = False
self._invalidator.force_invalidate(vts.cache_key)
vts.valid = False | Force invalidation of a VersionedTargetSet. |
14,094 | def cmd_link(self, args):
if len(args) < 1:
self.show_link()
elif args[0] == "list":
self.cmd_link_list()
elif args[0] == "add":
if len(args) != 2:
print("Usage: link add LINK")
return
self.cmd_link_add(args... | handle link commands |
14,095 | def name_variants(self):
out = []
variant = namedtuple(, )
for var in chained_get(self._json, [, ], []):
new = variant(name=var[], doc_count=var.get())
out.append(new)
return out | A list of namedtuples representing variants of the affiliation name
with number of documents referring to this variant. |
14,096 | def assign_taxonomy(dataPath, reference_sequences_fp, id_to_taxonomy_fp, read_1_seqs_fp, read_2_seqs_fp, single_ok=False, no_single_ok_generic=False,
header_id_regex=None, read_id_regex = "\S+\s+(\S+)", amplicon_id_regex = "(\S+)\s+(\S+?)\/",
output_fp=None, log_path=None, HALT_E... | Assign taxonomy to each sequence in data with the RTAX classifier
# data: open fasta file object or list of fasta lines
dataPath: path to a fasta file
output_fp: path to write output; if not provided, result will be
returned in a dict of {seq_id:(taxonomy_assignment,confidence)} |
14,097 | def wait_time(departure, now=None):
now = now or datetime.datetime.now()
yn, mn, dn = now.year, now.month, now.day
hour, minute = map(int, departure.split())
dt = datetime.datetime(yn, mn, dn, hour=hour, minute=minute)
delta = (dt - now).seconds
if (dt - now).days < 0:
delta = 0
... | Calculate waiting time until the next departure time in 'HH:MM' format.
Return time-delta (as 'MM:SS') from now until next departure time in the
future ('HH:MM') given as (year, month, day, hour, minute, seconds).
Time-deltas shorter than 60 seconds are reduced to 0. |
14,098 | def _write_cvvr(self, f, data):
f.seek(0, 2)
byte_loc = f.tell()
cSize = len(data)
block_size = CDF.CVVR_BASE_SIZE64 + cSize
section_type = CDF.CVVR_
rfuA = 0
cvvr1 = bytearray(24)
cvvr1[0:8] = struct.pack(, block_size)
cvvr1[8:12] = stru... | Write compressed "data" variable to the end of the file in a CVVR |
14,099 | def gdf_from_places(queries, gdf_name=, buffer_dist=None):
gdf = gpd.GeoDataFrame()
for query in queries:
gdf = gdf.append(gdf_from_place(query, buffer_dist=buffer_dist))
gdf = gdf.reset_index().drop(labels=, axis=1)
gdf.gdf_name = gdf_name
gdf.crs = settings.default_cr... | Create a GeoDataFrame from a list of place names to query.
Parameters
----------
queries : list
list of query strings or structured query dicts to geocode/download, one
at a time
gdf_name : string
name attribute metadata for GeoDataFrame (this is used to save shapefile
l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.