content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def search_cut(sentence):
"""
HMM的切割方式
:param sentence:
:return:
"""
return jieba.lcut_for_search(sentence) | 5,328,200 |
def count_items(column_list:list):
"""
Contar os tipos (valores) e a quantidade de items de uma lista informada
args:
column_list (list): Lista de dados de diferentes tipos de valores
return: Retorna dois valores, uma lista de tipos (list) e o total de itens de cada tip... | 5,328,201 |
def abort(exc=None):
"""Raise an exception to terminate a transaction.
If not specified, 'exceptions.NotFound' (404) is raised by default.
:param exc: The exception object to raise.
"""
if exc is None:
raise exceptions.NotFound
assert not issubclass(exc, exceptions.RedirectException), ... | 5,328,202 |
def py_call(obj, inputs=(), direct_args=()):
"""Create a task that calls Python code
Example:
>>> def hello(x):
return b"Hello " + x.read()
>>> a = tasks.const("Loom")
>>> b = tasks.py_call((a,), hello)
>>> client.submit(b)
b'Hello Loom'
"""
task = Task()
task.task_... | 5,328,203 |
def to_graph(grid):
"""
Build adjacency list representation of graph
Land cells in grid are connected if they are vertically or horizontally adjacent
"""
adj_list = {}
n_rows = len(grid)
n_cols = len(grid[0])
land_val = "1"
for i in range(n_rows):
for j in range(n_cols):
... | 5,328,204 |
def validate_doc(doc):
"""
Check to see if the given document is a valid dictionary, that is, that it
contains a single definition list.
"""
return len(doc.content) == 1 and \
isinstance(doc.content[0], pf.DefinitionList) | 5,328,205 |
def is_renderable(obj, quiet=True):
"""
Checks if object is renderable
Args:
obj (unicode): Name of object to verify
quiet (bool): If the function should keep quiet (default=True)
Returns:
(bool) if its renderable or not
"""
# unit test
# make sure we are not working ... | 5,328,206 |
def _refresh_database(bot, force=False, prune=True, callback=None, background=False, db=None):
"""
Actual implementation of refresh_database.
Refreshes the database of starsystems. Also rebuilds the bloom filter.
:param bot: Bot instance
:param force: True to force refresh
:param prune: True t... | 5,328,207 |
def refresh_emoji_text_map(pg: sql_query_tools.Postgres,
pg_schema: str,
table_name: str,
columnspec: dict,
logger: logging.Logger) -> None:
"""
Refresh table emoji_text_map.
"""
logger.info(f'Ref... | 5,328,208 |
def coverageone(ctx, source, test):
"""运行单元测试和计算测试覆盖率
inv coverageone --source plum_tools.fib --test tests/test_fib.py
"""
ctx.run(
"export PYTHONPATH=`pwd` && "
"coverage run --rcfile=.coveragerc --source={source} -m pytest -vv -rsxS -q {test} && "
"coverage report -m".format(s... | 5,328,209 |
def V_bandpass(V, R_S, C, L, R_L, f):
"""
filter output voltage
input voltage minus the current times the source impedance
"""
# current in circuit
I = V/(R_S + Z_bandpass(C, L, R_L, f))
# voltage across circuit
V_out = V - I*R_S
return V_out | 5,328,210 |
def move_to_element(driver, element, display_scaling=100, chrome_info_bar_shown=True):
"""
Move cursor to middle of element. Works for chrome and firefox
:param driver: Chrome or Firefox driver
:type driver: WebDriver
:param element: Web element
:type element:WebElement
:param display_scali... | 5,328,211 |
def get_server_url():
"""
Return current server url, does not work in a task
"""
host = os.environ.get('HTTP_X_FORWARDED_HOST') or os.environ['HTTP_HOST']
return u'%s://%s' % (os.environ['wsgi.url_scheme'], host) | 5,328,212 |
def celery():
"""Celery app test fixture."""
from admiral.celery import celery
return celery | 5,328,213 |
def test_copy_provenance(tracked_file):
"""Test `esmvalcore._provenance.TrackedFile.copy_provenance`."""
provenance = ProvDocument()
provenance.add_namespace('task', uri=ESMVALTOOL_URI_PREFIX + 'task')
activity = provenance.activity('task:test-task-name')
tracked_file.initialize_provenance(activity... | 5,328,214 |
def perm_cache(func):
"""
根据用户+请求参数,把权限验证结果结果进行缓存
"""
def _deco(self, request, view):
# 只对查询(GET方法)进行权限缓存
if request.method != "GET":
return func(self, request, view)
user = request.user.username
kwargs = "_".join("{}:{}".format(_k, _w) for _k, _w in list(vi... | 5,328,215 |
def test_median_even():
"""Test the median for even number of items."""
list_1 = [0, 1, 2, 3, 4, 5, 6]
list_2 = [7, 8, 9]
assert (
find_median(list_1, list_2)
== find_median_simpler_bit_less_efficient(list_1, list_2)
== 4.5
) | 5,328,216 |
def ast_walker(handler):
"""
A generic AST walker decorator.
Decorates either a function or a class (if dispatching based on node type is required).
``handler`` will be wrapped in a :py:class:`~peval.Dispatcher` instance;
see :py:class:`~peval.Dispatcher` for the details of the required class struct... | 5,328,217 |
def test_list_boolean_min_length_1_nistxml_sv_iv_list_boolean_min_length_2_4(mode, save_output, output_format):
"""
Type list/boolean is restricted by facet minLength with value 6.
"""
assert_bindings(
schema="nistData/list/boolean/Schema+Instance/NISTSchema-SV-IV-list-boolean-minLength-2.xsd",
... | 5,328,218 |
def html_escape(text):
"""Produce entities within text."""
L=[]
for c in text:
L.append(html_escape_table.get(c,c))
return "".join(L) | 5,328,219 |
def qs_without_parameter(arg1, arg2):
"""
Removes an argument from the get URL.
Use:
{{ request|url_without_parameter:'page' }}
Args:
arg1: request
arg2: parameter to remove
"""
parameters = {}
for key, value in arg1.items():
if parameters.get(key, None) is ... | 5,328,220 |
def main(
dataset: str = typer.Option(
"mc4", help="The name of the hub dataset or local csv/tsv file."
),
dataset_config: Optional[str] = typer.Option(
"es",
help="The configuration of the hub dataset, if any. Does not apply to local csv/tsv files.",
),
dataset_split: Option... | 5,328,221 |
def test_dissolution_statement_type(session, test_status, legal_type, dissolution_type, dissolution_statement_type,
identifier, expected_code, expected_msg): # pylint: disable=too-many-arguments
"""Assert that a VD can be validated."""
# setup
business = Business(identif... | 5,328,222 |
def find_power_graph(I, J, w_intersect=10, w_difference=1):
"""takes a graph with edges I,J, and returns a power
graph with routing edges Ir,Jr and power edges Ip,Jp.
Note that this treats the graph as undirected, and will
internally convert edges to be undirected if not already."""
n = int(max(max(... | 5,328,223 |
def getcomments(pyObject):
"""Get lines of comments immediately preceding an object's source code.
Returns None when source can't be found.
"""
try:
lines, lnum = findsource(pyObject)
except (IOError, TypeError):
return None
if ismodule(pyObject):
# Look for a comment b... | 5,328,224 |
def crack_captcha(headers):
"""
破解验证码,完整的演示流程
:return:
"""
currentTime = str(int(time.time())*1000)
# 向指定的url请求验证码图片
rand_captcha_url = 'http://59.49.77.231:81/getcode.asp?t=' + currentTime
res = requests.get(rand_captcha_url, stream=True,headers=headers)
f = io.BytesIO()
for ch... | 5,328,225 |
def test_2d_sill():
"""test_2d_sill
Tests against expected classic solution of shallow water equations over
a sill."""
from . import sill
def verify_expected(expected):
def sill_verify(claw):
from clawpack.pyclaw.util import check_diff
import numpy as np
... | 5,328,226 |
def nucleus_instance_segment(
pretrained_model,
pretrained_weights,
img_input,
file_types,
masks,
mode,
output_path,
batch_size,
yaml_config_path,
num_loader_workers,
num_postproc_workers,
auto_generate_mask,
on_gpu,
verbose,
):
"""Process an image/directory o... | 5,328,227 |
def draw_box(
canvas,
layout,
box_width=None,
box_alpha=0,
color_map=None,
show_element_id=False,
show_element_type=False,
id_font_size=None,
id_font_path=None,
id_text_color=None,
id_text_background_color=None,
id_text_background_alpha=1,
):
"""Draw the layout region... | 5,328,228 |
def gpio_connect(self):
"""gpio connections."""
# Check if the pins are already connected.
check_single_pin(self.hwint_1, self.hwint_2)
# gpio pins must be input-output or both-both.
if self.hwint_1.type == self.hwint_2.type \
and not self.hwint_1.type == GPIOType.BOTH:
raise In... | 5,328,229 |
def main(targets: str, cookies: str, outfile: str, customHeaders: str):
"""
Main function, takes a target name/file and parses them,
passes to thread pool and ultimately writes to the outfile in CSV format
"""
targets = parseTargets(targets)
if customHeaders:
global HEADERS
HEAD... | 5,328,230 |
def login(request):
"""Home view, displays login mechanism"""
return render(request, 'duck/login.html') | 5,328,231 |
def make_user_role_table(table_name='user', id_column_name='id'):
"""
Create the user-role association table so that
it correctly references your own UserMixin subclass.
"""
return db.Table('fp_user_role',
db.Column(
'user_id', db.Integer, ... | 5,328,232 |
def _remove_comments_inline(text):
"""Removes the comments from the string 'text'."""
if 'auto-ignore' in text:
return text
if text.lstrip(' ').lstrip('\t').startswith('%'):
return ''
match = re.search(r'(?<!\\)%', text)
if match:
return text[:match.end()] + '\n'
else:
return text | 5,328,233 |
def wide_to_tall(df: pd.DataFrame) -> pd.DataFrame:
"""Convert a wide table to a tall table
Args:
df (pd.DataFrame): wide table
Returns:
pd.DataFrame: tall table
"""
return df.unstack().dropna().reset_index() | 5,328,234 |
def is_pj_player_plus(value):
"""
:param value: The value to be checked
:type value: Any
:return: whether or not the value is a PJ Player+
:rtype: bool
"""
return isinstance(value, list) and len(value) == 4 or len(value) == 3 | 5,328,235 |
def pd_fuzz_partial_token_sort_ratio(col1, col2):
""" Calculate "partial token sort" ratio (`fuzz.partial_token_sort_ratio`) between two text columns.
Args:
col1 (Spark Column): 1st text column
col2 (Spark Column): 2nd text column
Returns:
Spark Column (IntegerType): result of `fuz... | 5,328,236 |
def setup(bot: StarBot) -> None:
"""Load the Configuration cog."""
bot.add_cog(Configuration(bot)) | 5,328,237 |
def path_remove(x, ask=True):
"""
Remove directories
"""
del_list = []
undel_list = []
if isinstance(x, str):
if os.path.isdir(x) and file_exists(x):
del_list.append(x)
else:
undel_list.append(x)
elif isinstance(x, list):
for f in x:
... | 5,328,238 |
def looterCanReinforce(mine: Game) -> bool:
"""
Return True if, in the given game, the looter (the attack) can
reinforce at this moment, regardless of whether its the first or the
second time
"""
return getLooterReinforcementStatus(mine) != 0 | 5,328,239 |
def _get_normed_sym_np(X_, _eps=DEFAULT_EPS):
"""
Compute the normalized and symmetrized probability matrix from
relative probabilities X_, where X_ is a numpy array
Parameters
----------
X_ : 2-d array_like (N, N)
asymmetric probabilities. For instance, X_(i, j) = P(i|j)
Returns
... | 5,328,240 |
def load_encoding_model():
"""Model to encode image as vector of length 4096 using 2nd to last layer of
VGG16"""
base_model = VGG16(weights='imagenet', include_top=True)
encoding_model = Model(inputs=base_model.input,
outputs=base_model.get_layer('fc2').output)
return enc... | 5,328,241 |
def get_geohash_radius_approximation(latitude, longitude, radius, precision, georaptor_flag=False, minlevel=1, maxlevel=12):
"""
Get the list of geohashed that approximate a circle
:param latitude: Float the longitude to get the radius approximation for
:param longitude: Float the latitude to get the r... | 5,328,242 |
def manage_products(request, category_id, template_name="manage/category/products.html"):
"""
"""
category = Category.objects.get(pk=category_id)
inline = products_inline(request, category_id, True)
# amount options
amount_options = []
for value in (10, 25, 50, 100):
amount_options.... | 5,328,243 |
def update_progress(pid: int, increment: int = 1) -> None:
"""
Updates a progress object.
:param pid: The id of the progress.
:param increment: The value to add to current.
"""
p = get_progress_by_id(pid=pid)
assert p is not None
p.current += increment
p.save() | 5,328,244 |
def random_indices(X, size=None, p=None, sort_indices=True, **kwargs):
""" Get indices for a random subset of the data.
Parameters
----------
size: int
* integer size to sample (required if p=None)
p: float
* threshold percentage to keep (required if size=None)
Returns
-... | 5,328,245 |
def get_facts(F5, uri):
"""
Issue a GET of the URI specified to the F5 appliance and return the result as facts.
If the URI must have a slash as the first character, add it if missing
In Ansible 2.2 found name clashing
http://stackoverflow.com/questions/40281706/cant-read-custom-fa... | 5,328,246 |
def _enter_beta_test_mode():
"""Called by conda-kapsel executable to do special things for beta."""
global _beta_test_mode
_beta_test_mode = True | 5,328,247 |
def tesselated_wrangler(gdp, paramset=None, properties=None, override_node=None):
"""Wrangler for any geo that needs to be tesselated"""
prim_name = gdp.iterPrims()[0].intrinsicValue("typename")
api.Comment(
"%s prims is are not directly supported, they will be tesselated" % prim_name
)
mesh... | 5,328,248 |
def test_CNOT_in_X_basis(qvm):
"""
Testing the definition of CNOT in the X basis.
"""
# CNOT truth table
true_truth_table = {(0, 0): (0, 0),
(0, 1): (0, 1),
(1, 0): (1, 1),
(1, 1): (1, 0)}
CNOTX = CNOT_X_basis(0, 1)
for... | 5,328,249 |
def parse_args(args: Optional[Sequence[str]] = None) -> Namespace:
"""
Parses args and validates the consistency of origin/target using the
generator
"""
parser = ArgumentParser(
prog="python -m luh3417.transfer",
description="Transfers a WordPress to one location to the other",
... | 5,328,250 |
def test_suite(session: nox.Session) -> None:
"""Run the Python-based test suite"""
install_requirements_file(session, "test-env")
session.install(".")
session.chdir("")
session.run("no-tests-yet") | 5,328,251 |
def parse_papers_plus_json(data):
""" Function which parses the papers_plus json and returns a pandas dataframe of the results.
Solr Field definition shown below:
<!-- Citing paper fields: papers, metadata, arxiv_metadata -->
<!-- Papers -->
<field name="sentencenum" type="pint" indexed="true" ... | 5,328,252 |
def get_credential(config_file: Path, credential_key: str = 'api_key') -> Optional[str]:
"""
Get a single credential from yaml file. Usual case is 'api_key'
:param config_file:
:param credential_key:
:return:
"""
config = load_credentials(config_file)
credential = config.get('credentials... | 5,328,253 |
def authenticate_secondarily(endpoint):
"""Proper authentication for function views."""
@functools.wraps(endpoint)
def wrapper(request: HttpRequest):
if not request.user.is_authenticated:
try:
auth_result = PersonalAPIKeyAuthentication.authenticate(request)
... | 5,328,254 |
def gather_emails_GUIDs(mailbox, search, folder):
""" Download GUID of messages passing search requirements
"""
mailbox.folder.set(folder)
return (email for email in mailbox.uids(search)) | 5,328,255 |
def pyrolite_meltsutil_datafolder(subfolder=None):
"""
Returns the path of the pyrolite-meltsutil data folder.
Parameters
-----------
subfolder : :class:`str`
Subfolder within the pyrolite data folder.
Returns
-------
:class:`pathlib.Path`
"""
return get_module_datafold... | 5,328,256 |
def setup_stanford_corenlp(force=False):
"""Download and move Stanford CoreNLP to the expected place.
Arguments:
force (boolean): If ``False``, then don't download if
``CORENLP_LOCAL_PATH`` exists. Otherwise, download anyway.
"""
temp_corenlp_name = "corenlp.zip"
if not force:
... | 5,328,257 |
def get_resource_record_set_cloud_formation_dict_list(hosted_zone: ResourceRecordSetList,
with_soa: str,
client: botocore.client.BaseClient, zone_id: str,
... | 5,328,258 |
async def make_async_request(
url: str, method: str = 'GET', **kwargs) -> dict:
"""
Делает асинхронный запрос по указанному URL с параметрами и возвращает словарь из JSON-ответа
Keyword Args:
headers: Request HTTP Headers
params: URI HTTP request params
data: POST HTTP data
... | 5,328,259 |
def pad_table(table, min_width=0, extra_pad=0):
"""takes a multidimensional array of strings and pads them so they're evenly formatted when printed out"""
longest = []
most_cols = 0
for row in table:
#naively assumes we're always passing in collections and not a string
most_cols = max(le... | 5,328,260 |
def test_check_levels():
"""Test _check_levels function of Fetch class"""
era5 = initialize()
era5.variables = "temperature"
# No levels should raise
with pytest.raises(ValueError):
era5._check_levels()
# Valid levels should pass
era5.pressure_levels = [1000, 950]
era5._check_l... | 5,328,261 |
def _prepare_line(edges, nodes):
"""prepare a plotly scatter3d line plot so that a set of disconnected edges
can be drawn as a single line.
`edges` are values associated with each edge (that get mapped to colors
through a colorscale). `nodes` are pairs of (source, target) node indices
for each edge... | 5,328,262 |
def validate_password( password:str ) -> bool:
""" Validates the password again a password policy.
Args:
password ( str, required ):
password to verify.
Returns:
valid ( bool ):
True if the password meets validity requirements.
"""
poli... | 5,328,263 |
def check_stats(hist, values, dtype, error):
"""Check the statistics of a streaming histogram."""
assert isinstance(hist, StreamingHistogram)
assert hist.count() == values.size
assert hist.size() == values.size
assert hist.max() == np.max(values)
assert hist.mean() == pytest.approx(np.mean(value... | 5,328,264 |
def build_webhooks(
handlers_: Iterable[handlers.WebhookHandler],
*,
resources: Iterable[references.Resource],
name_suffix: str,
client_config: reviews.WebhookClientConfig,
persistent_only: bool = False,
) -> List[Dict[str, Any]]:
"""
Construct the content for ``[... | 5,328,265 |
def ndo_real(data, n):
"""mimic of gmx_fio_ndo_real in gromacs"""
return [data.unpack_real() for i in range(n)] | 5,328,266 |
def build_string():
"""
Demonstrates building a STRING by using the Accumulator pattern.
We will later see a more efficient way to build/modify strings,
namely, by using the split/join methods.
"""
# ------------------------------------------------------------------
# The Accumulator patt... | 5,328,267 |
def test_iterable_becomes_attribute_if_passed_as_argument(eh):
"""An iterable in our case is limited to list, tuple."""
from binary_heap import BinaryHeap
b = BinaryHeap([1, 2, 3])
c = BinaryHeap((1, 2, 3))
assert type(b.iterable) == list
assert type(c.iterable) == tuple | 5,328,268 |
def test_probe(mp3, wav):
"""Tests whether minimp3py.probe() returns the correct information"""
samples, channels, sample_rate = minimp3py.probe(mp3)
ref_pcm, ref_rate = wav
assert samples == len(ref_pcm)
assert channels == ref_pcm.shape[1]
assert sample_rate == ref_rate | 5,328,269 |
def test_break_read_fhd():
"""Try various cases of incomplete file lists."""
fhd_uv = UVData()
# missing flags
with pytest.raises(ValueError, match="No flags file included in file list"):
fhd_uv.read(testfiles[1:])
# Missing params
subfiles = [item for sublist in [testfiles[0:2], testfi... | 5,328,270 |
def get_field_type(field: Union[syntax.Field, syntax.Command], idl_file: syntax.IDLParsedSpec,
idl_file_path: str) -> Optional[Union[syntax.Enum, syntax.Struct, syntax.Type]]:
"""Resolve and get field type of a field from the IDL file."""
parser_ctxt = errors.ParserContext(idl_file_path, erro... | 5,328,271 |
def query(context: models.Context, query_str: str) -> TimeSeriesCollection:
"""Do a monitoring query in the specified project.
Note that the project can be either the project where the monitored resources
are, or a workspace host project, in which case you will get results for all
associated monitored projects... | 5,328,272 |
def run_collector(service, metrics_factory, in_queue, pipe_to_server):
"""
Manages Prometheus metrics. Receives changes to the metrics through a queue and emits their text
representation (for HTTP export) over a pipe. Designed to be run as "target" in a multiprocessing.Process
in conjunction with run_ht... | 5,328,273 |
def get_status():
"""get the node status and return data"""
return data({}) | 5,328,274 |
def read_orc(path, columns=None, storage_options=None, **kwargs):
"""Read cudf dataframe from ORC file(s).
Note that this function is mostly borrowed from upstream Dask.
Parameters
----------
path: str or list(str)
Location of file(s), which can be a full URL with protocol specifier,
... | 5,328,275 |
def test_multiple_invocations_parallel_same_flow_running(api_type, capsys):
"""Requires job to be setup allowing simultaneous executions"""
xfail("TODO Note: Test job allowing concurrent builds!") | 5,328,276 |
def get_bm25_index(args, db, db_opts):
"""Form a sparse word to document count matrix (inverted index).
M[i, j] = # times word i appears in document j.
"""
# Map doc_ids to indexes
global DOC2IDX
db_class = retriever.get_class(db)
logging.info("Getting doc ids")
with db_class(**db_opt... | 5,328,277 |
def dedup_model1():
"""Here, we use the w2v_wiki500_yelp_embed_nontrainable mdoel to build indexes
of block then save it to disk for further usage.
"""
model_path = 'models'
# Define block size
block_size_x = 10000
block_size_y = 100
# Build block indexes on w2v_wiki500_yelp_embed_nont... | 5,328,278 |
def get_bernoulli_sample(probs):
"""Conduct Bernoulli sampling according to a specific probability distribution.
Args:
prob: (torch.Tensor) A tensor in which each element denotes a probability of 1 in a Bernoulli distribution.
Returns:
A Tensor of binary samples (0 or 1) wi... | 5,328,279 |
def angle_load(root, ext='.angle'):
"""
Load information from the :ref:`Output_angle` file previously created by :func:`.angle_save`.
Args:
root (str): root name for the file to be loaded
ext (str, optional): default ".angle" - extension for the file to be loaded: name = root + ext
Ret... | 5,328,280 |
def write_data_to_gcs(csv_data):
"""Writes CSV to GCS."""
logging.info('Uploading data to GCS')
now_iso8601 = datetime.datetime.utcnow().isoformat('T')
for classname, results in csv_data.iteritems():
filename_to_create = '{0}/{1}.csv'.format(now_iso8601, classname)
bucket_with_filename ... | 5,328,281 |
def parse_env_file(filename, pattern):
"""Source a shell script and extract variables from it."""
# Use the shell to parse this so we can also read substitutions
# like $() for example.
env = {}
command = 'source {}; set | grep -E "{}"'.format(filename, pattern)
output = subprocess.check_output(... | 5,328,282 |
def dispatch(intent_request):
"""
Called when the user specifies an intent for this bot.
"""
logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name']))
intent_name = intent_request['currentIntent']['name']
# Dispatch to you... | 5,328,283 |
def load_newsdata_and_labels():
"""
Read newsdata, return list of documents, each line in list is one document as string.
And list of labels, each line in list is one-hot-encoded class
"""
# read newsdata which is pickled
import pickle
def read_pickle_one_by_one(pickle_file):
with o... | 5,328,284 |
def CollectUniqueByOrderOfAppearance(dataset:list):
"""
This method collect all unique in order of appearance and return it as list.
:param dataset:list: dataset list
"""
try:
seen = set()
seen_add = seen.add
return [x for x in dataset if not (x in seen or seen_add(x))]
... | 5,328,285 |
async def list_slot_set_actions(current_user: User = Depends(Authentication.get_current_user_and_bot)):
"""
Returns list of slot set actions for bot.
"""
actions = mongo_processor.list_slot_set_actions(current_user.get_bot())
return Response(data=actions) | 5,328,286 |
def openfile_dialog(file_types="All files (*)", multiple_files=False,
file_path='.', caption="Select a file..."):
"""
Opens a File dialog which is used in open_file() function
This function uses pyQt5.
Parameters
----------
file_types : str, optional. Default = all
t... | 5,328,287 |
def getBlocks(bal: "BKAlignedLayout"):
"""
Finds all blocks of a given layout.
:param bal The layout of which the blocks shall be found
:return: The blocks of the given layout
"""
blocks = defaultdict(list)
for layer in bal.layeredGraph.layers:
for node in layer:
root =... | 5,328,288 |
def read_mcmc(path_to_file):
"""
Reads mcmc chain from file
Parameters
----------
path_to_file: string
Path to mcmc chain file
Returns
---------
emcee_table: pandas dataframe
Dataframe of mcmc chain values with NANs removed
"""
colnames = ['mhalo_c','mstellar_c'... | 5,328,289 |
def rotzV(x, theta):
"""Roate a coordinate in the local z frame"""
M = [[np.cos(theta), -np.sin(theta), 0], \
[np.sin(theta), np.cos(theta), 0], [0, 0, 1]]
return np.dot(M, x) | 5,328,290 |
def has_flock(fd):
"""
Checks if fd has flock over it
True if it is, False otherwise
:param fd:
:return:
:rtype: bool
"""
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return True
else:
return False | 5,328,291 |
def check_header(in_path):
"""Logs an error message and raises an exception if the in_path file has no
header (relies on the has_header function).
"""
if not has_header(in_path):
s = f"Error: the input file {in_path} must have a header"
log(s)
s = "Make sure the first elements o... | 5,328,292 |
def userprofile_set_date_joined_program_pre_save(sender, instance, **kwargs):
"""Set date_joined_program to today when empty."""
if not instance.date_joined_program:
instance.date_joined_program = timezone.now().date() | 5,328,293 |
def test_atomic_duration_min_inclusive_nistxml_sv_iv_atomic_duration_min_inclusive_1_3(mode, save_output, output_format):
"""
Type atomic/duration is restricted by facet minInclusive with value
P1970Y01M01DT00H00M00S.
"""
assert_bindings(
schema="nistData/atomic/duration/Schema+Instance/NIST... | 5,328,294 |
def test_nested_list_comprehensions():
"""Nested List Comprehensions
The initial expression in a list comprehension can be any arbitrary expression, including
another list comprehension.
"""
# Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4:
matrix =... | 5,328,295 |
def _check_data(
dataset_name="celeba", train_batch_size=32, eval_batch_size=512, num_per_group=200,
):
"""Check the blond vs non-blond number of images."""
# TODO: Support black hair.
train_loader, valid_loader, test_loader = _make_loaders(
dataset_name, train_batch_size=train_batch_size, eval_... | 5,328,296 |
def ExtractCodeBySystem(
codable_concept,
system):
"""Extract code in codable_concept."""
for coding in codable_concept.coding:
if (coding.HasField('system') and coding.HasField('code') and
coding.system.value == system):
return coding.code.value
return None | 5,328,297 |
def add_item(data, type):
""" Add an item to the data in ranked order
This function handles the process of adding an item to the list. It
first requests the item from the console. Items are nothing more than a
line of text typed in. Next, this kicks off a type of binary search to
find the proper l... | 5,328,298 |
def write_phones_txt(orig_lines, highest_numbered_symbol, nonterminals, filename):
"""Writes updated phones.txt to 'filename'. 'orig_lines' is the original lines
in the phones.txt file as a list of strings (without the newlines);
highest_numbered_symbol is the highest numbered symbol in the origin... | 5,328,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.