Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
367,900 | def write_config(config, config_path=CONFIG_PATH):
if not os.path.exists(config_path):
os.makedirs(os.path.dirname(config_path))
with open(config_path, , encoding=) as f:
config.write(f) | Write the config to the output path.
Creates the necessary directories if they aren't there.
Args:
config (configparser.ConfigParser): A ConfigParser. |
367,901 | def IsKeyPressed(key: int) -> bool:
state = ctypes.windll.user32.GetAsyncKeyState(key)
return bool(state & 0x8000) | key: int, a value in class `Keys`.
Return bool. |
367,902 | def load_all_modules_in_packages(package_or_set_of_packages):
if isinstance(package_or_set_of_packages, types.ModuleType):
packages = [package_or_set_of_packages]
elif isinstance(package_or_set_of_packages, Iterable) and not isinstance(package_or_set_of_packages, (dict, str)):
packages = pa... | 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 |
367,903 | def predict(self, X, raw_score=False, num_iteration=None,
pred_leaf=False, pred_contrib=False, **kwargs):
if self._n_features is None:
raise LGBMNotFittedError("Estimator not fitted, call `fit` before exploiting the model.")
if not isinstance(X, (DataFrame, DataTable... | 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... |
367,904 | def present(name,
clients=None,
hosts=None,
options=None,
exports=):
hostsoptions10.0.2.0/24rw*.example.comrosubtree_check10.0.2.12310.0.2.0/24minion1.example.com*.example.com*rwsubtree_check
path = name
ret = {: name,
: {},
: None,
... | 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... |
367,905 | def create_poi_gdf(polygon=None, amenities=None, north=None, south=None, east=None, west=None):
responses = osm_poi_download(polygon=polygon, amenities=amenities, north=north, south=south, east=east, west=west)
coords = parse_nodes_coords(responses)
poi_nodes = {}
poi_ways = {}
... | 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... |
367,906 | def get_all_synDelays(self):
tic = time()
randomstate = np.random.get_state()
delays = {}
for cellindex in self.RANK_CELLINDICES:
np.random.seed(self.POPULATIONSEED + cellindex + 2*self.POPULATION_SIZE)
... | 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
... |
367,907 | def remove(name=None, pkgs=None, **kwargs):
***["foo", "bar"]
try:
pkg_params = __salt__[](
name, pkgs, **kwargs
)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
targets = [x for x in pkg_params if x in old]
if not targets:
... | 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
... |
367,908 | def _EntriesGenerator(self):
location = getattr(self.path_spec, , None)
if location and location.startswith(self._file_system.PATH_SEPARATOR):
tar_path = location[1:]
processed_directories = set()
tar_file = self._file_system.GetTARFile()
for tar_info in iter... | 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. |
367,909 | def get_connection(self, alias=):
if not isinstance(alias, string_types):
return alias
try:
return self._conns[alias]
except KeyError:
pass
try:
return self.create_connection(alias, **self._kwa... | 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... |
367,910 | def invalid_request_content(message):
exception_tuple = LambdaErrorResponses.InvalidRequestContentException
return BaseLocalService.service_response(
LambdaErrorResponses._construct_error_response_body(LambdaErrorResponses.USER_ERROR, message),
LambdaErrorResponses._con... | 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 |
367,911 | def memoize(method):
cache = method.cache = collections.OrderedDict()
_get = cache.get
_popitem = cache.popitem
@functools.wraps(method)
def memoizer(instance, x, *args, **kwargs):
if not _WITH_MEMOIZATION or isinstance(x, u.Quantity):
return method(i... | 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 |
367,912 | def fromdescriptor(cls, desc):
type_, uri = (, None) if desc is None else desc.split(, 1)
for subclass in cls.__subclasses__():
if subclass.store_type == type_:
return subclass(uri)
raise NotImplementedError(f"Storage type not supported.") | 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 |
367,913 | def create(cls, **kwargs):
extra_columns = set(kwargs.keys()) - set(cls._columns.keys())
if extra_columns:
raise ValidationError("Incorrect columns passed: {0}".format(extra_columns))
return cls.objects.create(**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. |
367,914 | def a(text, mode=, indent=, file=None):
pprint_ast(parse(text, mode=mode), indent=indent, file=file) | 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... |
367,915 | def disable_jt_ha(self, active_name):
args = dict(
activeName = active_name,
)
return self._cmd(, data=args) | 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... |
367,916 | def add_regression_events(obj, events, targets, weights=None, test=False):
if NEW_TMVA_API:
if not isinstance(obj, TMVA.DataLoader):
raise TypeError(
"obj must be a TMVA.DataLoader "
"instance for ROOT >= 6.07/04")
else:
if not isinstance(obj,... | 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... |
367,917 | def run_diff_umap(self,use_rep=, metric=, n_comps=15,
method=, **kwargs):
import scanpy.api as sc
sc.pp.neighbors(self.adata,use_rep=use_rep,n_neighbors=self.k,
metric=self.distance,method=method)
sc.tl.diffmap(se... | Experimental -- running UMAP on the diffusion components |
367,918 | 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(g)... | Format option group kwargs into canonical options format |
367,919 | def generate_contains(self):
self.create_variable_is_list()
with self.l():
contains_definition = self._definition[]
if contains_definition is False:
self.l()
elif contains_definition is True:
with self.l():
... | 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. |
367,920 | def _set_sfp(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=sfp.sfp, is_container=, presence=False, yang_name="sfp", rest_name="sfp", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u: {u: u, ... | 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... |
367,921 | def resetTimeout(self):
if self.__timeoutCall is not None and self.timeOut is not None:
self.__timeoutCall.reset(self.timeOut) | Reset the timeout count down |
367,922 | def delete_merged_branches(self, **kwargs):
path = % self.get_id()
self.manager.gitlab.http_delete(path, **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 request |
367,923 | def sample_from_prior(self):
node_pairs = list(permutations(self.nodes(), 2))
simple_path_dict = {
node_pair: [
list(pairwise(path))
for path in nx.all_simple_paths(self, *node_pair)
]
for node_pair... | Sample elements of the stochastic transition matrix from the prior
distribution, based on gradable adjectives. |
367,924 | def _parse_fc(self, f, natom, dim):
ndim = np.prod(dim)
fc = np.zeros((natom, natom * ndim, 3, 3), dtype=, order=)
for k, l, i, j in np.ndindex((3, 3, natom, natom)):
line = f.readline()
for i_dim in range(ndim):
line = f.readline()
... | Parse force constants part
Physical unit of force cosntants in the file is Ry/au^2. |
367,925 | def make_valid_pyclipper(shape):
clean_shape = _drop_degenerate_inners(shape)
pc = pyclipper.Pyclipper()
try:
pc.AddPaths(_coords(clean_shape), pyclipper.PT_SUBJECT, True)
result = pc.Execute2(pyclipper.CT_UNION, pyclipper.PFT_EVENODD)
except pyclipper.ClipperExce... | 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... |
367,926 | def resp_set_infrared(self, resp, infrared_brightness=None):
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 |
367,927 | def get_root_list(class_path=None, cursor=None, count=50):
query = _PipelineRecord.all(cursor=cursor)
if class_path:
query.filter(, class_path)
query.filter(, True)
query.order()
root_list = query.fetch(count)
fetch_list = []
for pipeline_record in root_list:
fetch_list.append(db.Key(pipeline... | 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... |
367,928 | def _HandleLegacy(self, args, token=None):
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.client_status.name]
total_count = le... | Retrieves the clients for a hunt. |
367,929 | 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):
self.assert_exists()
... | Copy this file to other place. |
367,930 | def dst_addr(self):
try:
return socket.inet_ntop(self._af, self.raw[self._dst_addr].tobytes())
except (ValueError, socket.error):
pass | The packet destination address. |
367,931 | def exclude_functions(self, *funcs):
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. |
367,932 | def clear_jobs(self, recursive=True):
if recursive:
self._scatter_link.clear_jobs(recursive)
self.jobs.clear() | 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` |
367,933 | def get_content_html(request):
result = _get_content_json()
media_type = result[]
if media_type == COLLECTION_MIMETYPE:
content = tree_to_html(result[])
else:
content = result[]
resp = request.response
resp.body = content
resp.status = "200 OK"
resp.content_type = ... | Retrieve content as HTML using the ident-hash (uuid@version). |
367,934 | def parent_subfolders(self, ident, ann_id=None):
ann_id = self._annotator(ann_id)
cid, _ = normalize_ident(ident)
for lab in self.label_store.directly_connected(ident):
folder_cid = lab.other(cid)
subfolder_sid = lab.subtopic_for(folder_cid)
if not fo... | 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... |
367,935 | def zoom_leftdown(self, event=None):
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 |
367,936 | def make_ranges(cls, lines):
start_line = last_line = lines.pop(0)
ranges = []
for line in lines:
if line == (last_line + 1):
last_line = line
else:
ranges.append((start_line, last_line))
start_line = line
... | 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. |
367,937 | def get_access_token(tenant_id, application_id, application_secret):
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 Azure authentication token string.
... | 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... |
367,938 | def EnumKey(key, index):
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, LPDWORD,
ctypes.POINTER(FileTime)
]
buf = ctypes.create_unicode_b... | This calls the Windows RegEnumKeyEx function in a Unicode safe way. |
367,939 | def do_pyscript(self, args: argparse.Namespace) -> bool:
script_path = os.path.expanduser(args.script_path)
py_return = False
orig_args = sys.argv
try:
sys.argv = [script_path] + args.script_arguments
py_... | Run a Python script file inside the console |
367,940 | def log(self, msg):
self._execActions(, msg)
msg = self._execFilters(, msg)
self._processMsg(, msg)
self._sendMsg(, msg) | Log Normal Messages |
367,941 | def human_uuid():
return base64.b32encode(
hashlib.sha1(uuid.uuid4().bytes).digest()).lower().strip() | Returns a good UUID for using as a human readable string. |
367,942 | def RECEIVE_MESSAGE(op):
msg = op.message
text = msg.text
msg_id = msg.id
receiver = msg.to
sender = msg._from
try:
if msg.contentType == 0:
if msg.toType == 2:
line.sendChatChecked(receiver, msg_id)
... | 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 |
367,943 | def clip(self, lower=None, upper=None, axis=None, inplace=False,
*args, **kwargs):
if isinstance(self, ABCPanel):
raise NotImplementedError("clip is not supported yet for panels")
inplace = validate_bool_kwarg(inplace, )
axis = nv.validate_clip_with_axis(axis,... | 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... |
367,944 | def has_table(self, name):
return len(self.sql("SELECT name FROM sqlite_master WHERE type= AND name=?",
parameters=(name,), asrecarray=False, cache=False)) > 0 | Return ``True`` if the table *name* exists in the database. |
367,945 | def get_assessment(self, assessment):
response = self.http.get( + str(assessment))
assessment = Schemas.Assessment(assessment=response)
return assessment | To get Assessment by id |
367,946 | def generateSetupFile(self, outpath=, egg=False):
outpath = os.path.abspath(outpath)
outfile = os.path.join(outpath, )
opts = {
: self.name(),
: self.distributionName(),
: self.version(),
: self.author(),
: self.authorEmail(),... | Generates the setup file for this builder. |
367,947 | def validate_transaction_schema(tx):
_validate_schema(TX_SCHEMA_COMMON, tx)
if tx[] == :
_validate_schema(TX_SCHEMA_TRANSFER, tx)
else:
_validate_schema(TX_SCHEMA_CREATE, 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. |
367,948 | def recover_all(lbn, profile=):
**
ret = {}
config = get_running(profile)
try:
workers_ = config[.format(lbn)].split()
except KeyError:
return ret
for worker in workers_:
curr_state = worker_status(worker, profile)
if curr_state[] != :
worker_activat... | 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 |
367,949 | def admin(self, server=None):
with self.lock:
if not server:
self.send()
else:
self.send( % server)
rvalue = []
while self.readable():
admin_ncodes = , ,
msg = self._recv(expected_replies=(,... | Get the admin information.
Optional arguments:
* server=None - Get admin information for -
server instead of the current server. |
367,950 | def _empty_value(self, formattype):
if formattype.value.idx <= FormatType.BIN_32.value.idx:
return b
elif formattype.value.idx <= FormatType.FIXSTR.value.idx:
return
elif formattype.value.idx <= FormatType.INT_64.value.idx:
return 0
eli... | returns default empty value
:param formattype:
:param buff:
:param start:
:param end: |
367,951 | def load(filename, **kwargs):
with open(filename, ) as f:
reader = T7Reader(f, **kwargs)
return reader.read_obj() | Loads the given t7 file using default settings; kwargs are forwarded
to `T7Reader`. |
367,952 | def public_ip_address_create_or_update(name, resource_group, **kwargs):
if not in kwargs:
rg_props = __salt__[](
resource_group, **kwargs
)
if in rg_props:
log.error(
)
return False
kwargs[] = rg_props[]
ne... | .. 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-... |
367,953 | def backward_sampling(self, M, linear_cost=False, return_ar=False):
idx = np.empty((self.T, M), dtype=int)
idx[-1, :] = rs.multinomial(self.wgt[-1].W, M=M)
if linear_cost:
ar = self._backward_sampling_ON(M, idx)
else:
self._backward_sampling_ON2(M, idx)
... | 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 ... |
367,954 | def compare(molecules, ensemble_lookup, options):
print(" Analyzing differences ... ")
print()
sort_order = classification.get_sort_order(molecules)
ensemble1 = sorted(ensemble_lookup.keys())[0]
ensemble2 = sorted(ensemble_lookup.keys())[1]
stats = {}
stats[] = []
name = os.path.... | compare stuff
:param molecules:
:param ensemble_lookup:
:param options:
:return: |
367,955 | def execute_job(job, app=Injected, task_router=Injected):
app.logger.info("Job fetched, preparing the task .".format(job.path))
task, task_callable = task_router.route(job.path)
jc = JobContext(job, task, task_callable)
app.logger.info("Executing task.")
result = jc.task_callable(jc.tas... | 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 |
367,956 | def load_categories(self, max_pages=30):
logger.info("loading categories")
break
categories = []
for api_category in api_categories:
existing_category = Category.objects.filter(site_id=self.site_id, wp_id=api_category[... | Load all WordPress categories from the given site.
:param max_pages: kill counter to avoid infinite looping
:return: None |
367,957 | def p_additional_catches(p):
if len(p) == 10:
p[0] = p[1] + [ast.Catch(p[4], ast.Variable(p[5], lineno=p.lineno(5)),
p[8], lineno=p.lineno(2))]
else:
p[0] = [] | additional_catches : additional_catches CATCH LPAREN fully_qualified_class_name VARIABLE RPAREN LBRACE inner_statement_list RBRACE
| empty |
367,958 | def warning(self, text):
self.logger.warning("{}{}".format(self.message_prefix, text)) | Ajout d'un message de log de type WARN |
367,959 | def _packed_data(self):
header = self.header()
packed_data = np.frombuffer(self.data, dtype=np.int8)\
.reshape((header[], header[]))
packed_data = packed_data[::-1, constants.header_offset:]
packed_data = packed_data.reshape((header[]*(header[]- constants.header_offset)))
return ... | Returns the bit-packed data extracted from the data file. This is not so useful to analyze.
Use the complex_data method instead. |
367,960 | def check_base_required_attributes(self, dataset):
test_ctx = TestCtx(BaseCheck.HIGH, )
conventions = getattr(dataset, , )
metadata_conventions = getattr(dataset, , )
feature_type = getattr(dataset, , )
cdm_data_type = getattr(dataset, , )
standard_name_vocab = ... | 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... |
367,961 | def extract(filename_url_or_filelike):
pars_tnodes = get_parent_xpaths_and_textnodes(filename_url_or_filelike)
calc_across_paths_textnodes(pars_tnodes)
avg, _, _ = calc_avgstrlen_pathstextnodes(pars_tnodes)
filtered = [parpath_tnodes for parpath_tnodes in pars_tnodes
... | A more precise algorithm over the original eatiht algorithm |
367,962 | def list_devices(names=None, continue_from=None, **kwargs):
if not names:
names = [device for device, _type in settings.GOLDEN_DEVICES if _type == ]
if continue_from:
continue_from = names.index(continue_from)
else:
continue_from = 0
for port in names[continue_from:]:
... | List devices in settings file and print versions |
367,963 | def QA_indicator_OSC(DataFrame, N=20, M=6):
C = DataFrame[]
OS = (C - MA(C, N)) * 100
MAOSC = EMA(OS, M)
DICT = {: OS, : MAOSC}
return pd.DataFrame(DICT) | 变动速率线
震荡量指标OSC,也叫变动速率线。属于超买超卖类指标,是从移动平均线原理派生出来的一种分析指标。
它反应当日收盘价与一段时间内平均收盘价的差离值,从而测出股价的震荡幅度。
按照移动平均线原理,根据OSC的值可推断价格的趋势,如果远离平均线,就很可能向平均线回归。 |
367,964 | def setDateTimeEnd(self, dtime):
self._dateEnd = dtime.date()
self._timeEnd = dtime.time()
self._allDay = False | Sets the endiing date time for this gantt chart.
:param dtime | <QDateTime> |
367,965 | def list_objects_access(f):
@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. |
367,966 | def vertical_scroll(self, image, padding=True):
image_list = list()
height = image.size[1]
if padding:
for y in range(16):
section = image.crop((0, 0, 8, y))
display_section = self.create_blank_image()
display_section... | 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... |
367,967 | def list_replace(iterable, src, dst):
result=[]
iterable=list(iterable)
try:
dst=list(dst)
except TypeError:
dst=[dst]
src=list(src)
src_len=len(src)
index = 0
while index < len(iterable):
element = iterable[index:index+src_len]
if ele... | 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... |
367,968 | def liveReceivers(receivers):
for receiver in receivers:
if isinstance( receiver, WEAKREF_TYPES):
receiver = receiver()
if receiver is not None:
yield receiver
else:
yield receiver | 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. |
367,969 | def set_setpoint(self, setpointvalue):
_checkSetpointValue( setpointvalue, self.setpoint_max )
self.write_register( 4097, setpointvalue, 1) | Set the setpoint.
Args:
setpointvalue (float): Setpoint [most often in degrees] |
367,970 | def fmt(self, po_file, mo_file):
if not os.path.exists(po_file):
slog.error(%po_file)
return
txt = subprocess.check_output([self._msgfmt,
, "--strict", ,
"--output-file", mo_file, po_file],
stderr=subprocess.STDOUT,
... | 将 po 文件转换成 mo 文件。
:param string po_file: 待转换的 po 文件路径。
:param string mo_file: 目标 mo 文件的路径。 |
367,971 | def start(host, port, profiler_stats, dont_start_browser, debug_mode):
stats_handler = functools.partial(StatsHandler, profiler_stats)
if not debug_mode:
sys.stderr = open(os.devnull, )
print()
if not dont_start_browser:
webbrowser.open(.format(host, port))
try:
StatsSer... | 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. |
367,972 | def get_assessments_taken_by_banks(self, bank_ids):
assessment_taken_list = []
for bank_id in bank_ids:
assessment_taken_list += list(
self.get_assessments_taken_by_bank(bank_id))
return objects.AssessmentTakenList(assessment_taken_list) | 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... |
367,973 | def get_driver(self, desired_capabilities=None):
override_caps = desired_capabilities or {}
desired_capabilities = \
self.config.make_selenium_desired_capabilities()
desired_capabilities.update(override_caps)
browser_string = self.config.browser
chromedrive... | 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
... |
367,974 | def update_snapshots(self):
self.log.debug(.format(self.account.account_name, self.region))
ec2 = self.session.resource(, region_name=self.region)
try:
existing_snapshots = EBSSnapshot.get_all(self.account, self.region)
snapshots = {x.id: x for x in ec2.snapshot... | Update list of EBS Snapshots for the account / region
Returns:
`None` |
367,975 | def humanize_speed(c_per_sec):
scales = [60, 60, 24]
units = [, , , ]
speed = c_per_sec
i = 0
if speed > 0:
while (speed < 1) and (i < len(scales)):
speed *= scales[i]
i += 1
return "{:.1f}{}".format(speed, units[i]) | convert a speed in counts per second to counts per [s, min, h, d], choosing the smallest value greater zero. |
367,976 | def get_response(self, statement=None, **kwargs):
Statement = self.storage.get_object()
additional_response_selection_parameters = kwargs.pop(, {})
persist_values_to_response = kwargs.pop(, {})
if isinstance(statement, str):
kwargs[] = statement
if isinst... | 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... |
367,977 | def publish_scene_add(self, scene_id, animation_id, name, color, velocity, config):
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.sequence_number | publish added scene |
367,978 | def replace_each(text, items, count=None, strip=False):
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. |
367,979 | def set_colors_in_grid(self, some_colors_in_grid):
for color_in_grid in some_colors_in_grid:
self._set_pixel_and_convert_color(
color_in_grid.x, color_in_grid.y, color_in_grid.color) | 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` |
367,980 | def parse_geonames_data(lines_iterator):
data_headers = []
num_created = 0
num_updated = 0
for line in lines_iterator:
line = line.decode()
if line[0] == "
if line[0:4] == "
data_headers = line.strip().split()
if data_headers != DATA_HEADE... | 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... |
367,981 | def get_provider(name, creds):
p = _PROVIDERS.get(name)
if not p:
provider = PROVIDER_MAP.get(name)
if not provider:
if name == :
print "
"a provider; use hpcloud_v12 or hpcloud_v13. See " \
"release notes."
rai... | 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... |
367,982 | def get_params_from_func(func: Callable, signature: Signature=None) -> Params:
if signature is None:
signature = getattr(func, , None)
if signature is None:
signature = inspect.signature(func)
if getattr(func, , None):
annotation = func._doct... | 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. |
367,983 | 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 in tags:
over_resizer = True
... | Returns True if mouse is over a resizer |
367,984 | def query(self, query):
cursor = Cursor(query, self.shard_query_generator(query))
cursor.apply_order()
return cursor | Returns a sequence of objects matching criteria expressed in `query` |
367,985 | def graph_data_on_the_same_graph(list_of_plots, output_directory, resource_path, output_filename):
maximum_yvalue = -float()
minimum_yvalue = float()
plots = curate_plot_list(list_of_plots)
plot_count = len(plots)
if plot_count == 0:
return False, None
graph_height, graph_width, graph_title = get_gra... | graph_data_on_the_same_graph: put a list of plots on the same graph: currently it supports CDF |
367,986 | def match_variables(self, pattern, return_type=):
namevariable
pattern = re.compile(pattern)
vars_ = [v for v in self.variables.values() if pattern.search(v.name)]
return vars_ if return_type.startswith() \
else [v.name for v in vars_] | 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... |
367,987 | def m_seg(p1, p2, rad, dist):
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) |
367,988 | def _resolved_type(self):
import datetime
self.type_ratios = {test: (float(self.type_counts[test]) / float(self.count)) if self.count else None
for test, testf in tests + [(None, None)]}
try:
if self.type_ratios.get(text_type,0) + self... | Return the type for the columns, and a flag to indicate that the
column has codes. |
367,989 | def _secondary_min(self):
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 |
367,990 | def swap_deployment(self, service_name, production, source_deployment):
_validate_not_none(, service_name)
_validate_not_none(, production)
_validate_not_none(, source_deployment)
return self._perform_post(self._get_hosted_service_path(service_name),
... | 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... |
367,991 | def model(self):
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. |
367,992 | def decryption(self, ciphertext, key):
if len(ciphertext) != self._key_len:
raise pyrtl.PyrtlError("Ciphertext length is invalid")
if len(key) != self._key_len:
raise pyrtl.PyrtlError("key length is invalid")
key_list = self._key_gen(key)
t = self._add_ro... | 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 |
367,993 | def search(self, search_phrase, limit=None):
query, query_params = self._make_query_from_terms(search_phrase, limit=limit)
self._parsed_query = (str(query), query_params)
assert isinstance(query, TextClause)
datasets = {}
def make_result(vid=None, b_score=0, p_score... | 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. |
367,994 | def _scale_tile(self, value, width, height):
try:
return self._scale_cache[value, width, height]
except KeyError:
tile = pygame.transform.smoothscale(self.tiles[value], (width, height))
self._scale_cache[value, width, height] = tile
return tile | Return the prescaled tile if already exists, otherwise scale and store it. |
367,995 | def parseFilteringOptions(cls, args, filterRead=None, storeQueryIds=False):
referenceIds = (set(chain.from_iterable(args.referenceId))
if args.referenceId else None)
return cls(
args.samfile,
filterRead=filterRead,
referenceIds=refere... | 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
... |
367,996 | def union(input, **params):
res = []
for col in input:
res.extend(input[col])
return res | Union transformation
:param input:
:param params:
:return: |
367,997 | def enumiter(self, other, rmax, bunch=100000):
def feeder(process):
self.enum(other, rmax, process, bunch)
for r, i, j in makeiter(feeder):
yield r, i, j | 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. |
367,998 | def get_extended_attribute(value):
attribute = Attribute()
if value and value[0] in CFWS_LEADER:
token, value = get_cfws(value)
attribute.append(token)
if value and value[0] in EXTENDED_ATTRIBUTE_ENDS:
raise errors.HeaderParseError(
"expected token but found ".f... | [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. |
367,999 | def updateRole(self, *args, **kwargs):
return self._makeApiCall(self.funcinfo["updateRole"], *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 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.