content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def compute_wolfe_gap(point_x, objective_function, feasible_region):
"""Compute the Wolfe gap given a point."""
grad = objective_function.evaluate_grad(point_x.cartesian_coordinates)
v = feasible_region.lp_oracle(grad)
wolfe_gap = grad.dot(point_x.cartesian_coordinates - v)
return wolfe_gap | 5,339,700 |
def replace_chunk(filename, offset, length, chunk, in_place=True, max_mem=5):
"""Replace length bytes of data with chunk, starting at offset.
Any KeyboardInterrupts arriving while replace_chunk is runnning
are deferred until the operation is complete.
If in_place is true, the operation works directly o... | 5,339,701 |
async def get(ip, community, oid, port=161, timeout=DEFAULT_TIMEOUT):
# type: (str, str, str, int, int) -> PyType
"""
Delegates to :py:func:`~puresnmp.aio.api.raw.get` but returns simple Python
types.
See the "raw" equivalent for detailed documentation & examples.
"""
raw_value = await raw.... | 5,339,702 |
def preprocess_image(image, params):
"""Preprocess image tensor.
Args:
image: tensor, input image with shape
[cur_batch_size, height, width, depth].
params: dict, user passed parameters.
Returns:
Preprocessed image tensor with shape
[cur_batch_size, height, ... | 5,339,703 |
def get_vlim(xarr: xr.DataArray, alpha: float) -> dict:
"""Get vmin, vmax using mean and std."""
mean = xarr.mean()
std = xarr.std()
return {"vmin": max(0., mean - alpha * std), "vmax": mean + alpha * std} | 5,339,704 |
def count_consumed_symbols(e):
"""Count how many symbols are consumed from each sequence by a single sequence diff entry."""
op = e.op
if op == DiffOp.ADDRANGE:
return (0, len(e.valuelist))
elif op == DiffOp.REMOVERANGE:
return (e.length, 0)
elif op == DiffOp.PATCH:
return (1... | 5,339,705 |
def maha_dist_sq(cols, center, cov):
"""Calculate squared Mahalanobis distance of all observations (rows in the
vectors contained in the list cols) from the center vector with respect to
the covariance matrix cov"""
n = len(cols[0])
p = len(cols)
assert len(center) == p
# observation matri... | 5,339,706 |
def get_form_target():
"""
Returns the target URL for the comment form submission view.
"""
if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_form_target"):
return get_comment_app().get_form_target()
else:
return urlresolvers.reverse("comments.view... | 5,339,707 |
def secret_page(username=None, password=None):
"""
Returns the HTML for the page visited after the user has logged-in.
"""
if username is None or password is None:
raise ValueError("You need to pass both username and password!")
return _wrapper("""
<h1> Welcome, {username}! </h1>
<... | 5,339,708 |
def user(username):
""" displays a single user """
all_badgers = loads(r_server.get('all_badgers'))
this_badger = all_badgers[username]
this_badger_sorted = collections.OrderedDict(sorted(this_badger.items(), reverse=True))
days = days_in_a_row(this_badger)
kwargs = {'badgers': { username: this_... | 5,339,709 |
def ifft(a, axis):
"""
Fourier transformation from grid to image space, along a given axis.
(inverse Fourier transform)
:param a: numpy array, 1D or 2D (`uv` grid to transform)
:param axis: int; axes over which to calculate
:return: numpy array (an image in `lm` coordinate space)
"""
r... | 5,339,710 |
def transitions_and_masks_to_proposals(t1,
t2,
m1,
m2,
max_samples=10,
max_ccs=6):
"""
assumes set-based s and a... so s... | 5,339,711 |
def make_manifest(root: AnyPath) -> FileManifest:
"""
Returns the file manifest for the given directory.
"""
manifest = {}
for (dirpath, dirnames, filenames) in os.walk(root):
dirnames[:] = sorted(dirnames)
for filename in sorted(filenames):
path = Path(dirpath) / filen... | 5,339,712 |
def main():
"""Drives the main script behavior."""
script_dir = os.path.dirname(os.path.realpath(__file__))
for filename in os.listdir(script_dir):
basename, extension = os.path.splitext(filename)
if basename.startswith("Test") and extension == '.py':
source_path = os.path.join(s... | 5,339,713 |
def exists(url):
"""Check based on protocol if url exists."""
parsed_url = urlparse(url)
if parsed_url.scheme == "":
raise RuntimeError("Invalid url: %s" % url)
if parsed_url.scheme in ('http', 'https'):
r = requests.head(url, verify=False)
if r.status_code == 200:
r... | 5,339,714 |
def inverse_chirality_symbol(symbol):
"""
Inverses a chirality symbol, e.g., the 'R' character to 'S', or 'NS' to 'NR'.
Note that chiral double bonds ('E' and 'Z') must not be inversed (they are not mirror images of each other).
Args:
symbol (str): The chirality symbol.
Returns:
st... | 5,339,715 |
def simplify_columns(df):
"""
Simplify column labels for use as snake_case database fields.
All columns will be re-labeled by:
* Replacing all non-alphanumeric characters with spaces.
* Forcing all letters to be lower case.
* Compacting internal whitespace to a single " ".
* Stripping leadi... | 5,339,716 |
def delete(
request: HttpRequest,
wid: Optional[int] = None,
workflow: Optional[Workflow] = None,
) -> JsonResponse:
"""Delete a workflow."""
if request.method == 'POST':
# Log the event
Log.objects.register(
request.user,
Log.WORKFLOW_DELETE,
None... | 5,339,717 |
def at_threshold(FPR, TPR, parameter, threshold):
"""
False positive rate (FPR) and True positive rate (TPR) at the selected threshold.
:param FPR: False positive rates of given receiver operating characteristic (ROC) curve
:param TPR: True positive rate of given receiver operating characteristic (ROC) ... | 5,339,718 |
def cancel_and_close(driver, target_id):
"""
Clicks the cancel button in the current window, confirm the alert dialog,
waits until it is closed and then changes to the window with the given target id
is closed.
"""
time.sleep(10)
current_id = driver.current_window_handle
driver.find_elem... | 5,339,719 |
def _check_kl_estimator(estimator_fn, distribution_fn, num_samples=10000,
rtol=1e-1, atol=1e-3, grad_rtol=2e-1, grad_atol=1e-1):
"""Compares the estimator_fn output and gradient to exact KL."""
rng_key = jax.random.PRNGKey(0)
def expected_kl(params):
distribution_a = distribution_fn(*... | 5,339,720 |
def relative_bias(simu, reco, relative_scaling_method='s1'):
"""
Compute the relative bias of a reconstructed variable as
`median(reco-simu)/relative_scaling(simu, reco)`
Parameters
----------
simu: `numpy.ndarray`
reco: `numpy.ndarray`
relative_scaling_method: str
see `ctaplot.... | 5,339,721 |
def addon_config() -> Dict[str, Any]:
"""Sample addon config."""
return {
"package-name": "djangocms-blog",
"installed-apps": [
"filer",
"easy_thumbnails",
"aldryn_apphooks_config",
"parler",
"taggit",
"taggit_autosuggest",
... | 5,339,722 |
def print_layout24(layout):
"""
Print layout.
"""
print(' {0} {1}'.format(' '.join(layout[0:4]),
' '.join(layout[12:16])))
print(' {0} {1}'.format(' '.join(layout[4:8]),
' '.join(layout[16:20])))
print(' {0} {1}'.form... | 5,339,723 |
def join_mutations_regions(
out_path: str, sample1_id: int, sample2_id: int, mutations_file: File, regions_file: File
) -> File:
"""
Join mutations and regions together to compute an allele frequence.
"""
def iter_mut_points(muts):
for pos, count in muts:
yield pos, "mut", count... | 5,339,724 |
def credibility_interval(post, alpha=1.):
"""Calculate bayesian credibility interval.
Parameters:
-----------
post : array_like
The posterior sample over which to calculate the bayesian credibility
interval.
alpha : float, optional
Confidence level.
Returns:
--------
... | 5,339,725 |
def test_packed_object_reader():
"""Test the functionality of the PackedObjectReader."""
bytestream = b"0123456789abcdef"
with tempfile.NamedTemporaryFile(mode="wb", delete=False) as tempfhandle:
tempfhandle.write(bytestream)
offset = 3
length = 5
expected_bytestream = bytestream[offset... | 5,339,726 |
def test_create_instance_of_animal_shelter(empty_q):
""" can we create a Queue instance with no input values
"""
assert isinstance(empty_q, AnimalShelter) | 5,339,727 |
def test_space_after(style_checker):
"""style_checker on python file with invalid No_Style_Check comment.
The file has a No_Style_Check comment, except that that
the comment is not starting at the end of the line.
So style_checker ignores it, and lets pep8 report the errors
in that file.
"""
... | 5,339,728 |
def test_wild_g001_wild_g001_v(mode, save_output, output_format):
"""
TEST :Syntax Validation - any : ANY (w/ namespace=##any) and instance
document has elements from targetNamespace
"""
assert_bindings(
schema="msData/wildcards/wildG001.xsd",
instance="msData/wildcards/wildG001.xml"... | 5,339,729 |
def svn_ra_invoke_replay_revstart_callback(*args):
"""
svn_ra_invoke_replay_revstart_callback(svn_ra_replay_revstart_callback_t _obj, svn_revnum_t revision,
void replay_baton, svn_delta_editor_t editor,
void edit_baton, apr_hash_t rev_props,
apr_pool_t pool) -> svn_error_t
"""
ret... | 5,339,730 |
def tree(ctx, rootpage):
"""Export metadata of a page tree."""
if not rootpage:
click.serror("No root page selected via --entity!")
return 1
outname = getattr(ctx.obj.outfile, 'name', None)
with api.context() as cf:
results = []
try:
#page = content.Confluen... | 5,339,731 |
def to_half_life(days):
"""
Return the constant [1/s] from the half life length [day]
"""
s= days * 3600*24
return -math.log(1/2)/s | 5,339,732 |
def Send (dst_ip, data, sequence=0, spoof_source=False, dst_port=MDNS_PORT, src_port=MDNS_PORT, dns_name=TEST_QUERY):
"""
Send one packet of MDNS with data.
:param dst_ip: IP as string.
:param data: Data as bytes/string.
:param sequence: Number to use for sequence. Int.
:param spoof_source: Default:False. Set as ... | 5,339,733 |
def accreds_logs_list(request):
"""Display the list of accreds"""
from units.models import Unit
main_unit = Unit.objects.get(pk=settings.ROOT_UNIT_PK)
main_unit.set_rights_can_select(lambda unit: Accreditation.static_rights_can('LIST', request.user, unit))
main_unit.set_rights_can_edit(lambda uni... | 5,339,734 |
def write_pycode(CGpath,codes):
"""
param1: string : path of file to generate with either .py or .ipynb extension.
param2: string : Actual code strings to be written into the file.
The function writes provide code string into the the .py file.
"""
with open(CGpath,'w') as f:
f.write(cod... | 5,339,735 |
def build_dict(file_name, max_vocab_size):
"""
reads a list of sentences from a file and returns
- a dictionary which maps the most frequent words to indices and
- a table which maps indices to the most frequent words
"""
word_freq = Counter()
with open(file_name) as file:
for line in fi... | 5,339,736 |
def from_net(func):
"""
为进行相似度数据收集的函数装饰,作用是忽略env中的数据获取模式,改变数据获取模式,
只使用网络数据模式进行数据收集,完成整个任务后,再恢复之前的数据获取模式
:param func: 进行相似度应用且有数据收集行为的函数
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
# 临时保存env设置中的g_data_fetch_mode
fetch_mode = ABuEnv.g_data_fetch_mode
# 设置数... | 5,339,737 |
def create_index(connection, table_name, index):
"""Create index.
Args:
connection: pyodbc.connect() object, Connection to use when running Sql
table_name: string, Table name including db schema (ex: my_schema.my_table)
index: string, Column name of index... | 5,339,738 |
def profile(c):
"""Create an interactive CPU flame graph."""
_, venv_bin, _ = get_venv(VENV)
pyinstrument = venv_bin / 'pyinstrument'
c.run(f'{pyinstrument.resolve()} --renderer html {(venv_bin /project_name ).resolve()} -v --format count --pages 5',
pty=True) | 5,339,739 |
def embedding_lookup(ids, params):
"""
Returns the embeddings lookups.
The difference of this function to TensorFlow's function is that this
function expects the ids as the first argument and the parameters as the
second; while, in TensorFlow, is the other way around.
:param ids: the ids
:... | 5,339,740 |
def mock_pcluster_config(mocker, scheduler=None, extra_patches=None, patch_funcs=None):
"""Mock various components used to instantiate an instance of PclusterConfig."""
mock_patches = get_mock_pcluster_config_patches(scheduler, extra_patches)
for function, return_value in mock_patches.items():
mocke... | 5,339,741 |
def in_auto_mode(conx: Connection) -> bool:
"""Determine whether the controller is in AUTO or one of the MANUAL
modes.
Wraps the Karel IN_AUTO_MODE routine.
NOTE: this method is moderately expensive, as it executes a Karel
program on the controller.
:returns: True if the controller is in AUTO... | 5,339,742 |
def pref(pref_name, default=None):
"""Return a preference value.
Since this uses CFPreferencesCopyAppValue, Preferences can be defined
several places. Precedence is:
- MCX
- /var/root/Library/Preferences/com.github.salopensource.sal.plist
- /Library/Preferences/com.github.salopensou... | 5,339,743 |
def tRange(tStart, tStop, *, timedelta=300):
"""
Generate datetime list between tStart and tStop with fixed timedelta.
Parameters
----------
tStart: datetime
start time.
tStop: datetime
stop time.
Keywords
--------
timedelta: int
time delta in seconds (defaul... | 5,339,744 |
def insert_unit_record(cnx, time,user_id, unit_name, level, gear_level, gp, stars):
"""
Adds the specified unit to the database for a user
It will check previous entries and skip it if it's a duplicate record
'since only a handful of units change every day, this will save roughly a
bazillionmi... | 5,339,745 |
def TransformInversePoints(T,points):
"""Transforms a Nxk array of points by the inverse of an affine matrix"""
kminus = T.shape[1]-1
return numpy.dot(points-numpy.tile(T[0:kminus,kminus],(len(points),1)),T[0:kminus,0:kminus]) | 5,339,746 |
def act_func(act):
"""function that can choose activation function
Args:
act: (str) activation function name
Returns:
corresponding Pytorch activation function
"""
return nn.ModuleDict([
['relu', nn.ReLU(inplace=True)],
['leaky_relu', nn.LeakyReLU(negative_slope=0.01... | 5,339,747 |
def ajax_get_hashtags():
"""Flask Ajax Get Hashtag Route."""
f = request.args.get('f', 0, type=int)
t = request.args.get('t', 0, type=int)
hashtags_list = get_hashtags()
try:
if t == 0:
return jsonify(dict(hashtags_list[f:]))
elif t > len(hashtags_list):
... | 5,339,748 |
def imprimeJogo(letrasErradas, letrasAcertadas, palavraSecreta):
"""
Feito a partir da variável global que contem as imagens
do jogo em ASCII art, e támbem as letras chutadas de
maneira correta e as letras erradas e a palavra secreta
""" | 5,339,749 |
def extract_pdf_information(pdf_path):
""" Print and return pdf information
"""
# read binary
with open(pdf_path, 'rb') as f:
pdf = PdfFileReader(f)
information = pdf.getDocumentInfo()
number_of_pages = pdf.getNumPages()
txt = f"""
Information about {pdf_path}:
Aut... | 5,339,750 |
def normalize_string(subject: str) -> str:
"""Deprecated function alias"""
logger.warn("normalize_string is deprecated")
return string_to_title(subject) | 5,339,751 |
def get_default_args(func):
"""
Return dict for parameter name and default value.
Parameters
----------
func : Callable
A function to get parameter name and default value.
Returns
-------
Dict
Parameter name and default value.
Examples
--------
>>> def test... | 5,339,752 |
def main():
"""
Stub function for command line tool that launches the plasma calculator notebook.
"""
parser = argparse.ArgumentParser(description="Plasma calculator")
parser.add_argument(
"--port", type=int, default=8866, help="Port to run the notebook"
)
parser.add_argument... | 5,339,753 |
def sec_to_time(seconds):
"""Transform seconds into a formatted time string.
Parameters
-----------
seconds : int
Seconds to be transformed.
Returns
-----------
time : string
A well formatted time string.
"""
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
r... | 5,339,754 |
def chunks(list_of_features, n, agol_layer):
"""
Yield successive n-sized chunks from list_of_features.
list_of_features: list. List of features to be updated.
n: numeric. chunk size, 1000 is the max for AGOL feature layer
agol_layer: AGOL layer.
Ex:
flayer = gis.con... | 5,339,755 |
def list_files(root_dir, extension, min_N=None, max_N=None, exclude=[], random_seed=24):
"""Yields all files with allowed extensions.
The absolute path is returned for each file.
Parameters
----------
root_dir : str, Path
Top level directory
extension : str, iterable
One or mor... | 5,339,756 |
def power_oos(dmap_object, Y):
"""
Performs out-of-sample extension to calculate the values of the diffusion coordinates at each given point using the power-like method.
Parameters
----------
dmap_object : DiffusionMap object
Diffusion map upon which to perform the out-of-sample extension.
... | 5,339,757 |
def main(token: str, nextcloud_username: str = None, nextcloud_password: str = None):
"""
Starts the Antistasi Discord Bot 'AntiPetros'.
Instantiates the bot, loads the extensions and starts the bot with the Token.
This is seperated from the Cli run function so the bot can be started via cli but also f... | 5,339,758 |
def test_ft_tf_queue_thre_con_unicast():
"""
Author : Prudvi Mangadu (prudvi.mangadu@broadcom.com)
"""
tf_data.index = 0
tf_data.threshold = 20
count = 1
while True:
result = 1
result2 = 1
cutils.banner_log("TEST Starts for iteration - {}".format(count))
st... | 5,339,759 |
def mock_get_schedules_response(
schedule_object,
) -> Generator[MagicMock, Any, None]:
"""Fixture for mocking the get_schedules response.
Args:
schedule_object: Fixture of mocked ``SwitcherV2Schedule`` object.
Yields:
Mocked ``SwitcherV2GetScheduleResponseMSG`` object.
"""
mock_r... | 5,339,760 |
def detect_face_landmarks(image, face_rect=None):
"""
detect face landmarks,
if face_rect is None, the face_rect is the same size as image
-> object
:param image:
:param face_rect: where the face is
"""
if(face_rect == None):
face_rect = dlib.rectangle(0, 0, image.sh... | 5,339,761 |
def main_handler(event, context):
"""
Pull the specified files from S3 and push to a Shared Folder in Google Drive.
The payload passed in contains a list of Excel file names in the array fileList.
"""
print('payload:', event)
bucket = os.environ.get('REPORTS_BUCKET')
credentials_parameter =... | 5,339,762 |
def ensure_iterable(obj):
"""Ensure ``obj`` is either a sequential iterable object that is not a
string type.
1. If ``obj`` is :const:`None` return an empty :class:`tuple`.
2. If ``obj`` is an instance of :class:`str`, :class:`bytes`, or :class:`Mapping`,
or not :class:`Iterable` ret... | 5,339,763 |
def test_dist(**kwargs):
"""
Test Distance
"""
a = np.random.random((2, 3))
d = ahrs.utils.metrics.euclidean(a[0], a[1])
result = np.allclose(d, np.linalg.norm(a[0] - a[1]))
return result | 5,339,764 |
def get_pca(coords):
"""
Parameters
-----------
coords : 2D np.array of points
Returns
---------
new_coords : 2D np.array of points
keeps original number of dimension as input coords
variance_ratio : tuple
"""
pca = PCA(n_components=3)
# pca.fit(coords)
# ... | 5,339,765 |
def get_form_info(email):
"""Gets all existing application form info from the database."""
user_id = get_user_id(email)
if not user_id:
return (False, "Invalid user ID. Please contact the organizers.")
query = """
SELECT * FROM applications WHERE user_id = %s AND application_year = %s
""... | 5,339,766 |
def getLog():
"""simple wrapper around basic logger"""
return logging | 5,339,767 |
def _date(defval, t):
"""
支持的格式:
unix 时间戳
yyyy-mm-dd 格式的日期字符串
yyyy/mm/dd 格式的日期字符串
yyyymmdd 格式的日期字符串
如果年月日其中有一项是0,将被转换成 1
"""
if t is None:
return defval
if isinstance(t, (int, float)):
return datetime.fromtimestamp(t).strftime('%Y-%m-%d %H:%M... | 5,339,768 |
def compute_lat_long_distance(point1, point2):
"""
Compute the distance between two records that have fields 'lat' and 'lon'.
See details and reference implementation at http://andrew.hedges.name/experiments/haversine/
:param point1: a record with { 'lat', 'lon' }
:param point2: a record with { 'la... | 5,339,769 |
def entropy_analysis(data_df):
"""
Masked Shannon entropy analysis for sequences
Parameters
----------
data_df: pandas.DataFrame
merged Pandas dataframe
Returns
-------
H_list: list
entropy values for all positions
null_freq_list: list
masked percentage for al... | 5,339,770 |
def set_global_cfg(cfg: CfgNode) -> None:
"""
Let the global config point to the given cfg.
Assume that the given "cfg" has the key "KEY", after calling
`set_global_cfg(cfg)`, the key can be accessed by:
::
from detectron2.config import global_cfg
print(global_cfg.KEY)
By using... | 5,339,771 |
def get_requirements(filename):
"""
Helper function to read the list of requirements from a file
"""
dependency_links = []
with open(filename) as requirements_file:
requirements = requirements_file.read().strip('\n').splitlines()
requirements = [req for req in requirements if not req.sta... | 5,339,772 |
def nigam_and_jennings_response(acc, dt, periods, xi):
"""
Implementation of the response spectrum calculation from Nigam and Jennings (1968).
Ref: Nigam, N. C., Jennings, P. C. (1968) Digital calculation of response spectra from strong-motion earthquake
records. National Science Foundation.
:para... | 5,339,773 |
def rebin_BTSettl(make_unique=False):
"""
Rebin BTSettle models to atlas ck04 resolution; this makes
spectrophotometry MUCH faster
makes new directory: BTSettl_rebin
Code expects to be run in cdbs/grid directory
"""
# Get an atlas ck04 model, we will use this to set wavelength grid
sp_... | 5,339,774 |
def prompt_for_asking_mfa_code(perfect_profile: ProfileTuple):
"""該当プロフィールのMFAトークン入力を促すプロンプトを表示する"""
print(PROMPT_ASK_MFA_TOKEN_FOR_PROFILE_BEFORE + perfect_profile.name + PROMPT_ASK_MFA_TOKEN_FOR_PROFILE_AFTER) | 5,339,775 |
def binary_hamiltonian(op, nqubits, qubits1, qubits2, weights, device=None):
"""Generates tt-tensor classical Ising model Hamiltonian (two-qubit interaction terms in a single basis).
Hamiltonian of the form:
H = sum_i omega_i sigma_ind1(i) sigma_ind2(i)
where omega_i are the Hamiltonian weights, s... | 5,339,776 |
def map_entry(entry, fields):
"""
Retrieve the entry from the given fields and replace it if it should
have a different name within the database.
:param entry: is one of the followings:
- invalid field name
- command (i.g. $eq)
- valid field with no attribute name
- vali... | 5,339,777 |
def seqlogo_hairpin(N, target='none', ligand='theo', pam=None):
"""
Randomize the stem linking the aptamer to the sgRNA and the parts of the
sgRNA that were the most conserved after being randomized in previous
screens. Specifically, I identified these conserved positions by looking
at a sequenc... | 5,339,778 |
def azure_firewall_ip_group_list_command(client: AzureFirewallClient, args: Dict[str, Any]) -> CommandResults:
"""
List IP groups in resource group or subscription.
Args:
client (AzureFirewallClient): Azure Firewall API client.
args (dict): Command arguments from XSOAR.
Returns:
... | 5,339,779 |
def plot_heatmap(df, title=""):
"""
Plotly heatmap wrapper
:param df: pd.DataFrame
:param title: str
"""
fig = go.Figure(
data=go.Heatmap(z=df.values, x=df.columns, y=df.index, colorscale="RdBu")
)
fig.update_layout(template=_TEMPLATE, title=title, legend_orientation="h")
ret... | 5,339,780 |
def normalise_dir_pattern(repo_dir, d):
"""
if d is a relative path, prepend the repo_dir to it
"""
if not d.startswith(repo_dir):
return os.path.join(repo_dir, d)
else:
return d | 5,339,781 |
def describe_dependency():
"""
Describe Dependency supported
"""
print('acl - clausal modifier of noun')
print('advcl - adverbial clause modifier')
print('advmod - adverbial modifier')
print('amod - adjectival modifier')
print('appos - appositional modifier')
print('aux - auxiliary')... | 5,339,782 |
def patch(diff, orig_file, filename, request=None):
"""Apply a diff to a file.
This delegates out to ``patch`` because noone except Larry Wall knows how
to patch.
Args:
diff (bytes):
The contents of the diff to apply.
orig_file (bytes):
The contents of the orig... | 5,339,783 |
def make_docs():
"""Create the documentation and add it to ../src/docs"""
doc_build_dir = os.path.join(THIS_DIR, '..', 'docs')
doc_html_build = os.path.join(doc_build_dir, '_build', 'html')
doc_dest_dir = os.path.join(THIS_DIR, '..', 'src', 'docs')
ex("make clean && make html", cwd=doc_build_... | 5,339,784 |
def test_naptr_flood(cetp_mgr):
""" Tests the establishment of CETP-H2H, CETP-C2C layer and CETPTransport(s) towards r-ces upon getting a list of NAPTR records."""
sender_info = ("10.0.3.111", 43333)
l_hostid, l_hostip = "hosta1.cesa.lte.", sender_info[0]
dst_id, r_cesid, r_ip, r_port, r_proto = "", "",... | 5,339,785 |
def shift_transactions_forward(index, tindex, file, pos, opos):
"""Copy transactions forward in the data file
This might be done as part of a recovery effort
"""
# Cache a bunch of methods
seek=file.seek
read=file.read
write=file.write
index_get=index.get
# Initialize,
pv=z64... | 5,339,786 |
def draw_disturbances(seed, shocks_cov, num_periods, num_draws):
"""Creates desired number of draws of a multivariate standard normal distribution."""
# Set seed
np.random.seed(seed)
# Input parameters of the distribution
mean = [0, 0, 0]
shocks_cov_matrix = np.zeros((3, 3), float)
np.fill... | 5,339,787 |
def main():
"""Entrypoint function."""
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--username',
help='Hydro Quebec username')
parser.add_argument('-p', '--password',
help='Password')
parser.add_argument('-j', '--json', action='store_t... | 5,339,788 |
def wheel(pos):
"""Generate rainbow colors across 0-255 positions."""
if pos>1280:
pos = 1280
if pos <= 255:
r = 255-pos
g = 0
b = 255
else:
pos = pos-256
if pos <= 255:
r = 0
g = pos
b = 255
else:
p... | 5,339,789 |
def get_physical_connectivity(port):
"""Get local_link_information from specified port.
@param port a port object
@return lli a list of following dict
{"switch_id": "MAC_of_switch", "port_id": "1/1/0/1",
"switch_info": "switch_name"}
"""
# TODO(yushiro) replace fol... | 5,339,790 |
def optimize_profile(diff_matrix, x_points, dc_init, exp_norm_profiles,
display_result=True, labels=None):
"""
Fit the diffusion matrix
Parameters
----------
diff_matrix : tuple
tuple of (eigenvalues, eigenvectors) in reduced basis (dim n-1)
x_points : 1-D array_li... | 5,339,791 |
def getargsfromdoc(obj):
"""Get arguments from object doc"""
if obj.__doc__ is not None:
return getargsfromtext(obj.__doc__, obj.__name__) | 5,339,792 |
def test_0007_e():
""" 불규칙 활용기능 테스트 1"""
# #### "러" 불규칙 활용
pos_list = pos_E.endswithE(u"검푸르러")
assert postag_left_check(pos_list, u"검푸르"), u"검푸르 in eojeol"
assert postag_end_check(pos_list, u"러/EC"), u"러/EC in eojeol"
pos_list = pos_E.endswithE(u"푸르러서")
assert postag_left_check(po... | 5,339,793 |
def nms(dets, thresh):
"""Dispatch to either CPU or GPU NMS implementations.\
Accept dets as tensor"""
return pth_nms(dets, thresh) | 5,339,794 |
def get_disk_usage():
"""
Handle determining disk usage on this VM
"""
disk = {}
# Get the amount of general disk space used
cmd_out = subprocess.getstatusoutput('df -h | grep "/dev/xvda1"')[1]
cmd_parts = cmd_out.split()
disk["gen_disk_used"] = cmd_parts[2]
disk["gen_disk_total"] =... | 5,339,795 |
def generate_arg_parser():
"""
this function receives input arguments for various functions.
:return:
"""
project_path = get_project_path()
# load data
default_db_path = "".join([project_path, "/data/DisasterResponseDataBase.db"])
default_model_path = "".join([str(project_path), "/models... | 5,339,796 |
def QFont_from_Font(font):
""" Convert the given Enaml Font into a QFont.
Parameters
----------
font : Font
The Enaml Font object.
Returns
-------
result : QFont
The QFont instance for the given Enaml font.
"""
qfont = QFont(font.family, font.pointsize, font.weight... | 5,339,797 |
def download_file(source_url, dest_path, source_path=""):
"""
Downloads the given archive and extracts it
Currently works for:
- `zip` files
- `tar.gz` files
Inputs:
- `source_url` (str): URL to download the ZIP file
- `source_path` (str): p... | 5,339,798 |
def test_sns_topic_created(template):
"""
Test for SNS Topic and Subscription: S3 Upload Event Notification
"""
template.resource_count_is("AWS::SNS::Subscription", 1)
template.resource_count_is("AWS::SNS::Topic", 1)
template.resource_count_is("AWS::SNS::TopicPolicy", 1) | 5,339,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.