content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def force_grid(force_parameters, position_points, velocity_min, velocity_max):
"""Calculates the force on a grid of points in phase space."""
velocity_min_index = velocity_index(velocity_min)
velocity_max_index = velocity_index(velocity_max)
spacing = 2*math.pi / position_points
force = np.zeros((velocity_max_inde... | 43,300 |
def calc_coordination(mysupport, debugging=0):
"""Calculate the coordination number of the support using a 3x3x3 kernel."""
nbz, nby, nbx = mysupport.shape
mykernel = np.ones((3, 3, 3))
mycoord = np.rint(convolve(mysupport, mykernel, mode="same"))
mycoord = mycoord.astype(int)
if debugging == ... | 43,301 |
def valueFromMapping(procurement, subcontract, grant, subgrant, mapping):
"""We configure mappings between FSRS field names and our needs above.
This function uses that config to derive a value from the provided
grant/subgrant"""
subaward = subcontract or subgrant
if mapping is None:
return ... | 43,302 |
def get_cards_in_hand_values_list(player):
"""Gets all the cards in a players's hand and return as a values list"""
return list(Card.objects.filter(cardgameplayer__player=player, cardgameplayer__status=CardGamePlayer.HAND).values('pk', 'name', 'text')) | 43,303 |
def get_dGdE(fp, tau_E, a_E, theta_E, wEE, wEI, I_ext_E, **other_pars):
"""
Compute dGdE
Args:
fp : fixed point (E, I), array
Other arguments are parameters of the Wilson-Cowan model
Returns:
J : the 2x2 Jacobian matrix
"""
rE, rI = fp
# Calculate the J[0,0]
dGdrE = (-1 + wEE * dF(wE... | 43,304 |
def convert_data_to_ints(data, vocab2int, word_count, unk_count, eos=True):
"""
Converts the words in the data into their corresponding integer values.
Input:
data: a list of texts in the corpus
vocab2list: conversion dictionaries
word_count: an integer to count the words in the dat... | 43,305 |
def solve_life_support_rating():
"""Print the life support rating."""
with open('../data/day03.txt') as f:
lines = [line.strip() for line in f]
oxygen = solve_oxygen_or_co2_rating(lines, 'oxygen')
co2 = solve_oxygen_or_co2_rating(lines, 'co2')
print(int(oxygen, 2) * int(co2, 2)) | 43,306 |
def apply_objective_fn(state, obj_fn, precision, scalar_factor=None):
"""Applies a local ObjectiveFn to a state.
This function should only be called inside a pmap, on a pmapped state.
`obj_fn` will usually be a the return value of `operators.gather_local_terms`.
See the docstrings of `SevenDiscretedOperator` ... | 43,307 |
def oauth_generate_token(
consumer_key, consumer_secret, grant_type="client_credentials",
env="sandbox"):
"""
Authenticate your app and return an OAuth access token.
This token gives you time bound access token to call allowed APIs.
NOTE: The OAuth access token expires after an hour (360... | 43,308 |
def test_list_negative_integer_enumeration_4_nistxml_sv_iv_list_negative_integer_enumeration_5_1(mode, save_output, output_format):
"""
Type list/negativeInteger is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/negativeInteger/Schema+Instance/NISTSchema-SV-IV-list-n... | 43,309 |
def parse_quoted_string(string: str, preserve_quotes: bool) -> List[str]:
"""
Parse a quoted string into a list of arguments
:param string: the string being parsed
:param preserve_quotes: if True, then quotes will not be stripped
"""
if isinstance(string, list):
# arguments are already a... | 43,310 |
def do_cli(manager, options):
"""Handle irc cli"""
action_map = {
'status': action_status,
'restart': action_restart,
'stop': action_stop
}
from flexget.plugins.daemon.irc import irc_manager
if irc_manager is None:
console('IRC daemon does not appear to be running.')
... | 43,311 |
def test_magnetic_module_view_calculate_magnet_hardware_height(
definition: ModuleDefinition,
mm_from_base: float,
expected_result: float,
expected_exception_type: Union[Type[Exception], None],
) -> None:
"""It should return the expected height or raise the expected exception."""
module_view = m... | 43,312 |
def scalar(name, scalar_value):
""" 转换标量数据到potobuf格式 """
scalar = make_np(scalar_value)
assert (scalar.squeeze().ndim == 0), 'scalar should be 0D'
scalar = float(scalar)
metadata = SummaryMetadata(plugin_data=SummaryMetadata.PluginData(plugin_name='scalars'))
return Summary(value=[Summary.Value(... | 43,313 |
def filter_citations_by_type(list_of_citations, violation_description):
"""Gets a list of the citations for a particular violation_description.
"""
citations = []
for citation in list_of_citations:
filtered_citation = check_citation_type(citation, violation_description)
if filtered_ci... | 43,314 |
def user_import_circular_database(injector, session, user_mock_circular_database) -> UserMockDataSource:
"""Return the circular data source and import its schema
to the user's project."""
facade = injector.get(DataSourceFacade)
facade.import_schema(user_mock_circular_database.data_source)
session.co... | 43,315 |
def loss_fn(model, data, marginal_prob_std, eps=1e-5):
"""The loss function for training score-based generative models.
Args:
model: A PyTorch model instance that represents a
time-dependent score-based model.
x: A mini-batch of training data.
marginal_prob_std: A function that... | 43,316 |
def nCk(n, k):
"""
Combinations number
"""
if n < 0: raise ValueError("Invalid value for n: %s" % n)
if k < 0 or k > n: return 0
if k in (0, n): return 1
if k in (1, n-1): return n
low_min = 1
low_max = min(n, k)
high_min = max(1, n - k + 1)
high_max = n
return reduce(mul... | 43,317 |
def knowledge_extract_from_json():
"""
半结构化数据知识抽取的第二步
json <-> 数据表映射
Returns:
"""
data = request.json
result = extract_data_from_json(data)
return jsonify({"data": result}) | 43,318 |
def main():
"""
Create Cloud Manager CVO for GCP class instance and invoke apply
:return: None
"""
obj_store = NetAppCloudManagerCVOGCP()
obj_store.apply() | 43,319 |
def vote_random_ideas(request, owner, repository, full_repository_name):
"""
Get 2 random ideas
"""
database_repository = get_object_or_404(models.Repository, owner=owner, name=repository)
jb = jucybot.from_config()
context = {}
context = jb.get_issues(full_repository_name, context=context, ... | 43,320 |
def delta_EF_asym(ave,t_e,t_mu,comp,t_f,n,alpha = None,max_ave_H = 1):
"""computes the EF with asymptotic f, f(N) = f_i*H_i*N_i/(N_i+H_i)
For more information see S10
H_i is uniformly distributed in [0,2*ave_H]
Input
ave, t_e, t_mu, t_f, comp,n:
As in output of rand_par
... | 43,321 |
def time_average_psd(data, nfft, window, average="median", sampling_frequency=1):
"""
Estimate a power spectral density (PSD) by averaging over non-overlapping
shorter segments.
This is different from many other implementations as it does not account
for the window power loss factor (<window ** 2>)... | 43,322 |
def Variable(tensor, *args, **kwargs):
"""
The augmented Variable() function which automatically applies cuda() when gpu is available.
"""
if use_cuda:
return torch.autograd.Variable(tensor, *args, **kwargs).cuda()
else:
return torch.autograd.Variable(tensor, *args, **kwargs) | 43,323 |
def get_log(device):
"""
Gets log file from device.
:param device: device identifier (e.g. "TA9890AMTG").
"""
file_name = str(int(time.time() * 1000)) + ".txt"
target_dir = os.getcwd()
log_path = os.path.join(target_dir, file_name)
clear_log_command = "adb -s " + device + " logcat -c"
... | 43,324 |
def test_multiple_speakers():
"""
Test output exists with multiple speaker input
# GIVEN a sample file containing multiple speakers
# WHEN calling tscribe.write(...)
# THEN produce the .docx without errors
"""
# Setup
input_file = "sample_multiple.json"
output_file = "sample_multi... | 43,325 |
def deploy():
"""Run deployment tasks"""
# migrate database to latest revision
upgrade() | 43,326 |
def edit_distance(graph1, graph2, node_attr='h', edge_attr='e', upper_bound=100, indel_mul=3, sub_mul=3):
"""
Calculates exact graph edit distance between 2 graphs.
Args:
graph1 : networkx graph, graph with node and edge attributes
graph2 : networkx graph, graph with node and edge attributes
... | 43,327 |
def get_node_elements(coord,scale,alpha,dof,bcPrescr=None,bc=None,bc_color='red',fPrescr=None,f=None,f_color='blue6',dofs_per_node=None):
"""
Routine to get node node actors.
:param array coord: Nodal coordinates [number of nodes x 3]
:param int scale: Node actor radius
:param float alpha: Node act... | 43,328 |
async def proo(pros):
""" String for Pros only -_-"""
if not pros.text[0].isalpha() and pros.text[0] not in ("/", "#", "@", "!"):
index = random.randint(0, len(PRO_STRINGS) - 1)
reply_text = PRO_STRINGS[index]
await pros.edit(reply_text) | 43,329 |
def temporal_testing(
horizon, model, observ_interval, first_stage,
bm_threshold, ratio, bootstrap, epsilon, solve
):
"""
first stage random forest, cross validation,
not selecting a best model,
without separate testing
"""
model_name = "horizon-%s-ratio-%0.2f" % (horizon, ratio)
# =... | 43,330 |
def _test_vgp_vs_gpr(vgp, gpr):
"""Test that the VGP with Gaussian Likelihood gives the same results as GPR."""
true_likelihood = gpr.log_likelihood()
for __ in range(10): # iterations per try
vgp.update_sites()
trained_likelihood = vgp.elbo()
np.testing.assert_allclose(trained_likelihoo... | 43,331 |
def write_tsv_dataframe(filepath, dataframe):
"""
Stores `DataFrame` as tsv file
Parameters
----------
filepath : str
Path to tsv file
dataframe : pd.DataFrame
DataFrame to store
Raises
------
IOError
if the file c... | 43,332 |
def start_machines(p, ourmachines, vmids, usegui=False):
""" p = proxmox session, ourmachines= full dictionary of machines
vmids = list of machine-id we want to start
"""
for vmid in vmids:
machine = ourmachines[vmid]
ret = None
sleeptime = 1
if machine[3] == 'runnin... | 43,333 |
def _endian_char(big) -> str:
"""
Returns the character that represents either big endian or small endian in struct unpack.
Args:
big: True if big endian.
Returns:
Character representing either big or small endian.
"""
return '>' if big else '<' | 43,334 |
def planar_angle2D(v1, v2):
"""returns the angle of one vector relative to the other in the
plane defined by the normal (default is in the XY plane)
NB This algorithm avoids carrying out a coordinate transformation
of both vectors. However, it only works if both vectors are in that
plane to start... | 43,335 |
def test_agg_same_method_name(es):
"""
Pandas relies on the function name when calculating aggregations. This means if a two
primitives with the same function name are applied to the same column, pandas
can't differentiate them. We have a work around to this based on the name property
... | 43,336 |
def send_template_email(recipients, title_template, body_template, context, language):
"""Sends e-mail using templating system"""
send_emails = getattr(settings, 'SEND_PLANS_EMAILS', True)
if not send_emails:
return
domain = getattr(settings, 'SITE_URL', None)
context.update({'site_domain'... | 43,337 |
def test_1():
"""
Example with two processes:
source process feeds aggregate process.
"""
# Functions wrapped by agents
def f(in_streams, out_streams):
double(in_streams[0], out_streams[0])
def g(in_streams, out_streams):
s = Stream(name='s')
increment(in_streams... | 43,338 |
def dispatch(request):
"""If user is admin, then show them admin dashboard; otherwise redirect
them to trainee dashboard."""
if request.user.is_admin:
return redirect(reverse("admin-dashboard"))
else:
return redirect(reverse("trainee-dashboard")) | 43,339 |
def log_pdf_factor_analysis(X, W, mu, sigma):
""" log pdf of factor analysis
Args:
X: B X D
W: D X K
mu: D X 1
sigma: D X 1
Returns:
log likelihood
"""
Pi = tf.constant(float(np.pi))
diff_vec = X - mu
sigma_2 = tf.square(sigma)
# phi = tf.eye(K) * sigma_2
# M = tf.... | 43,340 |
def update_entry_validated(db, table, key, data, create_if_not_exists=False):
""" Update entry in table and validate configuration.
If attribute value in data is None, the attribute is deleted.
"""
cfg = db.get_config()
cfg.setdefault(table, {})
if create_if_not_exists:
cfg[table].setd... | 43,341 |
def two_datasets(*, headless=False, raise_on_deprecation=False):
"""Runs ex_two_datasets.py
from pyglotaran_examples/ex_two_datasets"""
# The whole script is run at import.
from pyglotaran_examples.ex_two_datasets import ex_two_datasets | 43,342 |
def _assert_initial_conditions(scheduler_commands, num_compute_nodes):
"""Assert cluster is in expected state before test starts; return list of compute nodes."""
compute_nodes = scheduler_commands.get_compute_nodes()
logging.info(
"Assert initial condition, expect cluster to have {num_nodes} idle n... | 43,343 |
def _clean_parameters(parameters: Dict[str, Any]) -> Dict[str, str]:
""" Removes entries which have no value."""
return {k: str(v) for k, v in parameters.items() if v} | 43,344 |
def delete(run_id):
"""Submits a request to CARROT's runs delete mapping"""
return request_handler.delete("runs", run_id) | 43,345 |
def get_tile_lat_lng(zoom, x, y):
"""convert Google-style Mercator tile coordinate to
(lat, lng) of top-left corner of tile"""
# "map-centric" latitude, in radians:
lat_rad = math.pi - 2*math.pi*y/(2**zoom)
# true latitude:
lat_rad = gudermannian(lat_rad)
lat = lat_rad * 180.0 / math.pi
... | 43,346 |
def test__theory():
""" test autodir.theory
"""
method = 'b3lyp'
basis = 'sto-3g'
open_shell = True
orb_restricted = False
dir_path = autodir.theory.directory_path(
TMP_DIR, method, basis, open_shell, orb_restricted)
assert not os.path.isdir(dir_path)
autodir.theory.create(... | 43,347 |
def decrypt():
"""
Function that takes a certain text and decrypts it using the cipher cipher logic, where each letter of the text
is replaced by another letter, which is presented in the alphabet. Using a key to find out which letter to replace.
:return: Returns nothing
"""
print('_' * 30)
... | 43,348 |
def process_zdr_precip(procstatus, dscfg, radar_list=None):
"""
Keeps only suitable data to evaluate the differential reflectivity in
moderate rain or precipitation (for vertical scans)
Parameters
----------
procstatus : int
Processing status: 0 initializing, 1 processing volume,
... | 43,349 |
def get_initators(filepath, n_lines):
"""
Open text file with iniator words and sample random iniator for each line in the poem.
"""
with open(filepath, "r", encoding = "utf-8") as file:
# save indices of all keywords
loaded_text = file.read() # load text file
lines = loaded_tex... | 43,350 |
def processes_ps(lockdown: LockdownClient, color):
""" show process list """
print_json(OsTraceService(lockdown=lockdown).get_pid_list().get('Payload'), colored=color) | 43,351 |
def length_handler(nbytes, input, output):
"""Async handler for reading a body given a Content-Length header."""
while nbytes > 0:
buffer = yield from input.read(min(nbytes, 256*1024))
if not buffer:
logger.error('premature end for content-length')
output.set_exception(EO... | 43,352 |
def add_syslog_server(ctx, syslog_ip_address):
""" Add syslog server IP """
if not clicommon.is_ipaddress(syslog_ip_address):
ctx.fail('Invalid ip address')
db = ctx.obj['db']
syslog_servers = db.get_table("SYSLOG_SERVER")
if syslog_ip_address in syslog_servers:
click.echo("Syslog se... | 43,353 |
def GSAOI_DARK():
"""
No. Name Ver Type Cards Dimensions Format
0 PRIMARY 1 PrimaryHDU 289 ()
1 1 ImageHDU 144 (2048, 2048) float32
2 2 ImageHDU 144 (2048, 2048) float32
3 3 ImageHDU 1... | 43,354 |
def wrapLoop(loopfunc):
"""Wraps a thread in a wrapper function to restart it if it exits."""
def wrapped():
while True:
try:
loopfunc()
except BaseException:
print(f"Exception in thread {loopfunc},"
" restarting in 10s...")
... | 43,355 |
def get_version(tp):
"""
Get Version based on input parameters
`tp` - Object of class: Transport
"""
response = None
try:
response = tp.send_data('proto-ver', '---')
except RuntimeError as e:
on_except(e)
response = ''
return response | 43,356 |
def _decode_feed_ids(option_feeds):
"""
>>> _decode_feed_ids('123,456')
[123, 456]
"""
return [int(x) for x in option_feeds.strip().split(',')] | 43,357 |
def set_domain(name):
"""Set the base name for the tool"""
global domain
domain = name | 43,358 |
def find_top_10():
""" find the top 10 words stored in the WORD_CACHE then print them in the channel """
global WORD_CACHE
words_array = [[key, WORD_CACHE[key]] for key in sorted(WORD_CACHE, key=WORD_CACHE.get, reverse=True)]
message = "Here are the top 10 most common words used by the room in the l... | 43,359 |
def append_to_phase(phase, data, amt=0.05):
"""
Add additional data outside of phase 0-1.
"""
indexes_before = [i for i, p in enumerate(phase) if p > 1 - amt]
indexes_after = [i for i, p in enumerate(phase) if p < amt]
phase_before = [phase[i] - 1 for i in indexes_before]
data_before = [dat... | 43,360 |
def timedelta2s(t_diff):
"""return number of seconds from :class:`numpy.timedelta64` object
Args:
t_diff: time difference as :class:`numpy.timedelta64` object
Returns:
scalar corresponding to number of seconds
"""
return t_diff / np.timedelta64(1, 's') | 43,361 |
def system_mock():
"""Mock system-level functions.
Functions from fcntl, pickle, select, socket,
subprocess are mocked to avoid tests touching the system state.
"""
calls = {'fcntl': ['fcntl'],
'select': ['select'],
'socket': ['socket'],
'subprocess': ['Popen'... | 43,362 |
def window(MT_seq, WT_seq, window_size=5):
"""
Chop two sequences with a sliding window
"""
if len(MT_seq) != len(WT_seq):
raise Exception("len(MT_seq) != len(WT_seq)")
pos = []
mt = []
wt = []
for i in xrange(len(MT_seq) - window_size + 1):
pos.append(i)
mt.appen... | 43,363 |
def splits_for_blast(target, NAME):
"""Create slices for BLAST
This function creates multiple slices of 400 nucleotides given an fasta
sequence. The step size is 50. This the gaps are excluded from the sequence.
Thats why sequences with less than 400 nucleotides are excluded.
Args:
target (np... | 43,364 |
def test_load_items_errors() -> None:
"""
Test error cases when creating a list of classification Items from a dataframe
"""
def load(csv_string: StringIO) -> str:
df = pd.read_csv(csv_string, sep=",", dtype=str)
numerical_columns = ["scalar2", "scalar1"]
non_image_channels = _g... | 43,365 |
def validate_image(stream):
"""
Ensure the images are valid and in correct format
Args:
stream (Byte-stream): The image
Returns:
str: return image format
"""
header = stream.read(512)
stream.seek(0)
format = imghdr.what(None, header)
if not format:
return No... | 43,366 |
def my_mean(my_list):
"""Calculates the mean of a given list.
Keyword arguments:
my_list (list) -- Given list.
return (float) -- Mean of given list.
"""
return my_sum(my_list)/len(my_list) | 43,367 |
def pr(labels, predictions):
"""Compute precision-recall curve and its AUC.
Arguments:
labels {array} -- numpy array of labels {0, 1}
predictions {array} -- numpy array of predictions, [0, 1]
Returns:
tuple -- precision array, recall array, area float
"""
precision, recall,... | 43,368 |
def done(cursor : sqlite3.Cursor, tableName : str) -> None:
"""_current 테이블의 모든 row를 삭제합니다. 이 함수를 제외한 모든 _current 연산은 기본적으로 row가 없는 것을 전제하기 때문에,
다른 모든 연산들은 전 또는 후에 done()를 해야 합니다."""
cursor.execute("""
DELETE FROM {0}_current""".format(tableName)) | 43,369 |
def copy_routing_table(device):
"""Delete all rows in table, not the table itself"""
for i in Base.metadata.tables.keys():
front_end_table = i.replace('_back_end', '_front_end')
if i == 'routingtable_back_end':
session.execute(f'DELETE FROM public.{front_end_table} WHERE id=... | 43,370 |
def grouped_evaluate(population: list, problem, max_individuals_per_chunk: int = None) -> list:
"""Evaluate the population by sending groups of multiple individuals to
a fitness function so they can be evaluated simultaneously.
This is useful, for example, as a way to evaluate individuals in parallel
o... | 43,371 |
def ZeusPaypalAccounts(request):
""" Zeus Paypal Account Credentials """
if request.method == "GET":
return render(request, "lost-empire/site_templates/zeus/paypal_accounts.html") | 43,372 |
def restart_tamr(
*,
tamr_install_dir: str,
include_dependencies: bool = True,
remote_client: Optional["paramiko.SSHClient"] = None,
impersonation_username: Optional[str] = None,
impersonation_password: Optional[str] = None,
verbose=False,
) -> None:
"""Restarts the Tamr software and the... | 43,373 |
def test_set_workflow_status(app, default_user, _get_user_mock):
"""Test get_workflow_logs view."""
with app.test_client() as client:
with patch(
"reana_server.rest.workflows.current_rwc_api_client",
make_mock_api_client("reana-workflow-controller")(),
):
res ... | 43,374 |
def upper_tri_to_full(n):
"""Returns a coefficient matrix to create a symmetric matrix.
Parameters
----------
n : int
The width/height of the matrix.
Returns
-------
SciPy CSC matrix
The coefficient matrix.
"""
entries = n*(n+1)//2
val_arr = []
row_arr = []... | 43,375 |
def get_job_postings_from_stepstone(url):
"""
docstring
"""
jobplatform_provider="StepStone"
jobposition = "react"
# This url does all the filtering for us, the one thing what does change is the job position
driver.get('https://www.stepstone.de/5/job-search-simple.html?stf=freeText&ns=1&companyid=0&sourc... | 43,376 |
def prod(a, axis=None, dtype=None, out=None, keepdims=False):
"""Returns the product of an array along given axes.
Args:
a (cupy.ndarray): Array to take product.
axis (int or sequence of ints): Axes along which the product is taken.
dtype: Data type specifier.
out (cupy.ndarray)... | 43,377 |
def get_dataset_path(filename):
"""Searches for filename in SEARCH_PATH"""
for p in SEARCH_PATH:
candidate = os.path.join(p, filename)
if os.path.exists(candidate):
print("Found %s in %s" % (filename, candidate))
sys.stdout.flush()
return candidate
raise F... | 43,378 |
def flipUnitsInArea(lPlots, iNewOwner, iOldOwner, bSkipPlotCity, bKillSettlers):
"""Creates a list of all flipping units, deletes old ones and places new ones
If bSkipPlotCity is True, units in a city won't flip. This is to avoid converting barbarian units that would capture a city before the flip delay"""
for tP... | 43,379 |
def test_show_multi_test_fixture_setup_and_teardown_same_as_setup_show(
pytester: Pytester,
) -> None:
"""Verify that SETUP/TEARDOWN messages match what comes out of --setup-show."""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope = 'session')
def sess():
... | 43,380 |
def wait_for_cancelled_sync(timeout: Optional[float] = None) -> None:
"""Synchronously block while waiting for a cancellation request on this
activity.
This is essentially a wrapper around :py:meth:`threading.Event.wait`.
Args:
timeout: Max amount of time to wait for cancellation.
Raises:... | 43,381 |
def sort_dnfs(x, y):
"""Sort dnf riders by code and riderno."""
if x[2] == y[2]: # same code
if x[2]:
return cmp(strops.bibstr_key(x[1]),
strops.bibstr_key(y[1]))
else:
return 0 # don't alter order on unplaced riders
else:
return strops.... | 43,382 |
def gen_diag(dim):
"""generate sparse diagonal matrix"""
diag = torch.randn(dim)
a_sp = sparse.diags(diag.numpy(), format=args.format)
a_pt = _torch_from_scipy(a_sp)
return a_pt, a_sp | 43,383 |
def wave_set_format(wav_file, fmt):
"""
Sets the format for the given WAV file, using the given :class:`AudioFormat`.
Args:
wav_file: A :class:`wave.Wave_write` object.
fmt: A :class:`AudioFormat` object.
"""
wav_file.setnchannels(fmt.num_channels)
wav_file.setsampwidth... | 43,384 |
def one_of(patterns, eql=equal):
"""Return a predicate which checks an object matches one of the patterns.
"""
def oop(ob):
for p in patterns:
if validate_object(ob, p, eql=eql):
return True
return False
return oop | 43,385 |
def SvnDiff(path_to_skdiff, dest_dir, source_dir):
"""Generates a visual diff of all pending changes in source_dir.
@param path_to_skdiff
@param dest_dir existing directory within which to write results
@param source_dir
"""
# Validate parameters, filling in default values if necessary and poss... | 43,386 |
def load_dataset_BlogCatalog3(location):
"""
This method loads the BlogCatalog3 network dataset (http://socialcomputing.asu.edu/datasets/BlogCatalog3)
into a networkx undirected heterogeneous graph.
The graph has two types of nodes, 'user' and 'group', and two types of edges, 'friend' and 'belongs'.
... | 43,387 |
def convert_to_MultiDiGraph(G):
"""
takes any graph object, loads it into a MultiDiGraph type Networkx object
:param G: a graph object
"""
a = nx.MultiDiGraph()
node_bunch = []
for u, data in G.nodes(data = True):
node_bunch.append((u,data))
a.add_nodes_from(node_bunch)
ed... | 43,388 |
def x_to_world_transformation(transform):
"""
Get the transformation matrix from x(it can be vehicle or sensor)
coordinates to world coordinate.
Parameters
----------
transform : carla.Transform
The transform that contains location and rotation
Returns
-------
matrix : np.nd... | 43,389 |
def protobuf_get_constant_type(proto_type) :
"""About protobuf write types see :
https://developers.google.com/protocol-buffers/docs/encoding#structure
+--------------------------------------+
+ Type + Meaning + Used For +
+--------------------------------------+
+ + + i... | 43,390 |
def edit_delivery_products(request, delivery):
"""Edit a delivery (name, state, products). Network staff only."""
delivery = get_delivery(delivery)
if request.user not in delivery.network.staff.all():
return HttpResponseForbidden('Réservé aux administrateurs du réseau '+delivery.network.name)
... | 43,391 |
def test_sampling_general_approach(spark_context):
"""Generate a dataframe and see if sampling it has same general shape"""
# Create wikis with different looking long tail distributions
wikis = [
("foowiki", 1500, -1),
("barwiki", 700, -1),
# This has a very flat long tail, with mos... | 43,392 |
def count_data(cur: psyconpg2.connect, table: str) -> None:
"""Data quality check which counting data in table.
If table count is 0, raise error.
Parameters
----------
cur : psyconpg2.connect
cursor of connection
table : str
table name to check
"""
query = f"""SELECT coun... | 43,393 |
def _tc_imul_ ( self , other ) :
"""Multiplication for TCut objects
>>> cut = ...
>>> other = ...
>>> cut *= other
"""
##
self.strip()
##
if isinstance ( other , num_types ) :
if self : self.SetTitle ( "(%s)*%s" % ( self , other ) )
else : sel... | 43,394 |
def format_locals(sys_exc_info):
"""Format locals for the frame where exception was raised."""
current_tb = sys_exc_info[-1]
while current_tb:
next_tb = current_tb.tb_next
if not next_tb:
frame_locals = current_tb.tb_frame.f_locals
return pprint.pformat(frame_locals)... | 43,395 |
def binarize_garcia(label: str) -> str:
"""
Streamline Garcia labels with the other datasets.
:returns (str): streamlined labels.
"""
if label == 'hate':
return 'abuse'
else:
return 'not-abuse' | 43,396 |
def diagstack(K1,K2):
"""
combine two kernel matrices along the diagonal [[K1 0][0 K2]]. Use to have
two kernels in temporal sequence
Inputs
-------
K1, K2 : numpy arrays
kernel matrics
Returns
--------
matrix of kernel values
"""
r1,c1 = K1.shape
r2,c2 = K2.sh... | 43,397 |
def submit_new_inteface():
"""POST interface configuration from form data"""
global unassigned_ints, interface_nums
ip = None
mask = None
status = None
descr = None
vrf = None
negotiation = None
int_num = [i for i in request.form.get("interface") if i not in string.ascii_letters]
... | 43,398 |
def component_clause(): # type: ignore
"""
component_clause =
type_prefix type_specifier array_subscripts? component_list
"""
return (
syntax.type_prefix,
syntax.type_specifier,
Optional(syntax.array_subscripts),
syntax.component_list,
) | 43,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.