positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def get(self, start, length):
"""
Fetch subsequence starting at position `start` with length `length`.
This method is picky about parameters, the requested interval must
have non-negative length and fit entirely inside the NIB sequence,
the returned string will contain exactly ... | Fetch subsequence starting at position `start` with length `length`.
This method is picky about parameters, the requested interval must
have non-negative length and fit entirely inside the NIB sequence,
the returned string will contain exactly 'length' characters, or an
AssertionError ... |
def check_cgroup_availability_in_thread(options):
"""
Run check_cgroup_availability() in a separate thread to detect the following problem:
If "cgexec --sticky" is used to tell cgrulesengd to not interfere
with our child processes, the sticky flag unfortunately works only
for processes spawned by th... | Run check_cgroup_availability() in a separate thread to detect the following problem:
If "cgexec --sticky" is used to tell cgrulesengd to not interfere
with our child processes, the sticky flag unfortunately works only
for processes spawned by the main thread, not those spawned by other threads
(and thi... |
def warning(self, *args):
"""Log a warning. Used for non-fatal problems."""
if _canShortcutLogging(self.logCategory, WARN):
return
warningObject(self.logObjectName(), self.logCategory,
*self.logFunction(*args)) | Log a warning. Used for non-fatal problems. |
def download_file(self, fname, output_dir):
"""Downloads competition file to output_dir."""
if fname not in self.competition_files: # pylint: disable=unsupported-membership-test
raise ValueError("%s is not one of the competition's "
"files: %s" % (fname, self.competition_files))
... | Downloads competition file to output_dir. |
def eval(expr, parser='pandas', engine=None, truediv=True,
local_dict=None, global_dict=None, resolvers=(), level=0,
target=None, inplace=False):
"""Evaluate a Python expression as a string using various backends.
The following arithmetic operations are supported: ``+``, ``-``, ``*``,
``/... | Evaluate a Python expression as a string using various backends.
The following arithmetic operations are supported: ``+``, ``-``, ``*``,
``/``, ``**``, ``%``, ``//`` (python engine only) along with the following
boolean operations: ``|`` (or), ``&`` (and), and ``~`` (not).
Additionally, the ``'pandas'`... |
def plugin(name):
"""Executes the selected plugin
Plugins are expected to be found in the kitchen's 'plugins' directory
"""
env.host_string = lib.get_env_host_string()
plug = lib.import_plugin(name)
lib.print_header("Executing plugin '{0}' on "
"{1}".format(name, env.host_s... | Executes the selected plugin
Plugins are expected to be found in the kitchen's 'plugins' directory |
def normalise(string):
"""
Convert each character of the string to the normal form in which it was
defined in the IPA spec. This would be normal form D, except for the
voiceless palatar fricative (ç) which should be in normal form C.
Helper for tokenise_word(string, ..).
"""
string = unicodedata.normalize('NFD'... | Convert each character of the string to the normal form in which it was
defined in the IPA spec. This would be normal form D, except for the
voiceless palatar fricative (ç) which should be in normal form C.
Helper for tokenise_word(string, ..). |
def run(self, args):
"""
Gives user permission based on auth_role arg and sends email to that user.
:param args Namespace arguments parsed from the command line
"""
email = args.email # email of person to send email to
username = args.username ... | Gives user permission based on auth_role arg and sends email to that user.
:param args Namespace arguments parsed from the command line |
def find_or_create(cls, **kwargs):
"""Checks if an instance already exists by filtering with the
kwargs. If yes, returns that instance. If not, creates a new
instance with kwargs and returns it
Args:
**kwargs: The keyword arguments which are used for filtering
... | Checks if an instance already exists by filtering with the
kwargs. If yes, returns that instance. If not, creates a new
instance with kwargs and returns it
Args:
**kwargs: The keyword arguments which are used for filtering
and initialization.
keys(list, ... |
def init_sqlite_db(path, initTime=False):
"""
Initialize SQLite Database
Args:
path(str): Path to database (Ex. '/home/username/my_sqlite.db').
initTime(Optional[bool]): If True, it will print the amount of time to generate database.
Example::
from gsshapy.lib.db_tools... | Initialize SQLite Database
Args:
path(str): Path to database (Ex. '/home/username/my_sqlite.db').
initTime(Optional[bool]): If True, it will print the amount of time to generate database.
Example::
from gsshapy.lib.db_tools import init_sqlite_db, create_session
... |
def _get_proc_status(proc):
'''
Returns the status of a Process instance.
It's backward compatible with < 2.0 versions of psutil.
'''
try:
return salt.utils.data.decode(proc.status() if PSUTIL2 else proc.status)
except (psutil.NoSuchProcess, psutil.AccessDenied):
return None | Returns the status of a Process instance.
It's backward compatible with < 2.0 versions of psutil. |
def todom(self):
""" Return the manifest as DOM tree """
doc = Document()
docE = doc.cE(self.manifestType)
if self.manifestType == "assemblyBinding":
cfg = doc.cE("configuration")
win = doc.cE("windows")
win.aChild(docE)
cfg.aChild(win)
... | Return the manifest as DOM tree |
def get_owner_emails(self, partial_owner_match=True):
"""Return a list of email addresses associated with the instance, based on tags
Returns:
List of email addresses if any, else None
"""
for tag in self.tags:
if tag.key.lower() == 'owner':
rgx =... | Return a list of email addresses associated with the instance, based on tags
Returns:
List of email addresses if any, else None |
def remove_jobs(self, mask):
"""Mark all jobs that match a mask as 'removed' """
jobnames = self.table[mask]['jobname']
jobkey = self.table[mask]['jobkey']
self.table[mask]['status'] = JobStatus.removed
for jobname, jobkey in zip(jobnames, jobkey):
fullkey = JobDetail... | Mark all jobs that match a mask as 'removed' |
def select_army(action, action_space, select_add):
"""Select the entire army."""
del action_space
action.action_ui.select_army.selection_add = select_add | Select the entire army. |
def pprint(self, stream=None, indent=1, width=80, depth=None):
"""
Pretty print the underlying literal Python object
"""
pp.pprint(to_literal(self), stream, indent, width, depth) | Pretty print the underlying literal Python object |
def default(cls):
"Make the current foreground color the default."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.FOREGROUND_MASK
wAttributes |= win32.FOREGROUND_GREY
wAttributes &= ~win32.FOREGROUND_INTENSITY
cls._set_text_attributes(wAttributes) | Make the current foreground color the default. |
def run_sked(self, object_id, sked, verbose=False):
"""
sked is the proper name of the schedule:
IRS990, IRS990EZ, IRS990PF, IRS990ScheduleA, etc.
"""
self.whole_filing_data = []
self.filing_keyerr_data = []
this_filing = Filing(object_id)
this_filing.proc... | sked is the proper name of the schedule:
IRS990, IRS990EZ, IRS990PF, IRS990ScheduleA, etc. |
def cross_phenotype_jsd(data, groupby, bins, n_iter=100):
"""Jensen-Shannon divergence of features across phenotypes
Parameters
----------
data : pandas.DataFrame
A (n_samples, n_features) Dataframe
groupby : mappable
A samples to phenotypes mapping
n_iter : int
Number o... | Jensen-Shannon divergence of features across phenotypes
Parameters
----------
data : pandas.DataFrame
A (n_samples, n_features) Dataframe
groupby : mappable
A samples to phenotypes mapping
n_iter : int
Number of bootstrap resampling iterations to perform for the
with... |
def summary(self, St=None):
"""Tabular summary of strategy composition, broken out by option.
Returns
-------
pd.DataFrame
Columns: kind, position, strike, price, St, payoff, profit.
"""
St = self.St if St is None else St
if self.options:
... | Tabular summary of strategy composition, broken out by option.
Returns
-------
pd.DataFrame
Columns: kind, position, strike, price, St, payoff, profit. |
def add(self, value_id, name, value_class):
"""
Factory function that creates a value.
:param value_id: id of the value, used to reference the value within this list.BaseException
:param value_class: The class of the value that should be created with this function.
"""
... | Factory function that creates a value.
:param value_id: id of the value, used to reference the value within this list.BaseException
:param value_class: The class of the value that should be created with this function. |
def terra(latitude, longitude, elevation, gast):
"""Compute the position and velocity of a terrestrial observer.
`latitude` - Latitude in radians.
`longitude` - Longitude in radians.
`elevation` - Elevation above sea level in au.
`gast` - Hours of Greenwich Apparent Sidereal Time (can be an array).... | Compute the position and velocity of a terrestrial observer.
`latitude` - Latitude in radians.
`longitude` - Longitude in radians.
`elevation` - Elevation above sea level in au.
`gast` - Hours of Greenwich Apparent Sidereal Time (can be an array).
The return value is a tuple of two 3-vectors `(pos... |
def download(dataset, node, entityids, products, api_key=None):
"""
The use of this request will be to obtain valid data download URLs.
:param dataset:
:param entityIds:
list
:param products:
list
:param node:
:param api_key:
API key is requir... | The use of this request will be to obtain valid data download URLs.
:param dataset:
:param entityIds:
list
:param products:
list
:param node:
:param api_key:
API key is required. |
def maybe_download(url, filename):
"""Download the data from Yann's website, unless it's already here."""
if not os.path.exists(WORK_DIRECTORY):
os.mkdir(WORK_DIRECTORY)
filepath = os.path.join(WORK_DIRECTORY, filename)
if not os.path.exists(filepath):
filepath, _ = request.urlretrieve(url + filename, f... | Download the data from Yann's website, unless it's already here. |
def calc_effective_diffusivity(self, inlets=None, outlets=None,
domain_area=None, domain_length=None):
r"""
This calculates the effective diffusivity in this linear transport
algorithm.
Parameters
----------
inlets : array_like
... | r"""
This calculates the effective diffusivity in this linear transport
algorithm.
Parameters
----------
inlets : array_like
The pores where the inlet composition boundary conditions were
applied. If not given an attempt is made to infer them from the
... |
def available_actions(self, obs):
"""Return the list of available action ids."""
available_actions = set()
hide_specific_actions = self._agent_interface_format.hide_specific_actions
for i, func in six.iteritems(actions.FUNCTIONS_AVAILABLE):
if func.avail_fn(obs):
available_actions.add(i)
... | Return the list of available action ids. |
def compact(self):
"""Compacts the queue: removes all the messages from the queue that
have been fetched by all the subscribed coroutines.
Returns the number of messages that have been removed."""
if self.subscribers:
level = min(self.subscribers.itervalues())
... | Compacts the queue: removes all the messages from the queue that
have been fetched by all the subscribed coroutines.
Returns the number of messages that have been removed. |
def _headers(self):
"""Ensure the Authorization Header has a valid Access Token."""
if not self.access_token or not self.access_token_expires:
self._basic_login()
elif datetime.now() > self.access_token_expires - timedelta(seconds=30):
self._basic_login()
return... | Ensure the Authorization Header has a valid Access Token. |
def run_mapper(self, stdin=sys.stdin, stdout=sys.stdout):
"""
Run the mapper on the hadoop node.
"""
self.init_hadoop()
self.init_mapper()
outputs = self._map_input((line[:-1] for line in stdin))
if self.reducer == NotImplemented:
self.writer(outputs, ... | Run the mapper on the hadoop node. |
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.g... | Exctract API version from provided URL |
def _parse_apps_to_ignore(self):
"""
Parse the applications to ignore in the config.
Returns:
set
"""
# We ignore nothing by default
apps_to_ignore = set()
# Is the "[applications_to_ignore]" in the cfg file ?
section_title = 'applications_to... | Parse the applications to ignore in the config.
Returns:
set |
def walk_direction_preheel(self, data_frame):
"""
Estimate local walk (not cardinal) direction with pre-heel strike phase.
Inspired by Nirupam Roy's B.E. thesis: "WalkCompass: Finding Walking Direction Leveraging Smartphone's Inertial Sensors"
:param data_frame: The data f... | Estimate local walk (not cardinal) direction with pre-heel strike phase.
Inspired by Nirupam Roy's B.E. thesis: "WalkCompass: Finding Walking Direction Leveraging Smartphone's Inertial Sensors"
:param data_frame: The data frame. It should have x, y, and z columns.
:type data_frame:... |
def _normalize(image):
"""Normalize the image to zero mean and unit variance."""
offset = tf.constant(MEAN_RGB, shape=[1, 1, 3])
image -= offset
scale = tf.constant(STDDEV_RGB, shape=[1, 1, 3])
image /= scale
return image | Normalize the image to zero mean and unit variance. |
def setCmd(self, cmd):
"""Check the cmd is valid, FrameError will be raised if its not."""
cmd = cmd.upper()
if cmd not in VALID_COMMANDS:
raise FrameError("The cmd '%s' is not valid! It must be one of '%s' (STOMP v%s)." % (
cmd, VALID_COMMANDS, STOMP_VERSION)
... | Check the cmd is valid, FrameError will be raised if its not. |
def to_raw(self, value, context=None):
"""Convert the value to a JSON compatible value"""
if value is None:
return None
res = {}
value = value.copy()
errors = []
for field in list(set(value) & set(self._fields)):
schema = self._fields.get(field)
... | Convert the value to a JSON compatible value |
def __reset_crosshair(self):
"""
redraw the cross-hair on the horizontal slice plot
Parameters
----------
x: int
the x image coordinate
y: int
the y image coordinate
Returns
-------
"""
self.lhor.set_ydata(self.y_c... | redraw the cross-hair on the horizontal slice plot
Parameters
----------
x: int
the x image coordinate
y: int
the y image coordinate
Returns
------- |
def add_format(self, parser, default=Encoding.PEM, help_text=None, opts=None):
"""Add the --format option."""
if opts is None:
opts = ['-f', '--format']
if help_text is None:
help_text = 'The format to use ("ASN1" is an alias for "DER", default: %(default)s).'
he... | Add the --format option. |
def calc_schm_wats_v1(self):
"""Calculate the actual amount of water melting within the snow cover.
Required control parameters:
|NHRU|
|Lnk|
Required flux sequences:
|SBes|
|WGTF|
Calculated flux sequence:
|Schm|
Updated state sequence:
|WATS|
Basic equa... | Calculate the actual amount of water melting within the snow cover.
Required control parameters:
|NHRU|
|Lnk|
Required flux sequences:
|SBes|
|WGTF|
Calculated flux sequence:
|Schm|
Updated state sequence:
|WATS|
Basic equations:
:math:`\\frac{dWATS}{dt... |
def set_parameters(self):
"""Setup all the parameters for the binaries to be evaluated.
Grid values and store necessary parameters for input into the SNR function.
"""
# declare 1D arrays of both paramters
if self.xscale != 'lin':
self.xvals = np.logspace(np.log10(... | Setup all the parameters for the binaries to be evaluated.
Grid values and store necessary parameters for input into the SNR function. |
def cp(hdfs_src, hdfs_dst):
"""Copy a file
:param hdfs_src: Source (str)
:param hdfs_dst: Destination (str)
:raises: IOError: If unsuccessful
"""
cmd = "hadoop fs -cp %s %s" % (hdfs_src, hdfs_dst)
rcode, stdout, stderr = _checked_hadoop_fs_command(cmd) | Copy a file
:param hdfs_src: Source (str)
:param hdfs_dst: Destination (str)
:raises: IOError: If unsuccessful |
def transmit_ack_bpdu(self):
""" Send Topology Change Ack BPDU. """
ack_flags = 0b10000001
bpdu_data = self._generate_config_bpdu(ack_flags)
self.ofctl.send_packet_out(self.ofport.port_no, bpdu_data) | Send Topology Change Ack BPDU. |
def free_params(self, value):
"""Set the free parameters. Note that this bypasses enforce_bounds.
"""
value = scipy.asarray(value, dtype=float)
self.K_up_to_date = False
self.k.free_params = value[:self.k.num_free_params]
self.w.free_params = value[self.k.num_free_params:... | Set the free parameters. Note that this bypasses enforce_bounds. |
def backup(self):
"""
Backup the application config files.
Algorithm:
if exists home/file
if home/file is a real file
if exists mackup/file
are you sure ?
if sure
rm mackup/file
... | Backup the application config files.
Algorithm:
if exists home/file
if home/file is a real file
if exists mackup/file
are you sure ?
if sure
rm mackup/file
mv home/file mackup/file
... |
def exec_command(command, cwd=None):
r'''
Helper to exec locally (subprocess) or remotely (paramiko)
'''
rc = None
stdout = stderr = None
if ssh_conn is None:
ld_library_path = {'LD_LIBRARY_PATH': '.:%s' % os.environ.get('LD_LIBRARY_PATH', '')}
p = subprocess.Popen(command, stdo... | r'''
Helper to exec locally (subprocess) or remotely (paramiko) |
def simple2data(text):
"""
Convert a simple table to data (the kind used by DashTable)
Parameters
----------
text : str
A valid simple rst table
Returns
-------
table : list of lists of str
spans : list of lists of lists of int
A span is a [row, column] pair that de... | Convert a simple table to data (the kind used by DashTable)
Parameters
----------
text : str
A valid simple rst table
Returns
-------
table : list of lists of str
spans : list of lists of lists of int
A span is a [row, column] pair that defines a group of merged
cel... |
def rename(self, renaming: Dict[str, str]) -> 'Substitution':
"""Return a copy of the substitution with renamed variables.
Example:
Rename the variable *x* to *y*:
>>> subst = Substitution({'x': a})
>>> subst.rename({'x': 'y'})
{'y': Symbol('a')}
... | Return a copy of the substitution with renamed variables.
Example:
Rename the variable *x* to *y*:
>>> subst = Substitution({'x': a})
>>> subst.rename({'x': 'y'})
{'y': Symbol('a')}
Args:
renaming:
A dictionary mapping old v... |
def send_mass_video(self, group_or_users, media_id, title=None,
description=None, is_to_all=False, preview=False,
send_ignore_reprint=0, client_msg_id=None):
"""
群发视频消息
详情请参考
https://mp.weixin.qq.com/wiki?id=mp1481187827_i0l21
:pa... | 群发视频消息
详情请参考
https://mp.weixin.qq.com/wiki?id=mp1481187827_i0l21
:param group_or_users: 值为整型数字时为按分组群发,值为列表/元组时为按 OpenID 列表群发
当 is_to_all 为 True 时,传入 None 即对所有用户发送。
:param media_id: 视频的媒体 ID。可以通过 :func:`upload_video` 上传。
:param title: 视频标题
... |
def _check_valid_data(self, data):
"""Checks that the incoming data is a 3 x #elements ndarray of normal
vectors.
Parameters
----------
data : :obj:`numpy.ndarray`
The data to verify.
Raises
------
ValueError
If the data is not of... | Checks that the incoming data is a 3 x #elements ndarray of normal
vectors.
Parameters
----------
data : :obj:`numpy.ndarray`
The data to verify.
Raises
------
ValueError
If the data is not of the correct shape or type, or if the vectors
... |
def sim(sense1: "wn.Synset", sense2: "wn.Synset", option: str = "path") -> float:
"""
Calculates similarity based on user's choice.
:param sense1: A synset.
:param sense2: A synset.
:param option: String, one of ('path', 'wup', 'lch', 'res', 'jcn', 'lin').
:return: A float, similarity measureme... | Calculates similarity based on user's choice.
:param sense1: A synset.
:param sense2: A synset.
:param option: String, one of ('path', 'wup', 'lch', 'res', 'jcn', 'lin').
:return: A float, similarity measurement. |
def set(self, instance, value, **kw):
"""Converts the value into a DateTime object before setting.
"""
if value:
try:
value = DateTime(value)
except SyntaxError:
logger.warn("Value '{}' is not a valid DateTime string"
... | Converts the value into a DateTime object before setting. |
def parse_csv_file(url, res):
"""Parse given URL and write res with {scheme -> description}"""
response = requests.get(url, stream=True)
reader = csv.reader(response.iter_lines())
first_row = True
for row in reader:
if first_row:
# skip first row
first_row = False
... | Parse given URL and write res with {scheme -> description} |
def _at(self, idx):
"""Returns a view of the array sliced at `idx` in the first dim.
This is called through ``x[idx]``.
Parameters
----------
idx : int
index for slicing the `NDArray` in the first dim.
Returns
-------
NDArray
`NDA... | Returns a view of the array sliced at `idx` in the first dim.
This is called through ``x[idx]``.
Parameters
----------
idx : int
index for slicing the `NDArray` in the first dim.
Returns
-------
NDArray
`NDArray` sharing the memory with t... |
def import_object_from_path(path, object):
"""Used to import an object from an absolute path.
This function takes an absolute path and imports it as a Python module.
It then returns the object with name `object` from the imported module.
Args:
path (string): Absolute file path of .py file to i... | Used to import an object from an absolute path.
This function takes an absolute path and imports it as a Python module.
It then returns the object with name `object` from the imported module.
Args:
path (string): Absolute file path of .py file to import
object (string): Name of object to ... |
def register_link(self, obj, attr=None):
"""
creates link from obj.attr to self
:param obj: object to register link to
:param attr: attribute name to register link to
"""
name = repr(self)
if not name:
return self
l = self.__class__._get_links(... | creates link from obj.attr to self
:param obj: object to register link to
:param attr: attribute name to register link to |
def iter_tsv(input_stream, cols=None, encoding='utf-8'):
"""
If a tuple is given in cols, use the elements as names to construct
a namedtuple.
Columns can be marked as ignored by using ``X`` or ``0`` as column name.
Example (ignore the first four columns of a five column TSV):
::
def... | If a tuple is given in cols, use the elements as names to construct
a namedtuple.
Columns can be marked as ignored by using ``X`` or ``0`` as column name.
Example (ignore the first four columns of a five column TSV):
::
def run(self):
with self.input().open() as handle:
... |
def reset(self):
"""Resets the sampler to its initial state
Note
----
This will destroy the label cache and history of estimates.
"""
self._TP = np.zeros(self._n_class)
self._FP = np.zeros(self._n_class)
self._FN = np.zeros(self._n_class)
self._TN... | Resets the sampler to its initial state
Note
----
This will destroy the label cache and history of estimates. |
def recorddiff(a, b, buffersize=None, tempdir=None, cache=True, strict=False):
"""
Find the difference between records in two tables. E.g.::
>>> import petl as etl
>>> a = [['foo', 'bar', 'baz'],
... ['A', 1, True],
... ['C', 7, False],
... ['B', 2, False]... | Find the difference between records in two tables. E.g.::
>>> import petl as etl
>>> a = [['foo', 'bar', 'baz'],
... ['A', 1, True],
... ['C', 7, False],
... ['B', 2, False],
... ['C', 9, True]]
>>> b = [['bar', 'foo', 'baz'],
... ... |
def kde_none(events_x, events_y, xout=None, yout=None):
""" No Kernel Density Estimation
Parameters
----------
events_x, events_y: 1D ndarray
The input points for kernel density estimation. Input
is flattened automatically.
xout, yout: ndarray
The coordinates at which the KD... | No Kernel Density Estimation
Parameters
----------
events_x, events_y: 1D ndarray
The input points for kernel density estimation. Input
is flattened automatically.
xout, yout: ndarray
The coordinates at which the KDE should be computed.
If set to none, input coordinates ... |
def _get_cached_file_name(bucket_name, saltenv, path):
'''
Return the cached file name for a bucket path file
'''
file_path = os.path.join(_get_cache_dir(), saltenv, bucket_name, path)
# make sure bucket and saltenv directories exist
if not os.path.exists(os.path.dirname(file_path)):
o... | Return the cached file name for a bucket path file |
def _get_item_str(self, res):
"""Return genes in any of these formats:
1. 19264, 17319, 12520, 12043, 74131, 22163, 12575
2. Ptprc, Mif, Cd81, Bcl2, Sash3, Tnfrsf4, Cdkn1a
3. 7: Ptprc, Mif, Cd81, Bcl2, Sash3...
"""
npl = self.pltvars.items_p_line # Numb... | Return genes in any of these formats:
1. 19264, 17319, 12520, 12043, 74131, 22163, 12575
2. Ptprc, Mif, Cd81, Bcl2, Sash3, Tnfrsf4, Cdkn1a
3. 7: Ptprc, Mif, Cd81, Bcl2, Sash3... |
def write_force_constants_to_hdf5(force_constants,
filename='force_constants.hdf5',
p2s_map=None,
physical_unit=None,
compression=None):
"""Write force constants in hdf5 format.
... | Write force constants in hdf5 format.
Parameters
----------
force_constants: ndarray
Force constants
shape=(n_satom,n_satom,3,3) or (n_patom,n_satom,3,3)
dtype=double
filename: str
Filename to be saved
p2s_map: ndarray
Primitive atom indices in supercell inde... |
def step_into(self):
"""Take a forward step (into) for all active states in the state machine
"""
logger.debug("Execution step into ...")
self.run_to_states = []
if self.finished_or_stopped():
self.set_execution_mode(StateMachineExecutionStatus.FORWARD_INTO)
... | Take a forward step (into) for all active states in the state machine |
def get_output(src):
"""
parse lines looking for commands
"""
output = ''
lines = open(src.path, 'rU').readlines()
for line in lines:
m = re.match(config.import_regex,line)
if m:
include_path = os.path.abspath(src.dir + '/' + m.group('script'));
if include... | parse lines looking for commands |
def negative_sharpe(
weights, expected_returns, cov_matrix, gamma=0, risk_free_rate=0.02
):
"""
Calculate the negative Sharpe ratio of a portfolio
:param weights: asset weights of the portfolio
:type weights: np.ndarray
:param expected_returns: expected return of each asset
:type expected_r... | Calculate the negative Sharpe ratio of a portfolio
:param weights: asset weights of the portfolio
:type weights: np.ndarray
:param expected_returns: expected return of each asset
:type expected_returns: pd.Series
:param cov_matrix: the covariance matrix of asset returns
:type cov_matrix: pd.Dat... |
def add_time_event(self, time_event):
"""Add a TimeEvent.
:type time_event: :class: `~opencensus.trace.time_event.TimeEvent`
:param time_event: A TimeEvent object.
"""
if isinstance(time_event, time_event_module.TimeEvent):
self.time_events.append(time_event)
... | Add a TimeEvent.
:type time_event: :class: `~opencensus.trace.time_event.TimeEvent`
:param time_event: A TimeEvent object. |
def show_url(context, **kwargs):
"""Return the show feed URL with different protocol."""
if len(kwargs) != 2:
raise TemplateSyntaxError(_('"show_url" tag takes exactly two keyword arguments.'))
request = context['request']
current_site = get_current_site(request)
url = add_domain(current_sit... | Return the show feed URL with different protocol. |
def stop(self):
"""
Stops a paused pipeline. This will a trigger a ``StopIteration`` in the
inputs of the pipeline. And retrieve the buffered results. This will
stop all ``Pipers`` and ``NuMaps``. Python will not terminate cleanly
if a pipeline is running or paused.
... | Stops a paused pipeline. This will a trigger a ``StopIteration`` in the
inputs of the pipeline. And retrieve the buffered results. This will
stop all ``Pipers`` and ``NuMaps``. Python will not terminate cleanly
if a pipeline is running or paused. |
def build_config(self, config):
"""Set config defaults"""
for sec in 'LiSE', 'ELiDE':
config.adddefaultsection(sec)
config.setdefaults(
'LiSE',
{
'world': 'sqlite:///LiSEworld.db',
'language': 'eng',
'logfile': '... | Set config defaults |
def ring_is_planar(ring, r_atoms):
"""Given a set of ring atoms, check if the ring is sufficiently planar
to be considered aromatic"""
normals = []
for a in r_atoms:
adj = pybel.ob.OBAtomAtomIter(a.OBAtom)
# Check for neighboring atoms in the ring
n_coords = [pybel.Atom(neigh).co... | Given a set of ring atoms, check if the ring is sufficiently planar
to be considered aromatic |
def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_oss_error():
bucket = self._get_bucket(client_kwargs)
# Object
if 'key' in client_kwargs:
retur... | Remove an object.
args:
client_kwargs (dict): Client arguments. |
def show(self, application_id, host_id):
"""
This API endpoint returns a single application host, identified by its
ID.
:type application_id: int
:param application_id: Application ID
:type host_id: int
:param host_id: Application host ID
:rtype: dict
... | This API endpoint returns a single application host, identified by its
ID.
:type application_id: int
:param application_id: Application ID
:type host_id: int
:param host_id: Application host ID
:rtype: dict
:return: The JSON response of the API
::
... |
def unlock(self):
"""
Unlock the active advisory lock.
"""
logger.debug("Releasing lock %s", self.lock_file)
self._lock.release()
try:
os.unlink(self.lock_file)
except FileNotFoundError:
pass | Unlock the active advisory lock. |
def parse(content, *args, **kwargs):
''' Use mecab-python3 by default to parse JP text. Fall back to mecab binary app if needed '''
global MECAB_PYTHON3
if 'mecab_loc' not in kwargs and MECAB_PYTHON3 and 'MeCab' in globals():
return MeCab.Tagger(*args).parse(content)
else:
return r... | Use mecab-python3 by default to parse JP text. Fall back to mecab binary app if needed |
def _filter_match(self, span: span, relations: Dict, patterns: List) -> bool:
"""
Filter the match result according to prefix, suffix, min, max ...
Args:
span: span
relations: Dict
patterns: List of pattern
Returns: bool
"""
for patte... | Filter the match result according to prefix, suffix, min, max ...
Args:
span: span
relations: Dict
patterns: List of pattern
Returns: bool |
def set_server_dir(self, dir):
"""
Set the directory of the server to be controlled
"""
self.dir = os.path.abspath(dir)
config = os.path.join(self.dir, 'etc', 'grid', 'config.xml')
self.configured = os.path.exists(config) | Set the directory of the server to be controlled |
def getStrips(self, scraperobj):
"""Download comic strips."""
with lock:
host_lock = get_host_lock(scraperobj.url)
with host_lock:
self._getStrips(scraperobj) | Download comic strips. |
def _installed_snpeff_genome(base_name, config):
"""Find the most recent installed genome for snpEff with the given name.
"""
snpeff_config_file = os.path.join(config_utils.get_program("snpeff", config, "dir"),
"snpEff.config")
if os.path.exists(snpeff_config_file):... | Find the most recent installed genome for snpEff with the given name. |
def parse_pr_numbers(git_log_lines):
"""
Parse PR numbers from commit messages. At GitHub those have the format:
`here is the message (#1234)`
being `1234` the PR number.
"""
prs = []
for line in git_log_lines:
pr_number = parse_pr_number(line)
if pr_number:
... | Parse PR numbers from commit messages. At GitHub those have the format:
`here is the message (#1234)`
being `1234` the PR number. |
def setCursorSize(self, p):
'sets width based on diagonal corner p'
self.cursorBox = BoundingBox(self.cursorBox.xmin, self.cursorBox.ymin, p.x, p.y)
self.cursorBox.w = max(self.cursorBox.w, self.canvasCharWidth)
self.cursorBox.h = max(self.cursorBox.h, self.canvasCharHeight) | sets width based on diagonal corner p |
def _tobytes(self, skipprepack = False):
'''
Convert the struct to bytes. This is the standard way to convert a NamedStruct to bytes.
:param skipprepack: if True, the prepack stage is skipped. For parser internal use.
:returns: converted bytes
'''
stream... | Convert the struct to bytes. This is the standard way to convert a NamedStruct to bytes.
:param skipprepack: if True, the prepack stage is skipped. For parser internal use.
:returns: converted bytes |
def disk_toggle(device, flag):
'''
Toggle the state of <flag> on <device>. Valid flags are the same
as the disk_set command.
CLI Example:
.. code-block:: bash
salt '*' partition.disk_toggle /dev/sda pmbr_boot
'''
_validate_device(device)
if flag not in VALID_DISK_FLAGS:
... | Toggle the state of <flag> on <device>. Valid flags are the same
as the disk_set command.
CLI Example:
.. code-block:: bash
salt '*' partition.disk_toggle /dev/sda pmbr_boot |
async def delay(source, delay):
"""Delay the iteration of an asynchronous sequence."""
await asyncio.sleep(delay)
async with streamcontext(source) as streamer:
async for item in streamer:
yield item | Delay the iteration of an asynchronous sequence. |
def arange(start, stop=None, step=1.0, repeat=1, infer_range=None, ctx=None, dtype=mx_real_t):
"""Returns evenly spaced values within a given interval.
Values are generated within the half-open interval [`start`, `stop`). In other
words, the interval includes `start` but excludes `stop`. The function is
... | Returns evenly spaced values within a given interval.
Values are generated within the half-open interval [`start`, `stop`). In other
words, the interval includes `start` but excludes `stop`. The function is
similar to the built-in Python function `range` and to `numpy.arange`,
but returns an `NDArray`.... |
def classify(self, classifier_id, text, **kwargs):
"""
Classify a phrase.
Returns label information for the input. The status must be `Available` before you
can use the classifier to classify text.
:param str classifier_id: Classifier ID to use.
:param str text: The sub... | Classify a phrase.
Returns label information for the input. The status must be `Available` before you
can use the classifier to classify text.
:param str classifier_id: Classifier ID to use.
:param str text: The submitted phrase. The maximum length is 2048 characters.
:param di... |
def _set_var_res(self, weights):
"""
Transform the weights to var_res
"""
if weights is None:
return
# layer 1
motif_base_weights_raw = np.swapaxes(weights["motif_base_weights"], 2, 0)
motif_base_weights = motif_base_weights_raw[np.newaxis]
mo... | Transform the weights to var_res |
def tictactoe(w, i, player, opponent, grid=None):
"Put two strategies to a classic battle of wits."
grid = grid or empty_grid
while True:
w.render_to_terminal(w.array_from_text(view(grid)))
if is_won(grid):
print(whose_move(grid), "wins.")
break
if not success... | Put two strategies to a classic battle of wits. |
def nx_gen_edge_values(G, key, edges=None, default=util_const.NoParam,
on_missing='error', on_keyerr='default'):
"""
Generates attributes values of specific edges
Args:
on_missing (str): Strategy for handling nodes missing from G.
Can be {'error', 'default'}. def... | Generates attributes values of specific edges
Args:
on_missing (str): Strategy for handling nodes missing from G.
Can be {'error', 'default'}. defaults to 'error'.
on_keyerr (str): Strategy for handling keys missing from node dicts.
Can be {'error', 'default'}. defaults to... |
def save(self):
"""
Creates / updates a row.
This is a blind insert call.
All validation and cleaning needs to happen
prior to calling this.
"""
if self.instance is None:
raise CQLEngineException("DML Query intance attribute is None")
assert ty... | Creates / updates a row.
This is a blind insert call.
All validation and cleaning needs to happen
prior to calling this. |
def _get_obj(self,space):
"""
Imports the acquisition function.
"""
obj_func = self.obj_func
from ..core.task import SingleObjective
return SingleObjective(obj_func, self.config['resources']['cores'], space=space, unfold_args=True) | Imports the acquisition function. |
def shapeless_placeholder(x, axis, name):
"""
Make the static shape of a tensor less specific.
If you want to feed to a tensor, the shape of the feed value must match
the tensor's static shape. This function creates a placeholder which
defaults to x if not fed, but has a less specific static shape ... | Make the static shape of a tensor less specific.
If you want to feed to a tensor, the shape of the feed value must match
the tensor's static shape. This function creates a placeholder which
defaults to x if not fed, but has a less specific static shape than x.
See also `tensorflow#5680 <https://github.... |
def _get_attributes(schema, location):
"""Return the schema's children, filtered by location."""
schema = DottedNameResolver(__name__).maybe_resolve(schema)
def _filter(attr):
if not hasattr(attr, "location"):
valid_location = 'body' in location
else:
... | Return the schema's children, filtered by location. |
def _save_vocab_file(vocab_file, subtoken_list):
"""Save subtokens to file."""
with tf.gfile.Open(vocab_file, mode="w") as f:
for subtoken in subtoken_list:
f.write("'%s'\n" % _unicode_to_native(subtoken)) | Save subtokens to file. |
def _set_MM(self, v, load=False):
"""
Setter method for MM, mapped from YANG variable /system_monitor/MM (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_MM is considered as a private
method. Backends looking to populate this variable should
do so via ... | Setter method for MM, mapped from YANG variable /system_monitor/MM (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_MM is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_MM() directly. |
def read(self, buf=None, n=None):
"""Reads a specified number of ``bytes`` from this stream.
arg: n (cardinal): the number of ``bytes`` to read
return: (integer) - the ``bytes`` read
raise: IllegalState - this stream has been closed or
``at_end_of_stream()`` is ``tru... | Reads a specified number of ``bytes`` from this stream.
arg: n (cardinal): the number of ``bytes`` to read
return: (integer) - the ``bytes`` read
raise: IllegalState - this stream has been closed or
``at_end_of_stream()`` is ``true``
raise: InvalidArgument - the siz... |
def with_empty_graph(cls, molecule, name="bonds",
edge_weight_name=None,
edge_weight_units=None):
"""
Constructor for MoleculeGraph, returns a MoleculeGraph
object with an empty graph (no edges, only nodes defined
that correspond to Sites... | Constructor for MoleculeGraph, returns a MoleculeGraph
object with an empty graph (no edges, only nodes defined
that correspond to Sites in Molecule).
:param molecule (Molecule):
:param name (str): name of graph, e.g. "bonds"
:param edge_weight_name (str): name of edge weights,
... |
def QA_fetch_get_future_transaction_realtime(code, ip=None, port=None):
'期货历史成交分笔'
ip, port = get_extensionmarket_ip(ip, port)
apix = TdxExHq_API()
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_lis... | 期货历史成交分笔 |
def authenticate(self, session: Session, listener):
"""
This method call the authenticate method on registered plugins to test user authentication.
User is considered authenticated if all plugins called returns True.
Plugins authenticate() method are supposed to return :
- True ... | This method call the authenticate method on registered plugins to test user authentication.
User is considered authenticated if all plugins called returns True.
Plugins authenticate() method are supposed to return :
- True if user is authentication succeed
- False if user authenticatio... |
def _set_new_connection(self, conn):
"""
Replace existing connection (if there is one) and close it.
"""
with self._lock:
old = self._connection
self._connection = conn
if old:
log.debug("[control connection] Closing old connection %r, replaci... | Replace existing connection (if there is one) and close it. |
def _construct(self, strings_collection):
"""
Naive generalized suffix tree construction algorithm,
with quadratic [O(n_1^2 + ... + n_m^2)] worst-case time complexity,
where m is the number of strings in collection.
"""
# 0. Add a unique character to eac... | Naive generalized suffix tree construction algorithm,
with quadratic [O(n_1^2 + ... + n_m^2)] worst-case time complexity,
where m is the number of strings in collection. |
def _krige(X, y, coords, variogram_function,
variogram_model_parameters, coordinates_type):
"""Sets up and solves the ordinary kriging system for the given
coordinate pair. This function is only used for the statistics calculations.
Parameters
----------
X: ndarray
float array [n... | Sets up and solves the ordinary kriging system for the given
coordinate pair. This function is only used for the statistics calculations.
Parameters
----------
X: ndarray
float array [n_samples, n_dim], the input array of coordinates
y: ndarray
float array [n_samples], the input arr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.