content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def uniquify_mask(lhs, ctx):
"""Element ÞU
(any) -> A list of booleans describing which elements of a will
remain after uniquifying.
"""
lhs = iterable(lhs, ctx=ctx)
# TODO (user/cgccuser): Reduce code duplication here?
if isinstance(lhs, list):
seen = set()
mask = [... | 5,286,000 |
def test_age(runner):
"""The age property should return the horse's age as at the date of the race"""
assert runner.age == (runner.race.meet['date'] - runner.horse['foaled']).days / 365 | 5,286,001 |
def UpdateName(new_name):
"""
Method for the dApp owner to update the dapp name
:param new_name: new name of the dapp
:type new_name: str
:return: whether the update succeeded
:rtype: bool
"""
if not CheckWitness(OWNER):
Log("Must be owner to update name")
return False... | 5,286,002 |
def get_entrez_df(
force: bool = False,
) -> pd.DataFrame:
"""Get the Entrez mappings dataframe."""
return ensure_df(
PREFIX,
url=ENTREZ_XREFS_URL,
sep="\t",
names=[
"mgi_id",
"symbol",
"status",
"name",
"position",
... | 5,286,003 |
def ks_unif_pelz_good(samples, statistic):
"""
Approximates the statistic distribution by a transformed Li-Chien formula.
This ought to be a bit more accurate than using the Kolmogorov limit, but
should only be used with large squared sample count times statistic.
See: doi:10.18637/jss.v039.i11 and... | 5,286,004 |
def tm_team_transfers(club, season, position_group='All', main_position='All', window='All', currency='EUR'):
"""
Extracts basic player information for each player in a squad including basic player information, market value, and contract expiration
Parameters:
club (string): club name
season (strin... | 5,286,005 |
def Month(year, month):
"""Define an smv.panel.Month
Month extends smv.panel.PartialTime base class
Args:
year (int):
month (int):
Example:
>>> m = Month(2012, 5)
>>> m.smvTime()
u'M201205'
>>> m.timeIndex()
... | 5,286,006 |
def single_threaded_session():
"""Returns a session which will only use a single CPU"""
return make_session(1) | 5,286,007 |
def buoyancy(sig0, rho0=1025.0):
"""Calculate buoyancy [m/s^2] based on potential density.
Inputs
------
sig0: DataArray, ndarray
Potential density [kg/m^3]
rho0: int, float, optional
Reference density [kg/m^3].
Returns
-------
DataArray or ndarray of calculated buoyanc... | 5,286,008 |
def shrink_mask(mask, kernel):
"""Shrink mask wrt to a kernel
Parameters
----------
mask : 2D boolean array_like
the mask to be shrinked by...
kernel : 2D float array_like
... the corresponding array
Returns
-------
2D boolean array
the corresponding shrunk mask... | 5,286,009 |
def bind(*args):
"""
Bind a list of clients and servers together, top down.
"""
# Hack to prevent cyclic import
from .client import Client
from .server import Server
from .service_element import ApplicationServiceElement
from .sap import ServiceAccessPoint
# go through the argument p... | 5,286,010 |
def host_clang(xcrun_toolchain):
"""
Return a Toolchain for the host platform.
If no appropriate compilers can be found, return None.
"""
if platform.system() == 'FreeBSD':
# See: https://github.com/apple/swift/pull/169
# Building Swift from source requires a recent version of the Cl... | 5,286,011 |
def bootstrap(a, nboot=1000, summary_fn=np.mean):
""" Calc vectorised bootstrap sample of array of observations
By default return the mean value of the observations per sample
I.e if len(a)=20 and nboot=100, this returns 100 bootstrap resampled
mean estimates of those 20 observations
... | 5,286,012 |
async def test_no_sensors(hass, mock_bridge):
"""Test the update_items function when no sensors are found."""
mock_bridge.allow_groups = True
mock_bridge.mock_sensor_responses.append({})
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 1
assert len(hass.states.async... | 5,286,013 |
def element2obs(obs, allow_null=False):
""" Remaps the old format to new api Observation model for a single
observation. Returns a dictionary, not an observation instance.
"""
# Should only be one
_obs = {}
#For now we require non-empty strings
if obs['answer']:
_obs['value']... | 5,286,014 |
def django_db_setup(django_db_setup, django_db_blocker):
"""
Creates and initializes test DB
"""
names = []
for i in BASE_DIR.glob('*/fixtures/*yaml'):
# TODO: Split test fixtures
# Do not import fixtures from users app
if i.parent.parent.name == 'users':
continue... | 5,286,015 |
def _get_authentication_key_data(file_path, pin):
"""Open the auth key file"""
from resources.lib.kodi import ui
try:
file_content = load_file(file_path)
iv = '\x00' * 16
cipher = AES.new((pin + pin + pin + pin).encode("utf-8"), AES.MODE_CBC, iv.encode("utf-8"))
decoded = Pad... | 5,286,016 |
def mark(label, func=None):
"""Mark the function/class with the given label.
This may be used as a decorator.
"""
if func is None:
def decorator(func):
return mark(label, func)
return decorator
if isinstance(func, type):
cls = func
apply_to_test_methods(c... | 5,286,017 |
def managerSpecificKey(key):
"""
Produces a manager-localised key for persistent options, etc..
"""
manager = FnAssetAPI.SessionManager.currentManager()
if not manager:
return key
identifier = manager.getIdentifier()
# Hiero doesn't seem to like dots in tag names
safeIdentifier = identifier.replace... | 5,286,018 |
def parse_load_balancer_name(load_balancer_arn):
"""
Parse name out from load balancer ARN
Example:
ARN of load balancer: 'arn:aws:elasticloadbalancing:us-east-1:881508045124:loadbalancer/app/alb-1/72074d479748b405',
Load balancer name: 'alb-1'
return: load balancer name
"""
return load_... | 5,286,019 |
def unsupervised_labels(y, yp, n_classes, n_clusters):
"""Linear assignment algorithm
Arguments:
y (tensor): Ground truth labels
yp (tensor): Predicted clusters
n_classes (int): Number of classes
n_clusters (int): Number of clusters
"""
assert n_classes == n_clusters... | 5,286,020 |
def process_and_validate_ref(ref, paper_database):
"""Takes a reference and database. First tests if the reference is an alias in
the database. Then attempts to extract arxiv id from the reference (which
might be a whole url). Then returns the processed reference or throws an error if
it is not a valid ... | 5,286,021 |
def taggifier(tag: str, **kwargs) -> Macro:
"""
Create a Builder Modifier that wraps the text in HTML tags.
The tag name is mandatory. Attributes can be added as keyword
arguments. All attributes are forced to be lowercase so you can
avoid name collisions by capitalizing words like "class".
"""... | 5,286,022 |
def _AddTask(
queue_name, payload, target=None, name=None, eta=None, transactional=False):
"""Add a task using a selected task scheduler implementation.
Args:
queue_name: a queue name.
payload: a task payload.
target: a target module name.
name: a task name.
eta: a ETA for task execution.
... | 5,286,023 |
def adjust_course_account():
"""
This api adjusts the course credit account for a student.
"""
student_id = request.json.get('student_id', None)
course_id = request.json.get('course_id', None)
transaction_type = request.json.get('transaction_type', None)
amount = request.json.get('amount', N... | 5,286,024 |
def dictHas_check(self, privilege, grant_target_name, user_name, node=None):
"""Check that user is able to execute `dictHas` if and only if they have the necessary privileges.
"""
if node is None:
node = self.context.node
exitcode, message = errors.not_enough_privileges(name=f"{user_name}")
... | 5,286,025 |
def resolved_tool_contract_runner(rtc):
"""Given resolved tool contract, run"""
p = ChunkTasksPickle.read(rtc.task.input_files[0])
p.sorted_by_attr(attr='cluster_bin_index')
assert all([isinstance(task, PartialChunkTask) for task in p])
with open(rtc.task.output_files[0], 'w') as writer:
fo... | 5,286,026 |
def get_gateway(gateway_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetGatewayResult:
"""
Resource schema for AWS::IoTSiteWise::Gateway
:param str gateway_id: The ID of the gateway device.
"""
__args__ = dict()
__args__['gatewayId'] = gate... | 5,286,027 |
def __get_categorical(self, sock=None):
"""
Transform column to numpy array
Args:
sock: Socket connecting the Python API with the getML
engine.
"""
# -------------------------------------------
# Build command string
cmd = dict()
cmd["name_"] = self.thisptr["df_na... | 5,286,028 |
def test_user_set_profile():
"""Can a registered user set their private profile (/profile)"""
app = create_ctfd()
with app.app_context():
register_user(app)
client = login_as_user(app)
r = client.get('/profile')
with client.session_transaction() as sess:
data = {
... | 5,286,029 |
def getUnicodeIndexGroup(name):
"""
Return a group letter for `name`, which must be a unicode string.
Currently supported: Hangul Syllables (U+AC00 - U+D7AF)
@param name: a string
@rtype: string
@return: group letter or None
"""
c = name[0]
if u'\uAC00' <= c <= u'\uD7AF': # Hangul S... | 5,286,030 |
def visualize_ci(ci):
"""
可视化参数a估计值置信区间的分布
"""
# 创建一个图形框
fig = plt.figure(figsize=(6, 6), dpi=80)
# 在图形框里只画一幅图
ax = fig.add_subplot(111)
# 将每一个95%置信区间用竖线表示
for i in range(len(ci) - 1):
ci_low = ci[i][0]
ci_up = ci[i][1]
# 如果置信区间不包含1,则用红色表示,否则用蓝色表示
incl... | 5,286,031 |
def setup_env(duthosts, rand_one_dut_hostname, cfg_facts, init_syslog_config, original_syslog_servers):
"""
Setup/teardown fixture for syslog config
Args:
duthosts: list of DUTs.
rand_selected_dut: The fixture returns a randomly selected DuT.
cfg_facts: config facts for selected DUT
... | 5,286,032 |
def job_run(jobId):
"""
Run a saved job
RouteParams:
jobId: the id of a job
GetParams:
account: an account
user: a user
Returns:
a json representation of a job
"""
account = request.form['account']
user = request.form['user']
cluster = request.form['... | 5,286,033 |
def generate_context_csv(
event_extractor,
paths:List[str],
seq: bool=True,
window_size:int=30,
step:int=5,
columns:List[str]=None,
outdir:str='./'
)->str:
"""Writes a context.csv file that can be processed by a contextual bandit
algorithm. It extracts fea... | 5,286,034 |
def get_embedding(x: Tensor, base_model: nn.Module) -> Tensor:
""" apply f until the last layer, instead return that as the embedding """
out = x
# if it has a get embedding later
if hasattr(base_model, 'get_embedding'):
out = base_model.get_embedding(x)
return out
# for handling mod... | 5,286,035 |
def test_weaver_test_data_packages():
"""Test available Pydataweaver test scripts"""
data_packages_exists = True
for weaver_script in WEAVER_TEST_DATA_PACKAGE_FILES:
file_paths = os.path.join(WEAVER_SCRIPT_DIR, weaver_script + ".json")
if not file_exists(os.path.normpath(file_paths)):
... | 5,286,036 |
def update_metric(metric_id, new_metric_name, metrics):
"""Updates the metric's name.
Args:
metric_id: ID of the metric. The metrics are one-indexed.
new_metric_name: A name to set the old name to.
metrics: A list of all metrics.
"""
index = int(metric_id) - 1
old_name = me... | 5,286,037 |
def _rebatch(iterator: Iterator[types.Transition],
batch_size: int) -> Iterator[types.Transition]:
"""Rebatch the itererator with the given batch size.
Args:
iterator: Iterator to rebatch.
batch_size: New batch size.
Yields:
Transitions with the new batch size.
"""
data = next(itera... | 5,286,038 |
def plot_confusion_matrix(cm, class_names, title='Confusion matrix'):
"""
This function prints and plots the confusion matrix.
"""
cm = cm.round(decimals=2)
figure = plt.figure(figsize=(30, 25))
df_cm = pd.DataFrame(cm) # , index=class_names, columns=class_names
sn.set(font_scale=4) # for... | 5,286,039 |
def iint(number):
"""This method behaves in the same way as the **INT()** function described
by Meeus in his book: Greatest integer which is not greater than number.
:param number: Number or expresion
:type number: int, float
:returns: Greatest integer which is not greater than number
:rtype: ... | 5,286,040 |
def fetch_deps():
"""
Fetch dependencies and install to ./vendor.
"""
run("pip install -r requirements.txt -t vendor") | 5,286,041 |
def init_xena(api, logger, owner, ip=None, port=57911):
""" Create XenaApp object.
:param api: cli/rest
:param logger: python logger
:param owner: owner of the scripting session
:param ip: rest server IP
:param port: rest server TCP port
:return: Xena object
:rtype: XenaApp
"""
... | 5,286,042 |
def register_instance_temporarily(registry, instance):
"""
A context manager to allow tests to register a new instance into a Baserow
registry which will then unregister the instance afterwards to ensure the global
registries are kept clean between tests.
"""
registry.register(instance)
try... | 5,286,043 |
def get_paths(dir_name, glob):
""" returns a generator of the recursive paths on input glob """
return Path(f'./{dir_name}').rglob(glob) | 5,286,044 |
def test_delete_partial_residues(package, resource, delete_backbone_C, sequence):
"""Compare results to expected sequence."""
from openeye import oechem
with resources.path(package, resource) as path:
structure = read_molecules(str(path))[0]
if delete_backbone_C:
hier_vie... | 5,286,045 |
def Plot_loss(history_object):
"""
print history data and plot losses
"""
### print the keys contained in the history object
print(history_object.history.keys())
print(history_object.history['loss'])
print(history_object.history['val_loss'])
### plot the training and validation loss... | 5,286,046 |
def priceVector(A: np.matrix, rho: float, a: int | float, c: int | float, alpha) -> np.matrix:
"""
Parameters
----------
A : Network
rho : network strength
a : stand alone util
c : marginal cost. Should be less than a
Returns
-------
Vector reprsenting what price to charge indiv... | 5,286,047 |
def mkdir_p(path):
"""
Can't believe Python doesn't have this built-in...
"""
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise | 5,286,048 |
def discover(email, credentials=None, auth_type=None, retry_policy=None):
"""
Performs the autodiscover dance and returns the primary SMTP address of the account and a Protocol on success. The
autodiscover and EWS server might not be the same, so we use a different Protocol to do the autodiscover request,
... | 5,286,049 |
def hotchoc(instance: bot, message: trigger) -> None:
"""Make me give the specified nick a hot chocolate."""
if message.group(2) is None:
instance.reply('To whom should I give this hot chocolate?')
else:
instance.action(
f'gives {message.group(2)} a warm, velvety salted caramel h... | 5,286,050 |
def batch_local_dist(x, y, min_val):
""" Compute local distance for batch
Args:
x: pytorch Variable, with shape [N, m, d]
y: pytorch Variable, with shape [N, n, d]
min_val: Minimal distance (for preventing division by zero)
Returns:
dist: pytorch Variable, with shape [N]
"""
... | 5,286,051 |
def get_title_block(txt):
"""
Get the general doc of the cmake code.
Should be at the top of the file, from the
first '#!' to the next text block
"""
res = ""
in_title = False
for line in txt.splitlines():
if line.startswith("#!"):
in_title = True
res += c... | 5,286,052 |
def cudasolve(A, b, tol=1e-3, normal=False, regA = 1.0, regI = 0.0):
""" Conjugate gradient solver for dense system of linear equations.
Ax = b
Returns: x = A^(-1)b
If the system is normal, then it solves
(regA*A'A +regI*I)x= b
Returns: x = (A'A +reg*I)^(-1)b
"""
... | 5,286,053 |
def fiyat(baslangic_tarihi=__dt.datetime.today().strftime("%Y-%m-%d"),
bitis_tarihi=__dt.datetime.today().strftime("%Y-%m-%d"), periyot="saatlik"):
"""
İlgili tarih aralığı için saatlik GÖP, GİP, DGP fiyat bilgilerini vermektedir.
Parametreler
------------
baslangic_tarihi : %YYYY-%AA-%GG... | 5,286,054 |
def test_part2():
""" Test part two """
assert part2(parse_input("test_input.txt")) == 26 | 5,286,055 |
def inverse_relation(dst, rel):
"""
Similar to :meth:``forwards_relation`` but selects
the source nodes instead, given a destination node.
:param dst: The destination node.
:param rel: The relation.
"""
statement = 'SELECT src FROM %s WHERE dst = ?'
return statement % rel, (dst,) | 5,286,056 |
def inline_query_handler(update, context):
"""
Inline query handler for the bot. Returns the appropriate shows as a result.
query_text must be in the space seperated argument form: <keyword> <quality> <send-link>. Check the README for more information.
"""
query_text = update.inline_query.query
... | 5,286,057 |
def PyUnicode_AsUnicodeEscapeString(space, pyobj):
"""Encode a Unicode object using Unicode-Escape and return the result as Python
string object. Error handling is "strict". Return NULL if an exception was
raised by the codec."""
if not pyunicode_check(pyobj):
PyErr_BadArgument(space)
w_un... | 5,286,058 |
def normalize_bridge_id(bridge_id: str):
"""Normalize a bridge identifier."""
bridge_id = bridge_id.upper()
# discovery: contains 4 extra characters in the middle: "FFFF"
if len(bridge_id) == 16 and bridge_id[6:10] == "FFFF":
return bridge_id[0:6] + bridge_id[-6:]
# deCONZ config API conta... | 5,286,059 |
def vdcorput(n, base=2):
"""[summary]
Arguments:
n ([type]): [description]
Keyword Arguments:
base (int): [description] (default: {2})
Returns:
[type]: [description]
"""
return [vdc(i, base) for i in range(n)] | 5,286,060 |
def load_nib(fpath):
"""
Load nifti image
:param fpath: path of nifti file
"""
im = nib.load(fpath)
return im | 5,286,061 |
def save_pickle(path, obj):
"""
simple method to save a picklable object
:param path: path to save
:param obj: a picklable object
:return: None
"""
with open(path, 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) | 5,286,062 |
def backup_cumulus(hostname, username, password, filename):
"""This method is for the cumulus switch because it's weird in the way
it works"""
files = """'/etc/network/interfaces /etc/cumulus/ports.conf /etc/frr/daemons /etc/frr/frr.conf' /tmp/"""
console = pexpect.spawn("scp {}@{}:{}".format(username, ... | 5,286,063 |
def list_of_exchanges(test_mode: bool = False) -> list:
"""Get List of Exchanges available"""
try:
return ListOfExchanges(test_mode=test_mode)
except Exception as exception:
logger.error('Oops! An error Occurred ⚠️')
raise exception | 5,286,064 |
def Min(a, axis, keep_dims):
"""
Min reduction op.
"""
return np.amin(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),
keepdims=keep_dims), | 5,286,065 |
def generate_tea_config(event, context):
"""
Lambda function to return a TEA configuration. Requires that event contain
the following:
* CMR must be configured with an env variable
* Path Parameter named 'id' with CMR provider name
* HTTP Header named 'Authorization' with a CMR compatible token
... | 5,286,066 |
def run_on_dataset(tf_manager: TensorFlowManager,
runners: List[BaseRunner],
dataset_runner: DatasetRunner,
dataset: Dataset,
postprocess: Postprocess,
write_out: bool = False,
log_progress: int = 0) -> Tup... | 5,286,067 |
def rmflvec(self, **kwargs):
"""Writes eigenvectors of fluid nodes to a file for use in damping
APDL Command: RMFLVEC
parameter extraction.
Notes
-----
RMFLVEC extracts the modal information from the modal results file for
all nodes specified in a node component called 'FLUN'. This compone... | 5,286,068 |
def task_show(ctx, task_id=None, block=False):
"""show a task's details."""
if not task_id:
ctx.fail('The task id must be specified by --task-id')
click.echo(
json.dumps(TaskShow(ctx.obj['CLIENT'], task_id=task_id).invoke())) | 5,286,069 |
def group_by_until(self, key_mapper, element_mapper, duration_mapper) -> ObservableBase:
"""Groups the elements of an observable sequence according to a
specified key mapper function. A duration mapper function is used
to control the lifetime of groups. When a group expires, it receives
an OnCompleted n... | 5,286,070 |
def validate_plain_data(
raw_data,
split_data,
float_limit=float(TEST_CONFIG.get('TEST', 'float_limit'))
):
"""validate data that did not split
Args:
raw_data (:obj:`pandas.DataFrame`): raw data (A group)
split_data (:obj:`pandas.DataFrame`): split data (B group)
... | 5,286,071 |
def createIniFile(name, subdir=None):
"""
Returns the path to the named configuration file.
Deprecated: Use createSettingsFile() instead.
"""
return createSettingsFile(name, subdir) | 5,286,072 |
def _nose_2eyes(landmarks):
"""
:param landmarks:
:return: nose, right eye corner, left eye corner
"""
return np.array([_centroid_nose(landmarks), _centroid_right_eye(landmarks),
_centroid_left_eye(landmarks)], dtype=np.double) | 5,286,073 |
def load_model(model_path):
"""Loads existing model
Parameters:
model_path - path to the model file
Returns: loaded model
"""
with open(model_path, 'rb') as f:
return pickle.load(f) | 5,286,074 |
def get_package_attribute(name):
"""Retrieve package attributes from the package itself."""
with open("darwin/__init__.py") as init_file:
for line in init_file:
if line.startswith(name):
return eval(line.split("=")[-1]) | 5,286,075 |
def legacy_redirect(id):
"""Redirect to the documents."""
error = {
"code": PIDDoesNotExistRESTError.code,
"description": PIDDoesNotExistRESTError.description,
}
try:
record = get_record_by_legacy_recid(Record, id)
except PIDDoesNotExistError:
return error
schema ... | 5,286,076 |
def get_service(hass, config, discovery_info=None):
"""Get the Pushetta notification service."""
api_key = config[CONF_API_KEY]
channel_name = config[CONF_CHANNEL_NAME]
send_test_msg = config[CONF_SEND_TEST_MSG]
pushetta_service = PushettaNotificationService(
api_key, channel_name, send_tes... | 5,286,077 |
def filter_end_events_per_object_type(ocel: OCEL, object_type: str, parameters: Optional[Dict[Any, Any]] = None) -> OCEL:
"""
Filters the events in which an object for the given object type terminates its lifecycle.
(E.g. an event with activity "Pay Order" might terminate an order).
Parameters
----... | 5,286,078 |
def scrape_inverter():
""" Connect to the inverter and scrape the metrics """
client.connect()
if "sungrow-" in options['model']:
for i in bus["read"]:
if not load_registers("read", i["start"], int(i["range"])):
return False
for i in bus["holding"]:
... | 5,286,079 |
def distinct(coll):
"""
Return a generator of the elements of ``coll`` with duplicates removed.
"""
seen = set()
for e in coll:
if e not in seen:
seen.add(e)
yield e | 5,286,080 |
def test_compress_bam_valid_outpath(base_context, bam_path):
"""Test to run the compress bam command"""
# GIVEN the path to a bam file, a non existing outpath and a cli runner
outpath = "a_file.cram"
runner = CliRunner()
# WHEN running the compress command
result = runner.invoke(
bam, ["... | 5,286,081 |
def call(cfg, clargs, cmds, **kwargs):
"""
IMPURE
Delegates work to appropriate `call_*` functions.
Parameters
----------
cfg: dict
Configuration dictionary.
clargs: Namespace
Command line arguments (normalized).
cmds: iter(tuple)
Iterator of commands to be passed to `subpro... | 5,286,082 |
def plotPeaks(x, y, peaks, showPeaks=True, plotLabels=False, fig=10, plotScore=False, plotsmooth=True, plothalf=False, plotbottom=False, plotmarker='.-b'):
""" Plot detected peaks
Arguments
---------
x,y : numpy arrays
scandata
peaks : list
list of peaks to plot
... | 5,286,083 |
def connect(creds):
"""
Connect to cloudformation, with user-provided options.
:param region_creds: The region name and AWS credentials.
:type region_creds: kaws.config.AwsCreds or kaws.config.RegionAwsCreds
:rtype: boto.cloudformation.connection.CloudFormationConnection
Note: IAM cannot authenticate a user us... | 5,286,084 |
def isBaidu(url):
"""Return True if this url matches the pattern for Baidu searches"""
#Example: http://www.baidu.com/s?wd=mao+is+cool&rsv_bp=0&ch=&tn=baidu&bar=&rsv_spt=3&ie=utf-8
pattern = 'http://www.baidu.com/s\?wd=[\S+]+'
matches = re.match(pattern, url)
if matches != None:
return True
return Fa... | 5,286,085 |
def create_home_dir():
"""Create Directory for projectpy."""
current_platform = platform.system().lower()
if current_platform != 'windows':
import pwd
# create the necessary directory structure for storing config details
# in the ~/.projectpy directory
required_dirs = [os.path.join(HOME... | 5,286,086 |
def table_to_json(table):
""" returns a table as JSON """
if arcpyFound == False:
raise Exception("ArcPy is required to use this function")
return arcpy.RecordSet(table).JSON | 5,286,087 |
def test_wrong_function_arguments(
assert_errors, parse_ast_tree, bad_name, code, default_options,
):
"""Testing that function can not have blacklisted arguments."""
tree = parse_ast_tree(code.format('x', bad_name))
visitor = WrongNameVisitor(default_options, tree=tree)
visitor.run()
assert_er... | 5,286,088 |
def epost_history_with_retries(qids, dbname, maxretries):
"""Entrez EPost for a batch of queryids.
qids - Collection of query IDs
dbname - target NCBI database
maxretries - maximum download attempts
Returns the generated history, as parsed by Entrez.read()
"""
trie... | 5,286,089 |
def cross_join(df1, df2):
"""
Return a dataframe that is a cross between dataframes
df1 and df2
ref: https://github.com/pydata/pandas/issues/5401
"""
if len(df1) == 0:
return df2
if len(df2) == 0:
return df1
# Add as lists so that the new index keeps the items in
#... | 5,286,090 |
def test_delete_app2(my_applications, create_cmd):
"""Run command 'delete' to delete second application"""
# my_applications and all related fixtures should be created for deletion
# pylint: disable=unused-argument
ret = toolbox.run_cmd(create_cmd('delete', f"{out_variables['app2']['id']}"))
assert ... | 5,286,091 |
def getModulesOfSequence(sequence):
""" returns the modules found in a sequence.
Note that a module can appear more than once.
"""
import FWCore.ParameterSet.Modules
class Visitor:
#----------------------------------------
def __init__(self):
self.modules_found = []
... | 5,286,092 |
def client(clusterrole, namespace, kubeconfig, port, admin_client):
"""I have <clusterrole> permissions in <namespace>."""
needs_admin = namespace == 'all namespaces'
if needs_admin:
return admin_client
ensure_namespace(admin_client, namespace)
k8s_client = kubernetes.config.new_client_fro... | 5,286,093 |
def read_cnf_mols ( filename, with_v=False, quaternions=False ):
"""Read in molecular configuration."""
import numpy as np
with open(filename,"r") as f:
n=int(f.readline()) # Number of atoms
box=float(f.readline()) # Simulation box length (assumed cubic)
revw=np.loadtxt(filenam... | 5,286,094 |
def multiply_series(*series) -> Series[T]:
"""
multiple addition
"""
if len(series) < 2:
return series[0]
return multiply_2series(series[0], multiply_series(*series[1:])) | 5,286,095 |
def get_app_id(c, app_name):
"""
Retrieve app-id for a given app name (in full). Called from get_id, not for use as sub-task.
:return: False on error, True on not found (continue), or string with app uuid
"""
print(f'{CYAN}Retrieving app-id for {app_name}...{COL_END}')
response = c.config.contro... | 5,286,096 |
def lnL_EB(time: np.ndarray, flux: np.ndarray, sigma: float,
R_EB: float, EB_fluxratio: float, P_orb: float, inc: float,
a: float, R_s: float, u1: float, u2: float,
companion_fluxratio: float = 0.0,
companion_is_host: bool = False):
"""
Calculates the log likelihood o... | 5,286,097 |
def timer():
"""Time the execution of a context block.
Yields:
None
"""
start = time.time()
# Send control back to the context block
yield
end = time.time()
print('Elapsed: {:.2f}s'.format(end - start)) | 5,286,098 |
def detect_burst(relevant_list, total_list):
""" Assume (num. of relevant docs, total num. docs) as the two input lists
returns state costs
"""
state_costs = [(0.0, 0.0)] # for the initial step
s = 2
R = sum(relevant_list)
D = sum(total_list)
p_0 = (1.0 * R) / D
p_1 = p_... | 5,286,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.