code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def write_config(config, config_path=CONFIG_PATH):
"""Write the config to the output path.
Creates the necessary directories if they aren't there.
Args:
config (configparser.ConfigParser): A ConfigParser.
"""
if not os.path.exists(config_path):
os.makedirs(os.path.dirname(config_pat... | Write the config to the output path.
Creates the necessary directories if they aren't there.
Args:
config (configparser.ConfigParser): A ConfigParser. |
def IsKeyPressed(key: int) -> bool:
"""
key: int, a value in class `Keys`.
Return bool.
"""
state = ctypes.windll.user32.GetAsyncKeyState(key)
return bool(state & 0x8000) | key: int, a value in class `Keys`.
Return bool. |
def load_all_modules_in_packages(package_or_set_of_packages):
"""
Recursively loads all modules from a package object, or set of package objects
:param package_or_set_of_packages: package object, or iterable of package objects
:return: list of all unique modules discovered by the function
"""
i... | Recursively loads all modules from a package object, or set of package objects
:param package_or_set_of_packages: package object, or iterable of package objects
:return: list of all unique modules discovered by the function |
def predict(self, X, raw_score=False, num_iteration=None,
pred_leaf=False, pred_contrib=False, **kwargs):
"""Return the predicted value for each sample.
Parameters
----------
X : array-like or sparse matrix of shape = [n_samples, n_features]
Input features ma... | Return the predicted value for each sample.
Parameters
----------
X : array-like or sparse matrix of shape = [n_samples, n_features]
Input features matrix.
raw_score : bool, optional (default=False)
Whether to predict raw scores.
num_iteration : int or No... |
def present(name,
clients=None,
hosts=None,
options=None,
exports='/etc/exports'):
'''
Ensure that the named export is present with the given options
name
The export path to configure
clients
A list of hosts and the options applied to the... | Ensure that the named export is present with the given options
name
The export path to configure
clients
A list of hosts and the options applied to them.
This option may not be used in combination with
the 'hosts' or 'options' shortcuts.
.. code-block:: yaml
- cli... |
def create_poi_gdf(polygon=None, amenities=None, north=None, south=None, east=None, west=None):
"""
Parse GeoDataFrames from POI json that was returned by Overpass API.
Parameters
----------
polygon : shapely Polygon or MultiPolygon
geographic shape to fetch the POIs within
amenities: l... | Parse GeoDataFrames from POI json that was returned by Overpass API.
Parameters
----------
polygon : shapely Polygon or MultiPolygon
geographic shape to fetch the POIs within
amenities: list
List of amenities that will be used for finding the POIs from the selected area.
See av... |
def get_all_synDelays(self):
"""
Create and load arrays of connection delays per connection on this rank
Get random normally distributed synaptic delays,
returns dict of nested list of same shape as SpCells.
Delays are rounded to dt.
This function takes no kwargs.
... | Create and load arrays of connection delays per connection on this rank
Get random normally distributed synaptic delays,
returns dict of nested list of same shape as SpCells.
Delays are rounded to dt.
This function takes no kwargs.
Parameters
----------
None
... |
def remove(name=None, pkgs=None, **kwargs):
'''
Removes packages with ``brew uninstall``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if th... | Removes packages with ``brew uninstall``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
... |
def _EntriesGenerator(self):
"""Retrieves directory entries.
Since a directory can contain a vast number of entries using
a generator is more memory efficient.
Yields:
TARPathSpec: TAR path specification.
"""
location = getattr(self.path_spec, 'location', None)
if location and locat... | Retrieves directory entries.
Since a directory can contain a vast number of entries using
a generator is more memory efficient.
Yields:
TARPathSpec: TAR path specification. |
def get_connection(self, alias='default'):
"""
Retrieve a connection, construct it if necessary (only configuration
was passed to us). If a non-string alias has been passed through we
assume it's already a client instance and will just return it as-is.
Raises ``KeyError`` if no ... | Retrieve a connection, construct it if necessary (only configuration
was passed to us). If a non-string alias has been passed through we
assume it's already a client instance and will just return it as-is.
Raises ``KeyError`` if no client (or its definition) is registered
under the alia... |
def invalid_request_content(message):
"""
Creates a Lambda Service InvalidRequestContent Response
Parameters
----------
message str
Message to be added to the body of the response
Returns
-------
Flask.Response
A response object r... | Creates a Lambda Service InvalidRequestContent Response
Parameters
----------
message str
Message to be added to the body of the response
Returns
-------
Flask.Response
A response object representing the InvalidRequestContent Error |
def memoize(method):
"""
A decorator for functions of sources which memoize the results of the last _CACHE_SIZE calls,
:param method: method to be memoized
:return: the decorated method
"""
cache = method.cache = collections.OrderedDict()
# Put these two methods in the local space (faster... | A decorator for functions of sources which memoize the results of the last _CACHE_SIZE calls,
:param method: method to be memoized
:return: the decorated method |
def fromdescriptor(cls, desc):
"""
Create a :class:`~manticore.core.workspace.Store` instance depending on the descriptor.
Valid descriptors:
* fs:<path>
* redis:<hostname>:<port>
* mem:
:param str desc: Store descriptor
:return: Store instance
... | Create a :class:`~manticore.core.workspace.Store` instance depending on the descriptor.
Valid descriptors:
* fs:<path>
* redis:<hostname>:<port>
* mem:
:param str desc: Store descriptor
:return: Store instance |
def create(cls, **kwargs):
"""
Create an instance of this model in the database.
Takes the model column values as keyword arguments. Setting a value to
`None` is equivalent to running a CQL `DELETE` on that column.
Returns the instance.
"""
extra_columns = set(k... | Create an instance of this model in the database.
Takes the model column values as keyword arguments. Setting a value to
`None` is equivalent to running a CQL `DELETE` on that column.
Returns the instance. |
def a(text, mode='exec', indent=' ', file=None):
"""
Interactive convenience for displaying the AST of a code string.
Writes a pretty-formatted AST-tree to `file`.
Parameters
----------
text : str
Text of Python code to render as AST.
mode : {'exec', 'eval'}, optional
Mode... | Interactive convenience for displaying the AST of a code string.
Writes a pretty-formatted AST-tree to `file`.
Parameters
----------
text : str
Text of Python code to render as AST.
mode : {'exec', 'eval'}, optional
Mode for `ast.parse`. Default is 'exec'.
indent : str, option... |
def disable_jt_ha(self, active_name):
"""
Disable high availability for a MR JobTracker active-standby pair.
@param active_name: name of the JobTracker that will be active after
the disable operation. The other JobTracker and
Failover Controllers will be remo... | Disable high availability for a MR JobTracker active-standby pair.
@param active_name: name of the JobTracker that will be active after
the disable operation. The other JobTracker and
Failover Controllers will be removed.
@return: Reference to the submitted comma... |
def add_regression_events(obj, events, targets, weights=None, test=False):
"""Add regression events to a TMVA::Factory or TMVA::DataLoader from NumPy arrays.
Parameters
----------
obj : TMVA::Factory or TMVA::DataLoader
A TMVA::Factory or TMVA::DataLoader (TMVA's interface as of ROOT
6.... | Add regression events to a TMVA::Factory or TMVA::DataLoader from NumPy arrays.
Parameters
----------
obj : TMVA::Factory or TMVA::DataLoader
A TMVA::Factory or TMVA::DataLoader (TMVA's interface as of ROOT
6.07/04) instance with variables already
booked in exactly the same order as... |
def run_diff_umap(self,use_rep='X_pca', metric='euclidean', n_comps=15,
method='gauss', **kwargs):
"""
Experimental -- running UMAP on the diffusion components
"""
import scanpy.api as sc
sc.pp.neighbors(self.adata,use_rep=use_rep,n_neig... | Experimental -- running UMAP on the diffusion components |
def _group_kwargs_to_options(cls, obj, kwargs):
"Format option group kwargs into canonical options format"
groups = Options._option_groups
if set(kwargs.keys()) - set(groups):
raise Exception("Keyword options %s must be one of %s" % (groups,
','.join(repr... | Format option group kwargs into canonical options format |
def generate_contains(self):
"""
Means that array must contain at least one defined item.
.. code-block:: python
{
'contains': {
'type': 'number',
},
}
Valid array is any with at least one number.
"""
... | Means that array must contain at least one defined item.
.. code-block:: python
{
'contains': {
'type': 'number',
},
}
Valid array is any with at least one number. |
def _set_sfp(self, v, load=False):
"""
Setter method for sfp, mapped from YANG variable /rbridge_id/system_monitor/sfp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_sfp is considered as a private
method. Backends looking to populate this variable should... | Setter method for sfp, mapped from YANG variable /rbridge_id/system_monitor/sfp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_sfp is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sfp() direc... |
def resetTimeout(self):
"""Reset the timeout count down"""
if self.__timeoutCall is not None and self.timeOut is not None:
self.__timeoutCall.reset(self.timeOut) | Reset the timeout count down |
def delete_merged_branches(self, **kwargs):
"""Delete merged branches.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server failed to perform the ... | Delete merged branches.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server failed to perform the request |
def sample_from_prior(self):
""" Sample elements of the stochastic transition matrix from the prior
distribution, based on gradable adjectives. """
# simple_path_dict caches the results of the graph traversal that finds
# simple paths between pairs of nodes, so that it doesn't have to b... | Sample elements of the stochastic transition matrix from the prior
distribution, based on gradable adjectives. |
def _parse_fc(self, f, natom, dim):
"""Parse force constants part
Physical unit of force cosntants in the file is Ry/au^2.
"""
ndim = np.prod(dim)
fc = np.zeros((natom, natom * ndim, 3, 3), dtype='double', order='C')
for k, l, i, j in np.ndindex((3, 3, natom, natom)):
... | Parse force constants part
Physical unit of force cosntants in the file is Ry/au^2. |
def make_valid_pyclipper(shape):
"""
Use the pyclipper library to "union" a polygon on its own. This operation
uses the even-odd rule to determine which points are in the interior of
the polygon, and can reconstruct the orientation of the polygon from that.
The pyclipper library is robust, and uses ... | Use the pyclipper library to "union" a polygon on its own. This operation
uses the even-odd rule to determine which points are in the interior of
the polygon, and can reconstruct the orientation of the polygon from that.
The pyclipper library is robust, and uses integer coordinates, so should
not produc... |
def resp_set_infrared(self, resp, infrared_brightness=None):
"""Default callback for set_infrared/get_infrared
"""
if infrared_brightness is not None:
self.infrared_brightness = infrared_brightness
elif resp:
self.infrared_brightness = resp.infrared_brightness | Default callback for set_infrared/get_infrared |
def get_root_list(class_path=None, cursor=None, count=50):
"""Gets a list root Pipelines.
Args:
class_path: Optional. If supplied, only return root Pipelines with the
given class_path. By default all root pipelines are returned.
cursor: Optional. When supplied, the cursor returned from the last call ... | Gets a list root Pipelines.
Args:
class_path: Optional. If supplied, only return root Pipelines with the
given class_path. By default all root pipelines are returned.
cursor: Optional. When supplied, the cursor returned from the last call to
get_root_list which indicates where to pick up.
cou... |
def _HandleLegacy(self, args, token=None):
"""Retrieves the clients for a hunt."""
hunt_urn = args.hunt_id.ToURN()
hunt_obj = aff4.FACTORY.Open(
hunt_urn, aff4_type=implementation.GRRHunt, token=token)
clients_by_status = hunt_obj.GetClientsByStatus()
hunt_clients = clients_by_status[args.c... | Retrieves the clients for a hunt. |
def copyto(self,
new_abspath=None,
new_dirpath=None,
new_dirname=None,
new_basename=None,
new_fname=None,
new_ext=None,
overwrite=False,
makedirs=False):
"""
Copy this file to other pl... | Copy this file to other place. |
def dst_addr(self):
"""
The packet destination address.
"""
try:
return socket.inet_ntop(self._af, self.raw[self._dst_addr].tobytes())
except (ValueError, socket.error):
pass | The packet destination address. |
def exclude_functions(self, *funcs):
"""
Excludes the contributions from the following functions.
"""
for f in funcs:
f.exclude = True
run_time_s = sum(0 if s.exclude else s.own_time_s for s in self.stats)
cProfileFuncStat.run_time_s = run_time_s | Excludes the contributions from the following functions. |
def clear_jobs(self, recursive=True):
"""Clear the self.jobs dictionary that contains information
about jobs associated with this `ScatterGather`
If recursive is True this will include jobs from all internal `Link`
"""
if recursive:
self._scatter_link.clear_jobs(recu... | Clear the self.jobs dictionary that contains information
about jobs associated with this `ScatterGather`
If recursive is True this will include jobs from all internal `Link` |
def get_content_html(request):
"""Retrieve content as HTML using the ident-hash (uuid@version)."""
result = _get_content_json()
media_type = result['mediaType']
if media_type == COLLECTION_MIMETYPE:
content = tree_to_html(result['tree'])
else:
content = result['content']
resp =... | Retrieve content as HTML using the ident-hash (uuid@version). |
def parent_subfolders(self, ident, ann_id=None):
'''An unordered generator of parent subfolders for ``ident``.
``ident`` can either be a ``content_id`` or a tuple of
``(content_id, subtopic_id)``.
Parent subfolders are limited to the annotator id given.
:param ident: identifie... | An unordered generator of parent subfolders for ``ident``.
``ident`` can either be a ``content_id`` or a tuple of
``(content_id, subtopic_id)``.
Parent subfolders are limited to the annotator id given.
:param ident: identifier
:type ident: ``str`` or ``(str, str)``
:pa... |
def zoom_leftdown(self, event=None):
"""leftdown event handler for zoom mode"""
self.x_lastmove, self.y_lastmove = None, None
self.zoom_ini = (event.x, event.y, event.xdata, event.ydata)
self.report_leftdown(event=event) | leftdown event handler for zoom mode |
def make_ranges(cls, lines):
"""Convert list of lines into list of line range tuples.
Only will be called if there is one or more entries in the list. Single
lines, will be coverted into tuple with same line.
"""
start_line = last_line = lines.pop(0)
ranges = []
... | Convert list of lines into list of line range tuples.
Only will be called if there is one or more entries in the list. Single
lines, will be coverted into tuple with same line. |
def get_access_token(tenant_id, application_id, application_secret):
'''get an Azure access token using the adal library.
Args:
tenant_id (str): Tenant id of the user's account.
application_id (str): Application id of a Service Principal account.
application_secret (str): Application se... | get an Azure access token using the adal library.
Args:
tenant_id (str): Tenant id of the user's account.
application_id (str): Application id of a Service Principal account.
application_secret (str): Application secret (password) of the Service Principal account.
Returns:
An A... |
def EnumKey(key, index):
"""This calls the Windows RegEnumKeyEx function in a Unicode safe way."""
regenumkeyex = advapi32["RegEnumKeyExW"]
regenumkeyex.restype = ctypes.c_long
regenumkeyex.argtypes = [
ctypes.c_void_p, ctypes.wintypes.DWORD, ctypes.c_wchar_p, LPDWORD,
LPDWORD, ctypes.c_wchar_p, LPD... | This calls the Windows RegEnumKeyEx function in a Unicode safe way. |
def do_pyscript(self, args: argparse.Namespace) -> bool:
"""Run a Python script file inside the console"""
script_path = os.path.expanduser(args.script_path)
py_return = False
# Save current command line arguments
orig_args = sys.argv
try:
# Overwrite sys.ar... | Run a Python script file inside the console |
def log(self, msg):
""" Log Normal Messages """
self._execActions('log', msg)
msg = self._execFilters('log', msg)
self._processMsg('log', msg)
self._sendMsg('log', msg) | Log Normal Messages |
def human_uuid():
"""Returns a good UUID for using as a human readable string."""
return base64.b32encode(
hashlib.sha1(uuid.uuid4().bytes).digest()).lower().strip('=') | Returns a good UUID for using as a human readable string. |
def RECEIVE_MESSAGE(op):
'''
This is sample for implement BOT in LINE group
Invite your BOT to group, then BOT will auto accept your invitation
Command availabe :
> hi
> /author
'''
msg = op.message
text = msg.text
msg_id = msg.id
receiver = msg.to
... | This is sample for implement BOT in LINE group
Invite your BOT to group, then BOT will auto accept your invitation
Command availabe :
> hi
> /author |
def clip(self, lower=None, upper=None, axis=None, inplace=False,
*args, **kwargs):
"""
Trim values at input threshold(s).
Assigns values outside boundary to boundary values. Thresholds
can be singular values or array like, and in the latter case
the clipping is perf... | Trim values at input threshold(s).
Assigns values outside boundary to boundary values. Thresholds
can be singular values or array like, and in the latter case
the clipping is performed element-wise in the specified axis.
Parameters
----------
lower : float or array_like... |
def has_table(self, name):
"""Return ``True`` if the table *name* exists in the database."""
return len(self.sql("SELECT name FROM sqlite_master WHERE type='table' AND name=?",
parameters=(name,), asrecarray=False, cache=False)) > 0 | Return ``True`` if the table *name* exists in the database. |
def get_assessment(self, assessment):
"""
To get Assessment by id
"""
response = self.http.get('/Assessment/' + str(assessment))
assessment = Schemas.Assessment(assessment=response)
return assessment | To get Assessment by id |
def generateSetupFile(self, outpath='.', egg=False):
"""
Generates the setup file for this builder.
"""
outpath = os.path.abspath(outpath)
outfile = os.path.join(outpath, 'setup.py')
opts = {
'name': self.name(),
'distname': self.distributionName(... | Generates the setup file for this builder. |
def validate_transaction_schema(tx):
"""Validate a transaction dict.
TX_SCHEMA_COMMON contains properties that are common to all types of
transaction. TX_SCHEMA_[TRANSFER|CREATE] add additional constraints on top.
"""
_validate_schema(TX_SCHEMA_COMMON, tx)
if tx['operation'] == 'TRANSFER':
... | Validate a transaction dict.
TX_SCHEMA_COMMON contains properties that are common to all types of
transaction. TX_SCHEMA_[TRANSFER|CREATE] add additional constraints on top. |
def recover_all(lbn, profile='default'):
'''
Set the all the workers in lbn to recover and activate them if they are not
CLI Examples:
.. code-block:: bash
salt '*' modjk.recover_all loadbalancer1
salt '*' modjk.recover_all loadbalancer1 other-profile
'''
ret = {}
config ... | Set the all the workers in lbn to recover and activate them if they are not
CLI Examples:
.. code-block:: bash
salt '*' modjk.recover_all loadbalancer1
salt '*' modjk.recover_all loadbalancer1 other-profile |
def admin(self, server=None):
"""
Get the admin information.
Optional arguments:
* server=None - Get admin information for -
server instead of the current server.
"""
with self.lock:
if not server:
self.send('ADMIN')
els... | Get the admin information.
Optional arguments:
* server=None - Get admin information for -
server instead of the current server. |
def _empty_value(self, formattype):
'''
returns default empty value
:param formattype:
:param buff:
:param start:
:param end:
'''
if formattype.value.idx <= FormatType.BIN_32.value.idx: # @UndefinedVariable
return b''
elif formatt... | returns default empty value
:param formattype:
:param buff:
:param start:
:param end: |
def load(filename, **kwargs):
"""
Loads the given t7 file using default settings; kwargs are forwarded
to `T7Reader`.
"""
with open(filename, 'rb') as f:
reader = T7Reader(f, **kwargs)
return reader.read_obj() | Loads the given t7 file using default settings; kwargs are forwarded
to `T7Reader`. |
def public_ip_address_create_or_update(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Create or update a public IP address within a specified resource group.
:param name: The name of the public IP address to create.
:param resource_group: The resource group name assigned to the
... | .. versionadded:: 2019.2.0
Create or update a public IP address within a specified resource group.
:param name: The name of the public IP address to create.
:param resource_group: The resource group name assigned to the
public IP address.
CLI Example:
.. code-block:: bash
salt-... |
def backward_sampling(self, M, linear_cost=False, return_ar=False):
"""Generate trajectories using the FFBS (forward filtering backward
sampling) algorithm.
Arguments
---------
M: int
number of trajectories we want to generate
linear_cost: bool
... | Generate trajectories using the FFBS (forward filtering backward
sampling) algorithm.
Arguments
---------
M: int
number of trajectories we want to generate
linear_cost: bool
if set to True, the O(N) version is used, see below.
return_ar: bool ... |
def compare(molecules, ensemble_lookup, options):
"""
compare stuff
:param molecules:
:param ensemble_lookup:
:param options:
:return:
"""
print(" Analyzing differences ... ")
print('')
sort_order = classification.get_sort_order(molecules)
ensemble1 = sorted(ensemble_lookup... | compare stuff
:param molecules:
:param ensemble_lookup:
:param options:
:return: |
def execute_job(job, app=Injected, task_router=Injected):
# type: (Job, Zsl, TaskRouter) -> dict
"""Execute a job.
:param job: job to execute
:type job: Job
:param app: service application instance, injected
:type app: ServiceApplication
:param task_router: task router instance, injected
... | Execute a job.
:param job: job to execute
:type job: Job
:param app: service application instance, injected
:type app: ServiceApplication
:param task_router: task router instance, injected
:type task_router: TaskRouter
:return: task result
:rtype: dict |
def load_categories(self, max_pages=30):
"""
Load all WordPress categories from the given site.
:param max_pages: kill counter to avoid infinite looping
:return: None
"""
logger.info("loading categories")
# clear them all out so we don't get dupes if requested
... | Load all WordPress categories from the given site.
:param max_pages: kill counter to avoid infinite looping
:return: None |
def p_additional_catches(p):
'''additional_catches : additional_catches CATCH LPAREN fully_qualified_class_name VARIABLE RPAREN LBRACE inner_statement_list RBRACE
| empty'''
if len(p) == 10:
p[0] = p[1] + [ast.Catch(p[4], ast.Variable(p[5], lineno=p.lineno(5)),
... | additional_catches : additional_catches CATCH LPAREN fully_qualified_class_name VARIABLE RPAREN LBRACE inner_statement_list RBRACE
| empty |
def warning(self, text):
""" Ajout d'un message de log de type WARN """
self.logger.warning("{}{}".format(self.message_prefix, text)) | Ajout d'un message de log de type WARN |
def _packed_data(self):
'''
Returns the bit-packed data extracted from the data file. This is not so useful to analyze.
Use the complex_data method instead.
'''
header = self.header()
packed_data = np.frombuffer(self.data, dtype=np.int8)\
.reshape((header['number_of_half_frames'], heade... | Returns the bit-packed data extracted from the data file. This is not so useful to analyze.
Use the complex_data method instead. |
def check_base_required_attributes(self, dataset):
'''
Check the global required and highly recommended attributes for 1.1 templates. These go an extra step besides
just checking that they exist.
:param netCDF4.Dataset dataset: An open netCDF dataset
:Conventions = "CF-1.6" ; ... | Check the global required and highly recommended attributes for 1.1 templates. These go an extra step besides
just checking that they exist.
:param netCDF4.Dataset dataset: An open netCDF dataset
:Conventions = "CF-1.6" ; //......................................... REQUIRED - Always try to... |
def extract(filename_url_or_filelike):
"""A more precise algorithm over the original eatiht algorithm
"""
pars_tnodes = get_parent_xpaths_and_textnodes(filename_url_or_filelike)
#[iterable, cardinality, ttl across iterable, avg across iterable.])
calc_across_paths_textnodes(pars_tnodes)
... | A more precise algorithm over the original eatiht algorithm |
def list_devices(names=None, continue_from=None, **kwargs):
"""List devices in settings file and print versions"""
if not names:
names = [device for device, _type in settings.GOLDEN_DEVICES if _type == 'OpenThread']
if continue_from:
continue_from = names.index(continue_from)
else:
... | List devices in settings file and print versions |
def QA_indicator_OSC(DataFrame, N=20, M=6):
"""变动速率线
震荡量指标OSC,也叫变动速率线。属于超买超卖类指标,是从移动平均线原理派生出来的一种分析指标。
它反应当日收盘价与一段时间内平均收盘价的差离值,从而测出股价的震荡幅度。
按照移动平均线原理,根据OSC的值可推断价格的趋势,如果远离平均线,就很可能向平均线回归。
"""
C = DataFrame['close']
OS = (C - MA(C, N)) * 100
MAOSC = EMA(OS, M)
DICT = {'OSC': OS, 'MAOS... | 变动速率线
震荡量指标OSC,也叫变动速率线。属于超买超卖类指标,是从移动平均线原理派生出来的一种分析指标。
它反应当日收盘价与一段时间内平均收盘价的差离值,从而测出股价的震荡幅度。
按照移动平均线原理,根据OSC的值可推断价格的趋势,如果远离平均线,就很可能向平均线回归。 |
def setDateTimeEnd(self, dtime):
"""
Sets the endiing date time for this gantt chart.
:param dtime | <QDateTime>
"""
self._dateEnd = dtime.date()
self._timeEnd = dtime.time()
self._allDay = False | Sets the endiing date time for this gantt chart.
:param dtime | <QDateTime> |
def list_objects_access(f):
"""Access to listObjects() controlled by settings.PUBLIC_OBJECT_LIST."""
@functools.wraps(f)
def wrapper(request, *args, **kwargs):
if not django.conf.settings.PUBLIC_OBJECT_LIST:
trusted(request)
return f(request, *args, **kwargs)
return wrapper | Access to listObjects() controlled by settings.PUBLIC_OBJECT_LIST. |
def vertical_scroll(self, image, padding=True):
"""Returns a list of images which appear to scroll from top to bottom
down the input image when displayed on the LED matrix in order.
The input image is not limited to being 8x16. If the input image is
largerthan this, then all rows will b... | Returns a list of images which appear to scroll from top to bottom
down the input image when displayed on the LED matrix in order.
The input image is not limited to being 8x16. If the input image is
largerthan this, then all rows will be scrolled through but only the
left-most 8 columns... |
def list_replace(iterable, src, dst):
"""
Thanks to "EyDu":
http://www.python-forum.de/viewtopic.php?f=1&t=34539 (de)
>>> list_replace([1,2,3], (1,2), "X")
['X', 3]
>>> list_replace([1,2,3,4], (2,3), 9)
[1, 9, 4]
>>> list_replace([1,2,3], (2,), [9,8])
[1, 9, 8, 3]
... | Thanks to "EyDu":
http://www.python-forum.de/viewtopic.php?f=1&t=34539 (de)
>>> list_replace([1,2,3], (1,2), "X")
['X', 3]
>>> list_replace([1,2,3,4], (2,3), 9)
[1, 9, 4]
>>> list_replace([1,2,3], (2,), [9,8])
[1, 9, 8, 3]
>>> list_replace([1,2,3,4,5], (2,3,4), "X... |
def liveReceivers(receivers):
"""Filter sequence of receivers to get resolved, live receivers
This is a generator which will iterate over
the passed sequence, checking for weak references
and resolving them, then returning all live
receivers.
"""
for receiver in receivers:
if isinst... | Filter sequence of receivers to get resolved, live receivers
This is a generator which will iterate over
the passed sequence, checking for weak references
and resolving them, then returning all live
receivers. |
def set_setpoint(self, setpointvalue):
"""Set the setpoint.
Args:
setpointvalue (float): Setpoint [most often in degrees]
"""
_checkSetpointValue( setpointvalue, self.setpoint_max )
self.write_register( 4097, setpointvalue, 1) | Set the setpoint.
Args:
setpointvalue (float): Setpoint [most often in degrees] |
def fmt(self, po_file, mo_file):
"""将 po 文件转换成 mo 文件。
:param string po_file: 待转换的 po 文件路径。
:param string mo_file: 目标 mo 文件的路径。
"""
if not os.path.exists(po_file):
slog.error('The PO file [%s] is non-existen!'%po_file)
return
txt = subprocess.chec... | 将 po 文件转换成 mo 文件。
:param string po_file: 待转换的 po 文件路径。
:param string mo_file: 目标 mo 文件的路径。 |
def start(host, port, profiler_stats, dont_start_browser, debug_mode):
"""Starts HTTP server with specified parameters.
Args:
host: Server host name.
port: Server port.
profiler_stats: A dict with collected program stats.
dont_start_browser: Whether to open browser after profili... | Starts HTTP server with specified parameters.
Args:
host: Server host name.
port: Server port.
profiler_stats: A dict with collected program stats.
dont_start_browser: Whether to open browser after profiling.
debug_mode: Whether to redirect stderr to /dev/null. |
def get_assessments_taken_by_banks(self, bank_ids):
"""Gets the list of ``AssessmentTaken`` objects corresponding to a list of ``Banks``.
arg: bank_ids (osid.id.IdList): list of bank ``Ids``
return: (osid.assessment.AssessmentTakenList) - list of
assessments taken
rai... | Gets the list of ``AssessmentTaken`` objects corresponding to a list of ``Banks``.
arg: bank_ids (osid.id.IdList): list of bank ``Ids``
return: (osid.assessment.AssessmentTakenList) - list of
assessments taken
raise: NullArgument - ``bank_ids`` is ``null``
raise: Op... |
def get_driver(self, desired_capabilities=None):
"""
Creates a Selenium driver on the basis of the configuration file
upon which this object was created.
:param desired_capabilities: Capabilities that the caller
desires to override. This have priority over those
... | Creates a Selenium driver on the basis of the configuration file
upon which this object was created.
:param desired_capabilities: Capabilities that the caller
desires to override. This have priority over those
capabilities that are set by the configuration file passed
... |
def update_snapshots(self):
"""Update list of EBS Snapshots for the account / region
Returns:
`None`
"""
self.log.debug('Updating EBSSnapshots for {}/{}'.format(self.account.account_name, self.region))
ec2 = self.session.resource('ec2', region_name=self.region)
... | Update list of EBS Snapshots for the account / region
Returns:
`None` |
def humanize_speed(c_per_sec):
"""convert a speed in counts per second to counts per [s, min, h, d], choosing the smallest value greater zero.
"""
scales = [60, 60, 24]
units = ['c/s', 'c/min', 'c/h', 'c/d']
speed = c_per_sec
i = 0
if speed > 0:
while (speed < 1) and (i < len(scales)... | convert a speed in counts per second to counts per [s, min, h, d], choosing the smallest value greater zero. |
def get_response(self, statement=None, **kwargs):
"""
Return the bot's response based on the input.
:param statement: An statement object or string.
:returns: A response to the input.
:rtype: Statement
:param additional_response_selection_parameters: Parameters to pass ... | Return the bot's response based on the input.
:param statement: An statement object or string.
:returns: A response to the input.
:rtype: Statement
:param additional_response_selection_parameters: Parameters to pass to the
chat bot's logic adapters to control response selec... |
def publish_scene_add(self, scene_id, animation_id, name, color, velocity, config):
"""publish added scene"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_add(self.sequence_number, scene_id, animation_id, name, color, velocity, config))
return self.se... | publish added scene |
def replace_each(text, items, count=None, strip=False):
'''
Like ``replace``, where each occurrence in ``items`` is a 2-tuple of
``(old, new)`` pair.
'''
for a,b in items:
text = replace(text, a, b, count=count, strip=strip)
return text | Like ``replace``, where each occurrence in ``items`` is a 2-tuple of
``(old, new)`` pair. |
def set_colors_in_grid(self, some_colors_in_grid):
"""Same as :meth:`set_color_in_grid` but with a collection of
colors in grid.
:param iterable some_colors_in_grid: a collection of colors in grid for
:meth:`set_color_in_grid`
"""
for color_in_grid in some_colors_in_gr... | Same as :meth:`set_color_in_grid` but with a collection of
colors in grid.
:param iterable some_colors_in_grid: a collection of colors in grid for
:meth:`set_color_in_grid` |
def parse_geonames_data(lines_iterator):
"""
Parses countries table data from geonames.org, updating or adding records as needed.
currency_symbol is not part of the countries table and is supplemented using the data
obtained from the link provided in the countries table.
:type lines_iterator: collec... | Parses countries table data from geonames.org, updating or adding records as needed.
currency_symbol is not part of the countries table and is supplemented using the data
obtained from the link provided in the countries table.
:type lines_iterator: collections.iterable
:return: num_updated: int, num_cre... |
def get_provider(name, creds):
"""
Generates and memoizes a :class:`~bang.providers.provider.Provider` object
for the given name.
:param str name: The provider name, as given in the config stanza. This
token is used to find the
appropriate :class:`~bang.providers.provider.Provider`.
... | Generates and memoizes a :class:`~bang.providers.provider.Provider` object
for the given name.
:param str name: The provider name, as given in the config stanza. This
token is used to find the
appropriate :class:`~bang.providers.provider.Provider`.
:param dict creds: The credentials dic... |
def get_params_from_func(func: Callable, signature: Signature=None) -> Params:
"""Gets all parameters from a function signature.
:param func: The function to inspect.
:param signature: An inspect.Signature instance.
:returns: A named tuple containing information about all, optional,
required an... | Gets all parameters from a function signature.
:param func: The function to inspect.
:param signature: An inspect.Signature instance.
:returns: A named tuple containing information about all, optional,
required and logic function parameters. |
def _over_resizer(self, x, y):
"Returns True if mouse is over a resizer"
over_resizer = False
c = self.canvas
ids = c.find_overlapping(x, y, x, y)
if ids:
o = ids[0]
tags = c.gettags(o)
if 'resizer' in tags:
over_resizer = True... | Returns True if mouse is over a resizer |
def query(self, query):
'''Returns a sequence of objects matching criteria expressed in `query`'''
cursor = Cursor(query, self.shard_query_generator(query))
cursor.apply_order() # ordering sharded queries is expensive (no generator)
return cursor | Returns a sequence of objects matching criteria expressed in `query` |
def graph_data_on_the_same_graph(list_of_plots, output_directory, resource_path, output_filename):
"""
graph_data_on_the_same_graph: put a list of plots on the same graph: currently it supports CDF
"""
maximum_yvalue = -float('inf')
minimum_yvalue = float('inf')
plots = curate_plot_list(list_of_plots)
plo... | graph_data_on_the_same_graph: put a list of plots on the same graph: currently it supports CDF |
def match_variables(self, pattern, return_type='name'):
''' Return columns whose names match the provided regex pattern.
Args:
pattern (str): A regex pattern to match all variable names against.
return_type (str): What to return. Must be one of:
'name': Returns a... | Return columns whose names match the provided regex pattern.
Args:
pattern (str): A regex pattern to match all variable names against.
return_type (str): What to return. Must be one of:
'name': Returns a list of names of matching variables.
'variable': Re... |
def m_seg(p1, p2, rad, dist):
""" move segment by distance
Args:
p1, p2: point(x, y)
rad: relative direction angle(radian)
dist: distance
Return:
translated segment(p1, p2)
"""
v = vector(p1, p2)
m = unit(rotate(v, rad), dist)
return translate(p1, m), translate(p2, m) | move segment by distance
Args:
p1, p2: point(x, y)
rad: relative direction angle(radian)
dist: distance
Return:
translated segment(p1, p2) |
def _resolved_type(self):
"""Return the type for the columns, and a flag to indicate that the
column has codes."""
import datetime
self.type_ratios = {test: (float(self.type_counts[test]) / float(self.count)) if self.count else None
for test, testf in tests +... | Return the type for the columns, and a flag to indicate that the
column has codes. |
def _secondary_min(self):
"""Getter for the minimum series value"""
return (
self.secondary_range[0]
if (self.secondary_range
and self.secondary_range[0] is not None) else
(min(self._secondary_values) if self._secondary_values else None)
) | Getter for the minimum series value |
def swap_deployment(self, service_name, production, source_deployment):
'''
Initiates a virtual IP swap between the staging and production
deployment environments for a service. If the service is currently
running in the staging environment, it will be swapped to the
production e... | Initiates a virtual IP swap between the staging and production
deployment environments for a service. If the service is currently
running in the staging environment, it will be swapped to the
production environment. If it is running in the production
environment, it will be swapped to st... |
def model(self):
"""Initialize and cache MigrationHistory model."""
MigrateHistory._meta.database = self.database
MigrateHistory._meta.table_name = self.migrate_table
MigrateHistory._meta.schema = self.schema
MigrateHistory.create_table(True)
return MigrateHistory | Initialize and cache MigrationHistory model. |
def decryption(self, ciphertext, key):
"""
Builds a single cycle AES Decryption circuit
:param WireVector ciphertext: data to decrypt
:param WireVector key: AES key to use to encrypt (AES is symmetric)
:return: a WireVector containing the plaintext
"""
if len(cip... | Builds a single cycle AES Decryption circuit
:param WireVector ciphertext: data to decrypt
:param WireVector key: AES key to use to encrypt (AES is symmetric)
:return: a WireVector containing the plaintext |
def search(self, search_phrase, limit=None):
""" Finds datasets by search phrase.
Args:
search_phrase (str or unicode):
limit (int, optional): how many results to return. None means without limit.
Returns:
list of DatasetSearchResult instances.
"""
... | Finds datasets by search phrase.
Args:
search_phrase (str or unicode):
limit (int, optional): how many results to return. None means without limit.
Returns:
list of DatasetSearchResult instances. |
def _scale_tile(self, value, width, height):
"""Return the prescaled tile if already exists, otherwise scale and store it."""
try:
return self._scale_cache[value, width, height]
except KeyError:
tile = pygame.transform.smoothscale(self.tiles[value], (width, height))
... | Return the prescaled tile if already exists, otherwise scale and store it. |
def parseFilteringOptions(cls, args, filterRead=None, storeQueryIds=False):
"""
Parse command line options (added in C{addSAMFilteringOptions}.
@param args: The command line arguments, as returned by
C{argparse.parse_args}.
@param filterRead: A one-argument function that acc... | Parse command line options (added in C{addSAMFilteringOptions}.
@param args: The command line arguments, as returned by
C{argparse.parse_args}.
@param filterRead: A one-argument function that accepts a read
and returns C{None} if the read should be omitted in filtering
... |
def union(input, **params):
"""
Union transformation
:param input:
:param params:
:return:
"""
res = []
for col in input:
res.extend(input[col])
return res | Union transformation
:param input:
:param params:
:return: |
def enumiter(self, other, rmax, bunch=100000):
""" cross correlate with other, for all pairs
closer than rmax, iterate.
for r, i, j in A.enumiter(...):
...
where r is the distance, i and j are the original
input array index of the data.
... | cross correlate with other, for all pairs
closer than rmax, iterate.
for r, i, j in A.enumiter(...):
...
where r is the distance, i and j are the original
input array index of the data.
This uses a thread to convert from KDNode.enum. |
def get_extended_attribute(value):
""" [CFWS] 1*extended_attrtext [CFWS]
This is like the non-extended version except we allow % characters, so that
we can pick up an encoded value as a single string.
"""
# XXX: should we have an ExtendedAttribute TokenList?
attribute = Attribute()
if valu... | [CFWS] 1*extended_attrtext [CFWS]
This is like the non-extended version except we allow % characters, so that
we can pick up an encoded value as a single string. |
def updateRole(self, *args, **kwargs):
"""
Update Role
Update an existing role.
The caller's scopes must satisfy all of the new scopes being added, but
need not satisfy all of the role's existing scopes.
An update of a role that will generate an infinite expansion will... | Update Role
Update an existing role.
The caller's scopes must satisfy all of the new scopes being added, but
need not satisfy all of the role's existing scopes.
An update of a role that will generate an infinite expansion will result
in an error response.
This method ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.