code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def set_section_order(self, section_name_list):
"""Set the order of the sections, which are by default unorderd.
Any unlisted sections that exist will be placed at the end of the
document in no particular order.
"""
self.section_headings = section_name_list[:]
for sectio... | Set the order of the sections, which are by default unorderd.
Any unlisted sections that exist will be placed at the end of the
document in no particular order. |
def _parse_binary(v, header_d):
""" Parses binary string.
Note:
<str> for py2 and <binary> for py3.
"""
# This is often a no-op, but it ocassionally converts numbers into strings
v = nullify(v)
if v is None:
return None
if six.PY2:
try:
return six.bi... | Parses binary string.
Note:
<str> for py2 and <binary> for py3. |
def copy(self):
"""
Retrieve a copy of the Environment. Note that this is a shallow
copy.
"""
return self.__class__(self._data.copy(), self._sensitive.copy(),
self._cwd) | Retrieve a copy of the Environment. Note that this is a shallow
copy. |
def delete(self, key, **opts):
"""Remove a key from the cache."""
key, store = self._expand_opts(key, opts)
try:
del store[key]
except KeyError:
pass | Remove a key from the cache. |
def ordered(self):
"""An equivalent unit cell with the active cell vectors coming first"""
active, inactive = self.active_inactive
order = active + inactive
return UnitCell(self.matrix[:,order], self.active[order]) | An equivalent unit cell with the active cell vectors coming first |
def rebuildtable(cls):
"""Regenerate the entire closuretree."""
cls._closure_model.objects.all().delete()
cls._closure_model.objects.bulk_create([cls._closure_model(
parent_id=x['pk'],
child_id=x['pk'],
depth=0
) for x in cls.objects.values("pk")])
... | Regenerate the entire closuretree. |
def get_new_links(self, url, resp):
"""Get new links from a URL and filter them."""
links_on_page = resp.xpath('//a/@href')
links = [utils.clean_url(u, url) for u in links_on_page]
# Remove non-links through filtering by protocol
links = [x for x in links if utils.check_protocol... | Get new links from a URL and filter them. |
def import_csv(filepath: str, currency: str):
""" Import prices from CSV file """
logger.debug(f"currency = {currency}")
# auto-convert to uppercase.
currency = currency.upper()
app = PriceDbApplication()
app.logger = logger
app.import_prices(filepath, currency) | Import prices from CSV file |
def unregister_widget(self, widget_cls):
"""Unregisters the given widget."""
if widget_cls.__name__ in self.widgets:
del self.widgets[widget_cls().get_name()] | Unregisters the given widget. |
def vert_dpi(self):
"""
Integer dots per inch for the height of this image. Defaults to 72
when not present in the file, as is often the case.
"""
pHYs = self._chunks.pHYs
if pHYs is None:
return 72
return self._dpi(pHYs.units_specifier, pHYs.vert_px_p... | Integer dots per inch for the height of this image. Defaults to 72
when not present in the file, as is often the case. |
def terminate(self, nowait=False):
"""Finalize and stop service
Args:
nowait: set to True to terminate immediately and skip processing
messages still in the queue
"""
logger.debug("Acquiring lock for service termination")
with self.lock:
l... | Finalize and stop service
Args:
nowait: set to True to terminate immediately and skip processing
messages still in the queue |
def _require(*names):
"""Helper for @require decorator."""
from IPython.parallel.error import UnmetDependency
user_ns = globals()
for name in names:
if name in user_ns:
continue
try:
exec 'import %s'%name in user_ns
except ImportError:
raise Un... | Helper for @require decorator. |
def Froude_densimetric(V, L, rho1, rho2, heavy=True, g=g):
r'''Calculates the densimetric Froude number :math:`Fr_{den}` for velocity
`V` geometric length `L`, heavier fluid density `rho1`, and lighter fluid
density `rho2`. If desired, gravity can be specified as well. Depending on
the application, thi... | r'''Calculates the densimetric Froude number :math:`Fr_{den}` for velocity
`V` geometric length `L`, heavier fluid density `rho1`, and lighter fluid
density `rho2`. If desired, gravity can be specified as well. Depending on
the application, this dimensionless number may be defined with the heavy
phase ... |
def points_possible(self, include_hidden=False):
"""Return the total points possible for this project."""
return sum([test_case.points for testable in self.testables
for test_case in testable.test_cases
if include_hidden or not testable.is_hidden]) | Return the total points possible for this project. |
def fix_contig_names(asseembly_path):
"""Removes whitespace from the assembly contig names
Parameters
----------
asseembly_path : path to assembly file
Returns
-------
str:
Path to new assembly file with fixed contig names
"""
fixed_assembly = "fixed_assembly.fa"
with... | Removes whitespace from the assembly contig names
Parameters
----------
asseembly_path : path to assembly file
Returns
-------
str:
Path to new assembly file with fixed contig names |
def run(self, ):
"""Start the configeditor
:returns: None
:rtype: None
:raises: None
"""
ra = SceneReleaseActions()
mayawin = maya_main_window()
self.rw = ReleaseWin(FILETYPES["mayamainscene"], parent=mayawin)
self.rw.set_release_actions(ra)
... | Start the configeditor
:returns: None
:rtype: None
:raises: None |
def aggregate_hazard_summary(impact, aggregate_hazard):
"""Compute the summary from the source layer to the aggregate_hazard layer.
Source layer :
|exp_id|exp_class|haz_id|haz_class|aggr_id|aggr_name|affected|extra*|
Target layer :
| aggr_id | aggr_name | haz_id | haz_class | extra* |
Output ... | Compute the summary from the source layer to the aggregate_hazard layer.
Source layer :
|exp_id|exp_class|haz_id|haz_class|aggr_id|aggr_name|affected|extra*|
Target layer :
| aggr_id | aggr_name | haz_id | haz_class | extra* |
Output layer :
|aggr_id| aggr_name|haz_id|haz_class|affected|extra... |
def get_or_create(cls, issue, header, text=None):
"""Get or create the dashboard comment in this issue.
"""
for comment in get_comments(issue):
try:
if comment.body.splitlines()[0] == header:
obj = cls(comment, header)
break
... | Get or create the dashboard comment in this issue. |
def summaries(self, sc, limit=None):
"""Summary of the files contained in the current dataset
Every item in the summary is a dict containing a key name and the corresponding size of
the key item in bytes, e.g.::
{'key': 'full/path/to/my/key', 'size': 200}
:param limit: Max numb... | Summary of the files contained in the current dataset
Every item in the summary is a dict containing a key name and the corresponding size of
the key item in bytes, e.g.::
{'key': 'full/path/to/my/key', 'size': 200}
:param limit: Max number of objects to retrieve
:return: An it... |
def must_open(filename, mode="r", checkexists=False, skipcheck=False, \
oappend=False):
"""
Accepts filename and returns filehandle.
Checks on multiple files, stdin/stdout/stderr, .gz or .bz2 file.
"""
if isinstance(filename, list):
assert "r" in mode
if filename[0].end... | Accepts filename and returns filehandle.
Checks on multiple files, stdin/stdout/stderr, .gz or .bz2 file. |
def clean_data(freqs, data, chunk, avg_bin):
""" Extract time-varying (wandering) lines from strain data.
Parameters
----------
freqs: list
List containing the frequencies of the wandering lines.
data: pycbc.types.TimeSeries
Strain data to extract the wandering lines from.
chunk... | Extract time-varying (wandering) lines from strain data.
Parameters
----------
freqs: list
List containing the frequencies of the wandering lines.
data: pycbc.types.TimeSeries
Strain data to extract the wandering lines from.
chunk: float
Duration of the chunks the data will ... |
def export_file(self, record, field, event=None, return_format='json'):
"""
Export the contents of a file stored for a particular record
Notes
-----
Unlike other export methods, this works on a single record.
Parameters
----------
record : str
... | Export the contents of a file stored for a particular record
Notes
-----
Unlike other export methods, this works on a single record.
Parameters
----------
record : str
record ID
field : str
field name containing the file to be exported.
... |
def set_length_and_maybe_checksums(self, record, payload_offset=None):
'''Set the content length and possibly the checksums.'''
if self._params.digests:
record.compute_checksum(payload_offset)
else:
record.set_content_length() | Set the content length and possibly the checksums. |
def batch_remove_absolute_retrain__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
""" Batch Remove Absolute (retrain)
xlabel = "Fraction of features removed"
ylabel = "1 - ROC AUC"
transform = "one_minus"
sort_order = 13
"""
return __run_batch_abs_metric(measures.batch_remove_r... | Batch Remove Absolute (retrain)
xlabel = "Fraction of features removed"
ylabel = "1 - ROC AUC"
transform = "one_minus"
sort_order = 13 |
def get_metadata_from_xml_tree(tree, get_issns_from_nlm=False,
get_abstracts=False, prepend_title=False,
mesh_annotations=False):
"""Get metadata for an XML tree containing PubmedArticle elements.
Documentation on the XML structure can be found at:
... | Get metadata for an XML tree containing PubmedArticle elements.
Documentation on the XML structure can be found at:
- https://www.nlm.nih.gov/bsd/licensee/elements_descriptions.html
- https://www.nlm.nih.gov/bsd/licensee/elements_alphabetical.html
Parameters
----------
tree : xml.etree... |
def pickledump(theobject, fname):
"""same as pickle.dump(theobject, fhandle).takes filename as parameter"""
fhandle = open(fname, 'wb')
pickle.dump(theobject, fhandle) | same as pickle.dump(theobject, fhandle).takes filename as parameter |
def check_lazy_load_gemeente(f):
'''
Decorator function to lazy load a :class:`Gemeente`.
'''
def wrapper(*args):
gemeente = args[0]
if (
gemeente._centroid is None or gemeente._bounding_box is None
or gemeente._taal_id is None or gemeente._metadata is None
... | Decorator function to lazy load a :class:`Gemeente`. |
def point(self, t):
"""returns the coordinates of the Bezier curve evaluated at t."""
return (1 - t)**2*self.start + 2*(1 - t)*t*self.control + t**2*self.end | returns the coordinates of the Bezier curve evaluated at t. |
def put_group_policy(self, group_name, policy_name, policy_json):
"""
Adds or updates the specified policy document for the specified group.
:type group_name: string
:param group_name: The name of the group the policy is associated with.
:type policy_name: string
:param... | Adds or updates the specified policy document for the specified group.
:type group_name: string
:param group_name: The name of the group the policy is associated with.
:type policy_name: string
:param policy_name: The policy document to get.
:type policy_json: string
:... |
def draw_panel(self, data, panel_params, coord, ax, **params):
"""
Plot all groups
For effeciency, geoms that do not need to partition
different groups before plotting should override this
method and avoid the groupby.
Parameters
----------
data : datafr... | Plot all groups
For effeciency, geoms that do not need to partition
different groups before plotting should override this
method and avoid the groupby.
Parameters
----------
data : dataframe
Data to be plotted by this geom. This is the
dataframe ... |
def send_Linux_notify(title, content, img_path):
'''发送Linux桌面通知'''
# Note: GNOME 下需要有任意的用户操作(鼠标、键盘等)才会自动隐藏通知
command = [
'notify-send',
'-a', 'Douban.fm', # 发送通知的应用名
'-t', '5000', # 自动隐藏的时间
'--hint=int:transient:1', # *建议* 桌面管理器不要保留通知
]
if img_path is not Non... | 发送Linux桌面通知 |
def read_json(self):
"""Read a single line and decode it as JSON.
Can raise an EOFError() when the input source was closed.
"""
line = self.stdin.readline()
if line == '':
raise EOFError()
return json.loads(line) | Read a single line and decode it as JSON.
Can raise an EOFError() when the input source was closed. |
def _parse_unit(measure_or_unit_abbreviation):
"""
Helper function that extracts constant factors from unit specifications.
This allows to specify units similar to this: 10^6 m^3.
Return a couple (unit, factor)
"""
try:
float(measure_or_unit_abbreviation[0])
# The mea... | Helper function that extracts constant factors from unit specifications.
This allows to specify units similar to this: 10^6 m^3.
Return a couple (unit, factor) |
def _get_argspec(f):
"""
Get argspec of a function. Supports both Python 2 and Python 3.
"""
if sys.version_info[0] < 3:
argspec = inspect.getargspec(f)
else:
# `getargspec` is deprecated since python3.0 (incompatible with function annotations).
# See SPARK-23569.
arg... | Get argspec of a function. Supports both Python 2 and Python 3. |
def save_ewif_file(self, path: str, password: str) -> None:
"""
Save an Encrypted Wallet Import Format file (WIF v2)
:param path: Path to file
:param password:
"""
# version
version = 1
# add version to seed
salt = libnacl.crypto_hash_sha256(
... | Save an Encrypted Wallet Import Format file (WIF v2)
:param path: Path to file
:param password: |
def _track(self, class_name):
"""Keep track of which test cases have executed."""
if self._test_cases.get(class_name) is None:
if self.streaming and self.header:
self._write_test_case_header(class_name, self.stream)
self._test_cases[class_name] = []
i... | Keep track of which test cases have executed. |
def ipv6_ipv6route_route_dest(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ipv6 = ET.SubElement(config, "ipv6", xmlns="urn:brocade.com:mgmt:brocade-common-def")
ipv6route = ET.SubElement(ipv6, "ipv6route", xmlns="urn:brocade.com:mgmt:brocade-ip-forwar... | Auto Generated Code |
def op_paths(self, path_base=None):
# type: (Union[str, UrlPath]) -> Generator[Tuple[UrlPath, Operation]]
"""
Return all operations stored in containers.
"""
if path_base:
path_base += self.path_prefix
else:
path_base = self.path_prefix or UrlPath(... | Return all operations stored in containers. |
def generate_filename(self, mark, **kwargs):
"""Comes up with a good filename for the watermarked image"""
kwargs = kwargs.copy()
kwargs['opacity'] = int(kwargs['opacity'] * 100)
kwargs['st_mtime'] = kwargs['fstat'].st_mtime
kwargs['st_size'] = kwargs['fstat'].st_size
... | Comes up with a good filename for the watermarked image |
def parse_eep(self, rorg_func=None, rorg_type=None, direction=None, command=None):
''' Parse EEP based on FUNC and TYPE '''
# set EEP profile, if demanded
if rorg_func is not None and rorg_type is not None:
self.select_eep(rorg_func, rorg_type, direction, command)
# parse dat... | Parse EEP based on FUNC and TYPE |
def threaded(system, func, *args, **kwargs):
""" uses thread_init as a decorator-style """
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
if system.raven_client:
system.raven_client.captureException(... | uses thread_init as a decorator-style |
def retry_shipper_tasks(self, project_name, logstore_name, shipper_name, task_list):
""" retry failed tasks , only the failed task can be retried
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type lo... | retry failed tasks , only the failed task can be retried
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type logstore_name: string
:param logstore_name: the logstore name
:type shipper_name... |
def parse_date_created(dct):
"""Helper function to parse date-created from profile."""
date = dct['date-created']
if date:
return (int(date['@year']), int(date['@month']), int(date['@day']))
else:
return (None, None, None) | Helper function to parse date-created from profile. |
def pivoted_cholesky(matrix, max_rank, diag_rtol=1e-3, name=None):
"""Computes the (partial) pivoted cholesky decomposition of `matrix`.
The pivoted Cholesky is a low rank approximation of the Cholesky decomposition
of `matrix`, i.e. as described in [(Harbrecht et al., 2012)][1]. The
currently-worst-approximat... | Computes the (partial) pivoted cholesky decomposition of `matrix`.
The pivoted Cholesky is a low rank approximation of the Cholesky decomposition
of `matrix`, i.e. as described in [(Harbrecht et al., 2012)][1]. The
currently-worst-approximated diagonal element is selected as the pivot at each
iteration. This y... |
def get_or_create_user(self, provider, access, info):
"Create a shell auth.User."
digest = hashlib.sha1(smart_bytes(access)).digest()
# Base 64 encode to get below 30 characters
# Removed padding characters
username = force_text(base64.urlsafe_b64encode(digest)).replace('=', '')
... | Create a shell auth.User. |
def ones(shape, ctx=None, dtype=None, **kwargs):
"""Returns a new array filled with all ones, with the given shape and type.
Parameters
----------
shape : int or tuple of int or list of int
The shape of the empty array.
ctx : Context, optional
An optional device context.
Def... | Returns a new array filled with all ones, with the given shape and type.
Parameters
----------
shape : int or tuple of int or list of int
The shape of the empty array.
ctx : Context, optional
An optional device context.
Defaults to the current default context (``mxnet.context.cu... |
def users_me_merge(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/users#merge-self-with-another-user"
api_path = "/api/v2/users/me/merge.json"
return self.call(api_path, method="PUT", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/users#merge-self-with-another-user |
def multi_trace_plot(traces, corr=True, stack='linstack', size=(7, 12),
**kwargs):
"""
Plot multiple traces (usually from the same station) on the same plot.
Differs somewhat to obspy's stream.plot in that only relative time within
traces is worried about, it will not merge traces ... | Plot multiple traces (usually from the same station) on the same plot.
Differs somewhat to obspy's stream.plot in that only relative time within
traces is worried about, it will not merge traces together.
:type traces: list
:param traces: List of obspy.core.Trace
:type corr: bool
:param corr:
... |
def _check_uninferable_call(self, node):
"""
Check that the given uninferable Call node does not
call an actual function.
"""
if not isinstance(node.func, astroid.Attribute):
return
# Look for properties. First, obtain
# the lhs of the Attribute node ... | Check that the given uninferable Call node does not
call an actual function. |
def for_print(self):
"""
for_print
"""
s = "\033[34m" + self.get_object_info() + "\033[0m"
s += "\n"
s += self.as_string()
return s | for_print |
def values(self):
"Returns a list of ConfigMap values."
return (list(self._pb.IntMap.values()) + list(self._pb.StringMap.values()) +
list(self._pb.FloatMap.values()) + list(self._pb.BoolMap.values())) | Returns a list of ConfigMap values. |
def volume_disk_temp_avg(self, volume):
"""Average temperature of all disks making up the volume"""
volume = self._get_volume(volume)
if volume is not None:
vol_disks = volume["disks"]
if vol_disks is not None:
total_temp = 0
total_d... | Average temperature of all disks making up the volume |
def get_soft_bounds(self):
"""
For each soft bound (upper and lower), if there is a defined bound (not equal to None)
then it is returned, otherwise it defaults to the hard bound. The hard bound could still be None.
"""
if self.bounds is None:
hl,hu=(None,None)
... | For each soft bound (upper and lower), if there is a defined bound (not equal to None)
then it is returned, otherwise it defaults to the hard bound. The hard bound could still be None. |
def stop_experiment(args):
'''Stop the experiment which is running'''
experiment_id_list = parse_ids(args)
if experiment_id_list:
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
for experiment_id in experiment_id_list:
print_nor... | Stop the experiment which is running |
def load_fd(self, key, noexpire=False):
'''Look up an item in the cache and return an open file
descriptor for the object. It is the caller's responsibility
to close the file descriptor.'''
cachekey = self.xform_key(key)
path = self.path(cachekey)
try:
stat... | Look up an item in the cache and return an open file
descriptor for the object. It is the caller's responsibility
to close the file descriptor. |
def batchDF(symbols, fields=None, range_='1m', last=10, token='', version=''):
'''Batch several data requests into one invocation
https://iexcloud.io/docs/api/#batch-requests
Args:
symbols (list); List of tickers to request
fields (list); List of fields to request
range_ (string);... | Batch several data requests into one invocation
https://iexcloud.io/docs/api/#batch-requests
Args:
symbols (list); List of tickers to request
fields (list); List of fields to request
range_ (string); Date range for chart
last (int);
token (string); Access token
... |
def get_extra_info(self, name, default=None):
"""
Return optional transport information.
- `'related_address'`: the related address
- `'sockname'`: the relayed address
"""
if name == 'related_address':
return self.__inner_protocol.transport.get_extra_info('so... | Return optional transport information.
- `'related_address'`: the related address
- `'sockname'`: the relayed address |
def get_broker_list(cluster_config):
"""Returns a list of brokers in the form [(id: host)]
:param cluster_config: the configuration of the cluster
:type cluster_config: map
"""
with ZK(cluster_config) as zk:
brokers = sorted(list(zk.get_brokers().items()), key=itemgetter(0))
return ... | Returns a list of brokers in the form [(id: host)]
:param cluster_config: the configuration of the cluster
:type cluster_config: map |
def find_module(self, module_name, path=None):
"""
Searches the paths for the required module.
:param module_name: the full name of the module to find
:param path: set to None when the module in being searched for is a
top-level module - otherwise this is set to
... | Searches the paths for the required module.
:param module_name: the full name of the module to find
:param path: set to None when the module in being searched for is a
top-level module - otherwise this is set to
package.__path__ for submodules and subpackages (... |
def mchirp_compression(m1, m2, fmin, fmax, min_seglen=0.02, df_multiple=None):
"""Return the frequencies needed to compress a waveform with the given
chirp mass. This is based on the estimate in rough_time_estimate.
Parameters
----------
m1: float
mass of first component object in solar mas... | Return the frequencies needed to compress a waveform with the given
chirp mass. This is based on the estimate in rough_time_estimate.
Parameters
----------
m1: float
mass of first component object in solar masses
m2: float
mass of second component object in solar masses
fmin : f... |
def send(self, channel, payload):
"""Send a message with the given payload on the given channel.
Messages are broadcast to all players in the group.
"""
with track('send_channel=' + channel):
with track('create event'):
Event.objects.create(
... | Send a message with the given payload on the given channel.
Messages are broadcast to all players in the group. |
def proto_0201(theABF):
"""protocol: membrane test."""
abf=ABF(theABF)
abf.log.info("analyzing as a membrane test")
plot=ABFplot(abf)
plot.figure_height,plot.figure_width=SQUARESIZE/2,SQUARESIZE/2
plot.figure_sweeps()
# save it
plt.tight_layout()
frameAndSave(abf,"membrane test")
... | protocol: membrane test. |
def _states(self):
"""Sets grid states"""
# The currently visible table
self.current_table = 0
# The cell that has been selected before the latest selection
self._last_selected_cell = 0, 0, 0
# If we are viewing cells based on their frozen status or normally
# ... | Sets grid states |
def calculate_lux(r, g, b):
"""Converts the raw R/G/B values to luminosity in lux."""
illuminance = (-0.32466 * r) + (1.57837 * g) + (-0.73191 * b)
return int(illuminance) | Converts the raw R/G/B values to luminosity in lux. |
def print_banner(filename: str, template: str = DEFAULT_BANNER_TEMPLATE) -> None:
"""
Print text file to output.
:param filename: Which file to print.
:param template: Format string which specified banner arrangement.
:return: Does not return anything
"""
if not os.path.isfile(filename):
... | Print text file to output.
:param filename: Which file to print.
:param template: Format string which specified banner arrangement.
:return: Does not return anything |
def split_url(url):
"""
Split the given URL ``base#anchor`` into ``(base, anchor)``,
or ``(base, None)`` if no anchor is present.
In case there are two or more ``#`` characters,
return only the first two tokens: ``a#b#c => (a, b)``.
:param string url: the url
:rtype: list of str
"""
... | Split the given URL ``base#anchor`` into ``(base, anchor)``,
or ``(base, None)`` if no anchor is present.
In case there are two or more ``#`` characters,
return only the first two tokens: ``a#b#c => (a, b)``.
:param string url: the url
:rtype: list of str |
def casefold_with_i_dots(text):
"""
Convert capital I's and capital dotted İ's to lowercase in the way
that's appropriate for Turkish and related languages, then case-fold
the rest of the letters.
"""
text = unicodedata.normalize('NFC', text).replace('İ', 'i').replace('I', 'ı')
return text.c... | Convert capital I's and capital dotted İ's to lowercase in the way
that's appropriate for Turkish and related languages, then case-fold
the rest of the letters. |
def _parse_options(opts, delim):
"""Helper method for split_options which creates the options dict.
Also handles the creation of a list for the URI tag_sets/
readpreferencetags portion."""
options = {}
for opt in opts.split(delim):
key, val = opt.split("=")
if key.lower() == 'readpre... | Helper method for split_options which creates the options dict.
Also handles the creation of a list for the URI tag_sets/
readpreferencetags portion. |
def qtePrepareToRun(self):
"""
This method is called by Qtmacs to prepare the macro for
execution.
It is probably a bad idea to overload this method as it only
administrates the macro execution and calls the ``qteRun``
method (which *should* be overloaded by the macro pr... | This method is called by Qtmacs to prepare the macro for
execution.
It is probably a bad idea to overload this method as it only
administrates the macro execution and calls the ``qteRun``
method (which *should* be overloaded by the macro programmer
in order for the macro to do s... |
def chmod_r(root: str, permission: int) -> None:
"""
Recursive ``chmod``.
Args:
root: directory to walk down
permission: e.g. ``e.g. stat.S_IWUSR``
"""
os.chmod(root, permission)
for dirpath, dirnames, filenames in os.walk(root):
for d in dirnames:
os.chmod(o... | Recursive ``chmod``.
Args:
root: directory to walk down
permission: e.g. ``e.g. stat.S_IWUSR`` |
def version(core_name=None):
'''
Gets the solr version for the core specified. You should specify a core
here as all the cores will run under the same servlet container and so will
all have the same version.
core_name : str (None)
The name of the solr core if using cores. Leave this blank ... | Gets the solr version for the core specified. You should specify a core
here as all the cores will run under the same servlet container and so will
all have the same version.
core_name : str (None)
The name of the solr core if using cores. Leave this blank if you are
not using cores or if ... |
def setAllColor(self, color):
"""
Command: 0x06
sets all colors in the array
Data:
[Command][r][g][b]
"""
header = bytearray()
header.append(LightProtocolCommand.SetAllColor)
light = bytearray()
light.extend(color)
buff = header + light
return self.send(buff) | Command: 0x06
sets all colors in the array
Data:
[Command][r][g][b] |
def parse_input(s):
"""Parse the given input and intelligently transform it into an absolute,
non-naive, timezone-aware datetime object for the UTC timezone.
The input can be specified as a millisecond-precision UTC timestamp (or
delta against Epoch), with or without a terminating 'L'. Alternatively, t... | Parse the given input and intelligently transform it into an absolute,
non-naive, timezone-aware datetime object for the UTC timezone.
The input can be specified as a millisecond-precision UTC timestamp (or
delta against Epoch), with or without a terminating 'L'. Alternatively, the
input can be specifi... |
def add_command_option(command, name, doc, is_bool=False):
"""
Add a custom option to a setup command.
Issues a warning if the option already exists on that command.
Parameters
----------
command : str
The name of the command as given on the command line
name : str
The nam... | Add a custom option to a setup command.
Issues a warning if the option already exists on that command.
Parameters
----------
command : str
The name of the command as given on the command line
name : str
The name of the build option
doc : str
A short description of the... |
def effect_ratio(self, mechanism, purview):
"""The effect ratio of the ``purview`` given ``mechanism``."""
return self._ratio(Direction.EFFECT, mechanism, purview) | The effect ratio of the ``purview`` given ``mechanism``. |
def strip_harakat(text):
"""Strip Harakat from arabic word except Shadda.
The striped marks are :
- FATHA, DAMMA, KASRA
- SUKUN
- FATHATAN, DAMMATAN, KASRATAN,
@param text: arabic text.
@type text: unicode.
@return: return a striped text.
@rtype: unicode.
"""
... | Strip Harakat from arabic word except Shadda.
The striped marks are :
- FATHA, DAMMA, KASRA
- SUKUN
- FATHATAN, DAMMATAN, KASRATAN,
@param text: arabic text.
@type text: unicode.
@return: return a striped text.
@rtype: unicode. |
def _map_player_request_to_func(self, player_request_type):
"""Provides appropriate parameters to the on_playback functions."""
# calbacks for on_playback requests are optional
view_func = self._intent_view_funcs.get(player_request_type, lambda: None)
argspec = inspect.getargspec(view_f... | Provides appropriate parameters to the on_playback functions. |
def set_handler(self, handler):
"""
Connect with a coroutine, which is scheduled when connection is made.
This function will create a task, and when connection is closed,
the task will be canceled.
:param handler:
:return: None
"""
if self._handler:
... | Connect with a coroutine, which is scheduled when connection is made.
This function will create a task, and when connection is closed,
the task will be canceled.
:param handler:
:return: None |
def _get_log_lines(self, n=300):
"""Returns a list with the last ``n`` lines of the nextflow log file
Parameters
----------
n : int
Number of last lines from the log file
Returns
-------
list
List of strings with the nextflow log
... | Returns a list with the last ``n`` lines of the nextflow log file
Parameters
----------
n : int
Number of last lines from the log file
Returns
-------
list
List of strings with the nextflow log |
def json(self):
""" returns a dict that represents a NetJSON NetworkGraph object """
nodes = []
links = []
for link in self.link_set.all():
if self.is_layer2:
source = link.interface_a.mac
destination = link.interface_b.mac
else:
... | returns a dict that represents a NetJSON NetworkGraph object |
def post_processor_affected_function(
exposure=None, hazard=None, classification=None, hazard_class=None):
"""Private function used in the affected postprocessor.
It returns a boolean if it's affected or not, or not exposed.
:param exposure: The exposure to use.
:type exposure: str
:param... | Private function used in the affected postprocessor.
It returns a boolean if it's affected or not, or not exposed.
:param exposure: The exposure to use.
:type exposure: str
:param hazard: The hazard to use.
:type hazard: str
:param classification: The hazard classification to use.
:type ... |
def format_title(self):
def asciify(_title):
_title = unicodedata.normalize('NFD', unicode(_title))
ascii = True
out = []
ok = u"1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM- ',"
for ch in _title:
if ch in ok:
... | Takes a string and sanitizes it for Github's url name format |
def signalbus(self):
"""The associated `SignalBus` object."""
try:
signalbus = self.__signalbus
except AttributeError:
signalbus = self.__signalbus = SignalBus(self, init_app=False)
return signalbus | The associated `SignalBus` object. |
def get_dependencies_from_index(dep, sources=None, pip_options=None, wheel_cache=None):
"""Retrieves dependencies for the given install requirement from the pip resolver.
:param dep: A single InstallRequirement
:type dep: :class:`~pip._internal.req.req_install.InstallRequirement`
:param sources: Pipfil... | Retrieves dependencies for the given install requirement from the pip resolver.
:param dep: A single InstallRequirement
:type dep: :class:`~pip._internal.req.req_install.InstallRequirement`
:param sources: Pipfile-formatted sources, defaults to None
:type sources: list[dict], optional
:return: A se... |
def copy(self):
"""Create a copy of this pen."""
pen = Pen()
pen.__dict__ = self.__dict__.copy()
return pen | Create a copy of this pen. |
def _get_html(self, url):
""" Get html from url
"""
self.log.info(u"/GET {}".format(url))
r = requests.get(url)
if hasattr(r, 'from_cache'):
if r.from_cache:
self.log.info("(from cache)")
if r.status_code != 200:
throw_request_err(... | Get html from url |
def clean_password(self):
"""Check that the password is valid."""
value = self.cleaned_data.get('password')
if value not in self.valid_passwords:
raise forms.ValidationError('Incorrect password.')
return value | Check that the password is valid. |
def portfolio_from_orders(orders, funds=1e5, price_type='close'):
"""Create a DataFrame of portfolio holdings (#'s' of shares for the symbols and dates)
Appends the "$CASH" symbol to the porfolio and initializes it to `funds` indicated.
Appends the symbol "total_value" to store the total value of cash + st... | Create a DataFrame of portfolio holdings (#'s' of shares for the symbols and dates)
Appends the "$CASH" symbol to the porfolio and initializes it to `funds` indicated.
Appends the symbol "total_value" to store the total value of cash + stocks at each timestamp.
The symbol holdings are found by multipling ... |
def get_reversed_aliases(self):
"""
Return the reversed aliases dict. Instead of being in the form
{'alias': mapping}, the dict is in the form {mapping: 'alias'}.
"""
return dict((v, k) for k, v in six.iteritems(self.aliases)) | Return the reversed aliases dict. Instead of being in the form
{'alias': mapping}, the dict is in the form {mapping: 'alias'}. |
def load_formatter_fn(formatter):
'''
>>> load_formatter_fn('logagg.formatters.basescript') #doctest: +ELLIPSIS
<function basescript at 0x...>
'''
obj = util.load_object(formatter)
if not hasattr(obj, 'ispartial'):
obj.ispartial = util.ispartial
return obj | >>> load_formatter_fn('logagg.formatters.basescript') #doctest: +ELLIPSIS
<function basescript at 0x...> |
def contains_duplicates(values: Iterable[Any]) -> bool:
"""
Does the iterable contain any duplicate values?
"""
for v in Counter(values).values():
if v > 1:
return True
return False | Does the iterable contain any duplicate values? |
def close(self):
"""
Closes the event streaming.
"""
if not self._response.raw.closed:
# find the underlying socket object
# based on api.client._get_raw_response_socket
sock_fp = self._response.raw._fp.fp
if hasattr(sock_fp, 'raw'):
... | Closes the event streaming. |
def login(self, username: str, password: str, course: int) -> requests.Response:
"""
登入課程
"""
try:
# 操作所需資訊
payload = {
'name': username,
'passwd': password,
'rdoCourse': course
}
# 回傳嘗試登入的回應
... | 登入課程 |
def run(self, row, **kwargs):
"""Methods takes a row and depending if a dict or list,
runs RML rules.
Args:
-----
row(Dict, List): Row from CSV Reader
"""
self.source = row
kwargs['output'] = self.__graph__()
super(CSVRowProcessor, self).run(*... | Methods takes a row and depending if a dict or list,
runs RML rules.
Args:
-----
row(Dict, List): Row from CSV Reader |
def _set_intrinsics(self):
"""Read the intrinsics matrix from the stream.
"""
strm = self._profile.get_stream(rs.stream.color)
obj = strm.as_video_stream_profile().get_intrinsics()
self._intrinsics[0, 0] = obj.fx
self._intrinsics[1, 1] = obj.fy
self._intrinsics[0,... | Read the intrinsics matrix from the stream. |
def _parse_access_vlan(self, config):
"""Scans the specified config and parse the access-vlan value
Args:
config (str): The interface configuration block to scan
Returns:
dict: A Python dict object with the value of switchport access
value. The dict retu... | Scans the specified config and parse the access-vlan value
Args:
config (str): The interface configuration block to scan
Returns:
dict: A Python dict object with the value of switchport access
value. The dict returned is intended to be merged into the
... |
def AjustarLiquidacionUnificadoPapel(self):
"Ajustar Liquidación realizada en un formulario F1116 B / C (papel)"
# limpiar arrays no enviados:
if not self.ajuste['ajusteBase']['certificados']:
del self.ajuste['ajusteBase']['certificados']
for k1 in ('ajusteCredito', ... | Ajustar Liquidación realizada en un formulario F1116 B / C (papel) |
def delete_project(id=None, name=None):
"""
Delete a Project by ID or name.
"""
content = delete_project_raw(id, name)
if content:
return utils.format_json(content) | Delete a Project by ID or name. |
def switch(self, first, second):
"""Switch two entries in the queue. Return False if an entry doesn't exist."""
allowed_states = ['queued', 'stashed']
if first in self.queue and second in self.queue \
and self.queue[first]['status'] in allowed_states\
and self.que... | Switch two entries in the queue. Return False if an entry doesn't exist. |
def get_offload(self, name, **kwargs):
"""Return a dictionary describing the connected offload target.
:param offload: Name of offload target to get information about.
:type offload: str
:param \*\*kwargs: See the REST API Guide on your array for the
documenta... | Return a dictionary describing the connected offload target.
:param offload: Name of offload target to get information about.
:type offload: str
:param \*\*kwargs: See the REST API Guide on your array for the
documentation on the request:
**... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.