content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def coordinate_search(mni_coordinates, img_shape, inverse_affine, store_path):
"""
Return a list of patients whose masks have damage at the specified location.
Parameters
----------
coordinates : tuple
MNI coordinates (x,y,z)
img_shape : tuple
Voxel dimensions of the 3D MNI-... | 62,800 |
def prepare_floppy_image(task, params=None):
"""Prepares the floppy image for passing the parameters.
This method prepares a temporary VFAT filesystem image and adds
a file into the image which contains parameters to be passed to
the ramdisk. Then this method uploads built image to Swift
'[redfish]... | 62,801 |
def array_relative_error(a1, a2):
"""Return the elementwise absolute difference between the inputs,
scaled by the maximum value that occurs in the input."""
denom = max(np.amax(np.absolute(a1)), np.amax(np.absolute(a2)))
difference = np.amax(np.absolute(a1 - a2))
if denom < 1e-15:
# Both input a... | 62,802 |
def calculate_inverse_log_density(cluster):
"""Calculate the log of inverse of Density of a cluster.
inverse of density-log = log-volume - ln(size)
Args:
cluster ():
Returns:
float: inverse of density-log
-inf if log-volume = -inf
"""
inverse_log_density = clus... | 62,803 |
def reload_api_v1_integrator(func):
""" Reload a model for each quest """
@wraps(func)
def wrapper(*args, **kwargs):
global COVID_API_V1, dt, ts
COVID_API_V1 = CovidAPIv1()
dt, ts = COVID_API_V1.datetime_raw, COVID_API_V1.timestamp
return func(*args, **kwargs)
return wrap... | 62,804 |
def console(labelbot, interval, repo_urls):
"""Runs LabelBot in console mode"""
labelbot = LabelBot(labelbot.token_file,
labelbot.github_token,
labelbot.rules_file,
labelbot.default_label,
labelbot.check_comments,
... | 62,805 |
def _prepare_errcheck():
"""
This function sets the errcheck attribute of all ctypes wrapped functions
to evaluate the _exc_info_from_callback global variable and re-raise any
exceptions that might have been raised in callbacks.
It also modifies all callback types to automatically wrap the func... | 62,806 |
def _es_primo(n: int) -> bool:
"""
>>> _es_primo(7)
True
>>> _es_primo(8)
False
"""
for i in range(2, n):
if n % i == 0:
return False
return True | 62,807 |
def tarball64_factory():
"""Provides a factor for creating base64 encoded contents of a tarball.
"""
def tarball_(input_dir):
"""Creates a base64 encoded tarball fro input_dir.
Args:
input_dir (dict): The tree structure of the files.
keys represen... | 62,808 |
def test_import_from_geodb(geodb_client, reproject, clip, n_features, bbox):
"""Test for importing from GeoDB.
It will only run if geodb credentials are available as the environment variables
"""
assert geodb_client.whoami, 'Client is not set-up correctly'
feature = FeatureType.VECTOR_TIMELESS, 'lp... | 62,809 |
def safe_encode(text, incoming=None,
encoding='utf-8', errors='strict'):
"""
Encodes incoming str/unicode using `encoding`. If
incoming is not specified, text is expected to
be encoded with current python's default encoding.
(`sys.getdefaultencoding`)
:param incoming: Text's cur... | 62,810 |
def basic_solve(puzzle):
"""Solve puzzle using a non-recursive technique, finding hidden singles.
:param puzzle: Puzzle object
"""
while puzzle.changed:
puzzle.changed = False
find_hidden_singles(puzzle)
puzzle.check() | 62,811 |
def study_with_records(
complete_study: castor_study.CastorStudy, records: List[castor_record.CastorRecord]
) -> castor_study.CastorStudy:
"""Creates a CastorStudy with linked records for use in tests."""
return link_study_with_records(complete_study, records) | 62,812 |
def expires(plugin):
"""
Returns the number of seconds after which to expire a pending plugin task
Args:
plugin (PanoptesPluginInfo): The plugin for which to return the expiry time
Returns:
int: The number of seconds after which to consider the task expired
"""
assert isinstanc... | 62,813 |
def exp_map(x, r, tangent_point=None):
"""
Let \(\mathcal{M}\) be a CCM of radius `r`, and \(T_{p}\mathcal{M}\) the
tangent plane of the CCM at point \(p\) (`tangent_point`).
This function maps a point `x` on the tangent plane to the CCM, using the
Riemannian exponential map.
:param x: np.array,... | 62,814 |
def count_media_packages(distribution_artefacts):
"""
Count media packages in nested list.
:param distribution_artefacts: Nested list containing distribution artefacts mapped to media packages and tenants
:type distribution_artefacts: dict
:return: Amount of media packages
:rtype: int
"""
... | 62,815 |
def renameConstraint(cursor, table, oldConstraintName, newConstraintName):
"""
Rename a constaint of the specified table.
"""
cursor.execute("""ALTER TABLE {0}
RENAME CONSTRAINT {1} TO {2}""".format(table, oldConstraintName, newConstraintName)) | 62,816 |
def set_pixels(n):
"""Game is shown in 8x8"""
if n == 4:
set_pixels_4()
else:
for x in range(8):
for y in range(8):
sense.set_pixel(x, y, colors[L8[x][y]]) | 62,817 |
def get_eos_df(df,order,volpp_name='volpp',epp_name='Epp',with_error=False):
""" obtain eos_df for df
Args:
df (pd.DataFrame): raw data, must have columns [volpp,epp]
order (int): polynomial order, must be one of 1,2,3
"""
data = []
snamel = df.sname.unique()
for sname in snamel:
sel = df.sname... | 62,818 |
def value_at_risk_1d_nb(returns, cutoff=0.05):
"""See `empyrical.value_at_risk`."""
returns = returns[~np.isnan(returns)]
if len(returns) < 1:
return np.nan
return np.percentile(returns, 100 * cutoff) | 62,819 |
def read_last_processed():
"""Read last processed build number."""
with open("last_processed", "r") as fin:
return int(fin.readline()) | 62,820 |
def load_config(filename):
"""
load config file or all the config files if filename represents a directory.
"""
s = os.stat(filename).st_mode
if stat.S_ISREG(s):
return load_one_config(filename)
elif stat.S_ISDIR(s):
return load_all_config(filename)
else:
raise Invali... | 62,821 |
def best_model_from_trials(trials):
"""Extract and return the best model object from trails."""
valid_trial_list = [trial for trial in trials
if STATUS_OK == trial['result']['status']]
losses = [float(trial['result']['loss']) for trial in valid_trial_list]
index_having_minimum_lo... | 62,822 |
def get_region_keys(options):
"""
Extract the region name and credentials, from the options.
:param options: options returned from OptionParser().parse_args()
:type options: optparse.Values
:rtype: k.aws.config.RegionAwsCreds
"""
region_name = options.region
if not region_name:
region_name = DEFAULT_REGION_... | 62,823 |
def dirac(t, n, freq, pulse_delay):
"""
:param t: time sequence (s).
:type t: list of floats
:param n: time iteration index
:type n: int
:param freq: frequency of the sinusoid (Hz)
:type freq: float
:param pulse_delay: number of iteration for the delay of the signal defined
... | 62,824 |
def prepare_supervisor(
mipingDir,
workingDir
):
"""
Copy and modify supervisor config according to
current system.
Parameters
----------
mipingDir : string, default=None, required
Directory path to miping module.
workingDir : string, default=None, required
... | 62,825 |
def video_classify(video_name):
"""
extract_feature
"""
logger.info('predict ... ')
logger.info(video_name)
imgs_path = video_name.replace(".mp4", "").replace("mp4", "frames")
pcm_path = video_name.replace(".mp4", ".pcm").replace("mp4", "pcm")
# step 1: extract feature
feature_... | 62,826 |
def MultiStreamRWBenchmark(results, metadata, vms, command_builder,
service, bucket_name):
"""A benchmark for multi-stream read/write latency and throughput.
Args:
results: the results array to append to.
metadata: a dictionary of metadata to add to samples.
vms: the VMs to ... | 62,827 |
def print_transitions(epsilon, invepsilon, L_max):
"""
For a given partition of histories of length
L_max or smaller, print the transitions
from state to state based on appending
a new (input, output) emission symbol to
a given history.
This function can therefore be used to check
determinism / unifilarity '... | 62,828 |
def make_mag_column_names(instrument, filters):
"""
Given as input the instrument name and the list of filters needed, this
routine generates the list of output header values for the Mirage input
file.
Parameters
----------
instrument : str
'NIRCam', 'NIRISS', or 'Guider"
filte... | 62,829 |
def update(request, tid):
"""Update a PAF."""
return render(request, 'transaction/update.html', {}) | 62,830 |
def get_student_sessions():
"""
This api returns the student's sessions within a time frame.
"""
student_id = request.json.get('student_id', None)
start_time = request.json.get('start_time', None)
end_time = request.json.get('end_time', None)
start_time_utc = datetime_string_to_utc(start_ti... | 62,831 |
def get_macos_version():
"""returns a tuple with the (major,minor,revision) numbers"""
# OS X Yosemite return 10.10, so we will be happy with len(...) == 2, then add 0 for last number
try:
mac_ver = tuple(int(n) for n in platform.mac_ver()[0].split('.'))
assert 2 <= len(mac_ver) <= 3
# p... | 62,832 |
def missing_columns(df,
default_cols = ['Reported Semiology', 'Semiology Category'],
):
"""
These columns must always have a value.
"""
for col in default_cols:
if df[col].isna().sum() ==0:
print('\n\t', col, 'no missing values')
else:
print('\n\t', ... | 62,833 |
def RunModel(num_parameters, num_training_samples):
"""
Creates a logistic regression model of size num_parameters by initializing
the parameters randomly. Generates ground truth for the model and adds
the specified amount of noise to the labels. Then uses gradient decent to
train the model and determines the... | 62,834 |
def test_code_block_tracking(ckr):
"""Check to make sure that no other messages get triggered in a code block."""
ckr.enabled([MessageId.BAD_ENTITY])
# Should have 1 error: not a valid entity
assert(ckr.check("slink:BogusStruct").numDiagnostics() == 1)
assert(ckr.check(
"""****
* sl... | 62,835 |
def edit(task, edit_task):
"""
Edit a task in the list.
"""
edit_query = "UPDATE todo_list SET task = ? WHERE task = ?"
conn = sqlite3.connect("todo_list.db")
cursor = conn.cursor()
cursor.execute(edit_query, (edit_task, task))
conn.commit()
click.echo("Successfully updated!") | 62,836 |
def DeterminePeople(tensor, classes):
""" Input: Tensor of all objects detected on screen
Output: Tensor of only 'people' detected on screen """
PersonIndexes = [] #Index of 'person' in tensor
CurrentIndex = 0
for t in tensor:
cls = int(t[-1])
ObjectDetected = "{0}".form... | 62,837 |
def get_query_date_index(timeframe="today 5-y"):
"""Queries Google trends to have a valid index for query results that returned an empty dataframe
Args:
timeframe (string):
Returns:
pd.Series: date index of Google trend's interest_over_time()
"""
# init pytrends with query that ALW... | 62,838 |
def _l2t_section(label, include_section, include_marker):
"""Helper function converting section labels to text. Assumes
_l2t_subterp, _l2t_interp, and _l2t_appendix failed"""
if include_marker:
marker = u'§ '
else:
marker = ''
if include_section:
# Regulation Text with secti... | 62,839 |
def extract_scores_from_outlist_file(outlist):
"""
:param outlist:
:return:
"""
scores = {'SEED': [], 'FULL': [], 'OTHER': []}
outlist_fp = open(outlist, 'r')
for line in outlist_fp:
if line[0] != '#':
line = [x for x in line.strip().split(' ') if x!='']
s... | 62,840 |
def init_services(service_definitions, client_get, client_authn_factory=None):
"""
Initiates a set of services
:param service_definitions: A dictionary containing service definitions
:param client_get: A function that returns different things from the base entity.
:param client_authn_factory: A lis... | 62,841 |
def label_wav(wav, labels, graph, input_name, output_name, how_many_labels):
"""Loads the model and labels, and runs the inference to print predictions."""
if not wav or not tf.gfile.Exists(wav):
tf.logging.fatal('Audio file does not exist %s', wav)
if not labels or not tf.gfile.Exists(labels):
tf.loggin... | 62,842 |
def test_user_parameter_input_invalid_input():
"""checks that ValidationErrors are raised when input parameters
are missing or incorrect"""
d = deepcopy(TEST_INPUT_UNCERTAINTY)
d.pop("parameters")
with pytest.raises(ValidationError):
validate_input_parameters(d)
d = deepcopy(TEST_INPUT... | 62,843 |
def integration_url(scope="session"):
"""
returns an url
"""
test_url = os.getenv('TEST_URL_INTEGRATION', 'http://127.0.0.1')
port = os.getenv('TEST_PORT_INTEGRATION', 5000)
return f"{test_url}:{port}" | 62,844 |
def list_downloaded_zoo_datasets(base_dir=None):
"""Returns information about the zoo datasets that have been downloaded.
Args:
base_dir (None): the base directory to search for downloaded datasets.
By default, ``fo.config.dataset_zoo_dir`` is used
Returns:
a dict mapping datas... | 62,845 |
def get_clients(units=None, cacert=None):
"""Create a list of clients, one per vault server.
:param units: List of IP addresses of vault endpoints
:type units: [str, str, ...]
:param cacert: Path to CA cert used for vaults api cert.
:type cacert: str
:returns: List of CharmVaultClients
:rty... | 62,846 |
def var_to_np(var):
"""Convenience function to transform `torch.Tensor` to numpy
array.
Should work both for CPU and GPU."""
return var.cpu().data.numpy() | 62,847 |
async def test_order_field_not_nullable(client: Client) -> None:
"""Order by fields, if present, cannot be None"""
with pytest.raises(prisma.errors.MissingRequiredValueError) as exc:
await client.post.find_many(order={'desc': None}) # type: ignore
assert exc.match(r'desc') | 62,848 |
def is_aaai_url(url):
"""determines whether the server from url
@param url : parsed url
"""
return 'aaai.org' in url.netloc | 62,849 |
def ModExp(a, b, c):
"""Uses openssl, if available, to do a^b mod c where a,b,c are longs."""
if not _FOUND_SSL:
return pow(a, b, c)
# convert arbitrary long args to bytes
bytes_a = number.LongToBytes(a)
bytes_b = number.LongToBytes(b)
bytes_c = number.LongToBytes(c)
# convert bytes to (pointer to) B... | 62,850 |
def extract_video_without_audio(input_video, output_video):
"""
功能:删掉视频中的音频,提取无声视频
input_video: 输入的有声视频,如:'with_audio.mp4'
output_video: 删除音频后的视频,如:'without_audio.mp4'
示例:
extract_video_without_audio('with_audio.mp4', 'without_audio.mp4')
"""
VideoFileClip... | 62,851 |
def read_batch_of_files(DIR):
"""Reads in an entire batch of text files as a list of strings"""
files = glob.glob(os.path.join(DIR,'*.txt'))
texts = []
for f in files:
with open(f,'r') as f:
texts.append(f.read())
return texts | 62,852 |
def test_get_acs_auth_data():
"""Verify that X-Akamai-ACS-Auth-Data is formatted correctly."""
timestamp = 1280000000
unique_id = '382644692'
key = 'key1'
data = '5, 0.0.0.0, 0.0.0.0, 1280000000, 382644692, key1'
assert auth.acs_auth_data(key, unique_id, timestamp) == data | 62,853 |
def get_words_label(words_data: list) -> list:
"""
得到当前数据集下的词汇表
:param words_data: 读取到的词语数据
:return: 词汇表
"""
# 使用 set 去重
words_label = set({})
for words in words_data:
words_label.update(words[1])
res = list(words_label)
res.sort()
return res | 62,854 |
def PopupCancel(*args, title=None, button_color=None, background_color=None, text_color=None, auto_close=False,
auto_close_duration=None, non_blocking=False, icon=None, line_width=None, font=None,
no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None, None)):
"... | 62,855 |
def main():
"""通过类方法创建对象获取系统时间"""
clock = Clock.now()
while True:
print(clock.show())
sleep(1)
clock.run() | 62,856 |
def find_good_lines(spec, basename, transition, transs, z, vel_shift, x_col):
"""
"""
specs = glob.glob(spec)
crrls.natural_sort(specs)
with open('{0}_good_lines.log'.format(transition), 'w') as log:
for s in specs:
# Determine the subband name
... | 62,857 |
def home(request):
"""
Controller for the app home page.
"""
# Get the options for the GLDAS Variables
variables = gldas_variables()
variable_opts = []
for key in sorted(variables.keys()):
variable_opts.append((key, variables[key]))
del variables
date_opts = available_dates()... | 62,858 |
def add_identifier(request):
"""
Create an Actor Identifier. Should be an AJAX POST.
:param request: Django request.
:type request: :class:`django.http.HttpRequest`
:returns: :class:`django.http.HttpResponseRedirect`
"""
if request.method == "POST" and request.is_ajax():
username =... | 62,859 |
def locate_file(filename, default=''):
"""Locate command path according to OS environment"""
for path in ENV_PATH:
path = os.path.join(path, filename)
if os.path.isfile(path):
return path
if default != '':
return os.path.join(default, filename)
else:
return filename | 62,860 |
def writePlot(output, plot_data):
"""
Serialize the plot_data into JSON format
:param output:
:param plot_data:
:return:
"""
with open(output, 'w') as fh:
fh.write(json.dumps(plot_data)) | 62,861 |
def alias_(expression, alias, table=False, dialect=None, quoted=None, **opts):
"""
Create an Alias expression.
Expample:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
Args:
expression (str or Expression): the SQL code strings to parse.
If an Expression instance is pass... | 62,862 |
async def async_attach_trigger(hass, config, action, automation_info):
"""Listen for state changes based on configuration."""
device_registry = await hass.helpers.device_registry.async_get_registry()
device = device_registry.async_get(config[CONF_DEVICE_ID])
trigger = (config[CONF_TYPE], config[CONF_SU... | 62,863 |
def forward_errors(func):
"""
Transforms ``func`` in order to forward any ``grpc.RPCError`` returned by the upstream grpc as the result of the
current grpc call.
"""
@functools.wraps(func)
def wrapper(self, request, context, *args, **kwargs):
try:
return func(self, request, ... | 62,864 |
def update_configuration(okta_file, profile):
"""Update okta configuration file on local system.
:param okta_file: Default configuration system file
:param profile: profile of the okta user
:return:
"""
logging.debug("Update okta configuration file on local system.")
config = configparser.... | 62,865 |
async def test_get_triggers(
hass: HomeAssistant,
device_reg: device_registry.DeviceRegistry,
entity_reg: EntityRegistry,
) -> None:
"""Test we get the expected triggers from a select."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = dev... | 62,866 |
def print_sources(sources):
"""Report sources to stderr"""
print("Using layout:", file=sys.stderr)
for _, source in sources.items():
end = memory["base"] + memory["length"] - 1
print("\t%4s: (%s)" %
(memory["name"], memory["dir"]), file=sys.stderr) | 62,867 |
def test_get_with_default_from_portfolio_timeframe_by_startyear_by_allocation():
"""tests get_statistics_by_allocation"""
portfolio_returns_by_allocation = pf.Returns(
EXPECTED_SPECIFIC_RETURNS, EXPECTED_PORTFOLIO_ALLOCATIONS)
portfolio_timeframe_by_startyear_by_allocation = portfolio_returns_by_all... | 62,868 |
def add_graph_data(graph, dataset, value, cluster=None, horiz_value=None, pval=None, val_min=None, val_max=None):
"""Add a graph datapoint.
Return the newly created GraphData object on success.
Raise a LoaderException on error, or if the provided arguments are not valid for the graph.
"""
if not isinstance(da... | 62,869 |
def run_sim(systems, trades, edge=0.1, pnl=0.01):
"""
模拟多个参数组合的资金曲线,策略的胜率从-edge ~ edge
:param systems: 参数数量
:param trades: 交易次数
:param edge: 最优参数的额外胜率
:param pnl: 每次交易盈亏百分比的标准差
:return: 实际最优参数的排名,回测结果最好参数的实际edge
"""
# 参数1~N的盈利笔数
win_rate_list = 0.5 + np.linspace(-1 * edge, edge,... | 62,870 |
def verify_ldp_database_session(
device,
interface=None,
expected_interface=None,
label_type='input',
local_label=None,
max_time=60,
check_interval=10,
):
"""Verifies ldp session exists
Args:
device (obj): device object
interface (str): Interface to use in show comma... | 62,871 |
async def _download_image(
url: str,
filename: Union[Path, str],
semaphore: asyncio.Semaphore,
timeout: float
) -> bool:
"""Download an image from a given url to a given path.
Args:
url: A url from which to download.
filename: A path to the file where to save the image..
... | 62,872 |
def get_exptype_counts(exposures, calibs, width=300, height=300, min_border_left=50, min_border_right=50):
"""
Generate a horizontal bar plot showing the counts for each type of
exposure grouped by whether they have FLAVOR='science' or PROGRAM='calib'
ARGS:
exposures : a table of exposures whic... | 62,873 |
def map(**kwargs):
"""Returns a dictionary of the given keyword arguments mapped to their
values from the environment.
"""
d = {}
e = lower_dict(environ.copy())
for k, v in kwargs.iteritems():
d[k] = e.get(v)
return d | 62,874 |
def make_crossedAxes(ax, xyzero=[0., 0.], limits=[None, None, None, None], ndec=3,
density=(1.0, 1.0), tickl = 0.0125, insideMargin=0.05, pointSize=12, tickPlacesAdd=(0,0)):
"""
Parameters
----------
axl : pyqtgraph plot/axes instance or list
the plot to modify
xyzero : list
... | 62,875 |
def update_inventory(metadata: dict, inventory: dict):
"""Updates inventory to match metadata
Args:
metadata (dict): housing metadata
inventory (dict): user inventory
"""
save = False
for c_name in metadata["companions"]:
if (save := c_name not in (companions := inventory["... | 62,876 |
def ReadXml(filename):
"""读取xml"""
def set_to_field(cls):
sep = os.sep
file_path = inspect.getfile(cls)
file_path = file_path[:file_path.rfind(sep)]
path = os.path.join(file_path, filename)
setattr(cls, '_xml_file', path)
xml = AestateXml.read_file(path)
... | 62,877 |
def login_ui():
"""
Login to OpenShift Console
return:
driver (Selenium WebDriver)
"""
logger.info("Get URL of OCP console")
console_url = config.UI_SELENIUM.get("url")
browser = config.UI_SELENIUM.get("browser_type")
if browser == "chrome":
logger.info("chrome browser... | 62,878 |
def hover_over(spell: str,
stopcast: bool = False,
dismount: bool = True,
) -> str:
""" Hover over target. """
macro = f'#showtooltip {spell}\n'
if stopcast:
macro += '/stopcast\n'
if dismount:
macro += '/dismount\n'
macro += f'/use [@mous... | 62,879 |
def read_story_file(filename):
"""read story file, return three lists, one of titles, one of keywords, one of stories"""
title_list, kw_list, story_list = [], [], []
with open(filename, 'r') as infile:
for line in infile:
title, rest = line.strip().split('<EOT>')
kw, story = ... | 62,880 |
def rotate_points(points, width=600, height=300):
"""180 degree rotation of points of bbox
Parameters
----------
points: list or array
Coordinates of top-left, top-right, bottom-left and bottom-right points
width, height: int
Width/height of perspective transformed module image
Return... | 62,881 |
def inSkipTokens(start, end, skip_tokens: list) -> bool:
"""
Check if start and end index(python) is in one of skip tokens
"""
for token in skip_tokens:
if start >= token[0] and end <= token[1]:
return True
return False | 62,882 |
def test_get_tokens_gc():
"""Ensures get_tokens() works properly with garbage collection."""
tu = get_tu('int foo();')
r = tu.get_extent('t.c', (0, 10))
tokens = list(tu.get_tokens(extent=r))
assert tokens[0].spelling == 'int'
gc.collect()
assert tokens[0].spelling == 'int'
del tokens... | 62,883 |
def comp(a,b,av=None,bv=None,domatch=True,out=None) :
""" VSCATTER comparison of two different data sets
"""
if domatch :
i1,i2=match.match(a['APOGEE_ID'],b['APOGEE_ID'])
gd = np.where(a['NVISITS'][i1] == b['NVISITS'][i2])[0]
a=a[i1[gd]]
b=b[i2[gd]]
fig = vscat(a)
vs... | 62,884 |
def add_layer(cfg, layer, name='', path='', description=''):
""" add new layer
:param layer: layer id
:param name: name
:param path: asset path
:param description: module description
"""
if not path:
raise ConfigurationError('Path is required')
discr = (ID_LAYER, name, layer)
... | 62,885 |
def create_canvas_obj(stroke_width, drawing_mode, realtime_update, background_image, key, height, width):
"""
Creating a canvas object in Streamlit with the parameters specified by the user.
"""
canvas_result = st_canvas(
fill_color="rgba(255, 165, 0, 0)",
stroke_width=stroke_width,
... | 62,886 |
def get_observed_entity_list(): # noqa: E501
"""get observed entity list
get observed entity list # noqa: E501
:param timestamp: the time that cared
:type timestamp: int
:rtype: EntitiesResponse
"""
timestamp = time.time()
entities = []
# obtain tcp_link entities
_edges_tabl... | 62,887 |
def linkrgt(id0, id1, a, b, c, d, z, y):
"""
defines a link from rooms id0->id1, on id0's right.
appends to the lsroom-list at element id0.
this way, multiple calls to link[direction] can be made to build up
source code for a particular room.
"""
a = a*float(scale)
b = b*float(... | 62,888 |
def EnableCoverageBuild():
"""Enable building an Android target with code coverage instrumentation."""
os.environ["EMMA_INSTRUMENT"] = "true" | 62,889 |
def test_port_translate_filter_func_not_in_single(app_context: None):
"""Test to see if the port_translate_filter_func behaves as expected when the NOT_IN
operator is used with a single port"""
input_column = Column("user_ip", Integer)
input_operation = FilterOperator.NOT_IN
input_values = [[443]]
... | 62,890 |
def clear_cache() -> None:
"""Clears the component CACHE."""
global CACHE
global CACHE_IMPORTED_CELLS
CACHE = {}
CACHE_IMPORTED_CELLS = {} | 62,891 |
def datetime_to_time_str(dattim):
""" Converts datetime to a string containing only the time.
@rtype : str
"""
return dattim.strftime(TIME_STR_FORMAT) | 62,892 |
def nest_tokens(tokens: List[Token]) -> List[Union[Token, NestedTokens]]:
"""Convert the token stream to a list of tokens and nested tokens.
``NestedTokens`` contain the open and close tokens and a list of children
of all tokens in between (recursively nested)
"""
output = []
tokens = list(rev... | 62,893 |
def safeWriteFile(filepath, content, maxbackups=10):
"""(Almost) atomic writing of a file.
The content is first written to a temporary file and then swapped in while
keeping a backup file.
It can take both a plain content blob or a list of lines.
"""
tmpfile = filepath + '.tmp'
if isinsta... | 62,894 |
def dnslib_resolve_over_udp(query, dnsservers, timeout, **kwargs):
"""
http://gfwrev.blogspot.com/2009/11/gfwdns.html
http://zh.wikipedia.org/wiki/%E5%9F%9F%E5%90%8D%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%BC%93%E5%AD%98%E6%B1%A1%E6%9F%93
http://support.microsoft.com/kb/241352
https://gist.github.com/klz... | 62,895 |
def is_restricted(fname):
""" Is the filename restricted
- not to be downloaded by non question editors?
"""
if fname in ('datfile.txt', 'datfile.dat', 'qtemplate.html',
'marker.py', 'results.py'):
return True
if fname.startswith("_"):
return True
if fname.en... | 62,896 |
def add_pedestrian(simulation_parameters: SimulationParameters, geometry: Geometry, grid: Grid, step: int):
"""
Add pedestrian at entrances depending on flow to the simulation
:param simulation_parameters: parameters of simulation
:param geometry: geometry to use
:param grid: grid to use
:param ... | 62,897 |
def getBlock(lines, row):
"""
Parameters
----------
lines
row
Returns
-------
"""
block = []
for i in range(row, len(lines)):
if lines[i][0] == 'END':
return i, block
else:
if lines[i][0] != '#':
block.append(lines[i]) | 62,898 |
def serve_suggestions(request):
"""Returns a list of nodes matching the given query"""
# Retrieving the query
query = request.GET.get("q")
if query:
# connecting to mongodb with the credentials defined above
client = pymongo.MongoClient(f"mongodb://{USERNAME}:{PASSWORD}@{HOSTNAME... | 62,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.