content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _bias_scale(x, b, data_format):
"""The multiplication counter part of tf.nn.bias_add."""
if data_format == 'NHWC':
return x * b
elif data_format == 'NCHW':
return x * b
else:
raise ValueError('invalid data_format: %s' % data_format) | 12,500 |
def checkTableName(tables):
""" Check if table name has an underscore or not."""
bad = set()
output = []
for i in tables:
if re.search('.*_.*', i):
bad.add(i)
if bad:
output.append("These tables have underscores in the name")
for i in bad:
output.appen... | 12,501 |
def Popd():
"""Pops and returns the top of the directory stack.
"""
os.chdir(_dirstack.pop()) | 12,502 |
def global_exception_handler(loop, context) -> None:
"""Global exception handler."""
LOGGER.exception(
"Caught exception: %s", context.get("exception", context["message"])
)
loop.default_exception_handler(context) | 12,503 |
def bluecat():
"""
Collect bluecat data
"""
bluecat_.collect() | 12,504 |
def load_split_from_tfds_builder(builder,
batch_size,
split,
preprocess_example=None,
augment_train_example=None,
shuffle_buffer_size=None,
... | 12,505 |
def load_model_weights(model, filename, verbose=1, cp_folder=""):
"""
Loads the weights of a PyTorch model. The exception handles cpu/gpu incompatibilities
Arguments:
model {torch module} -- Model to load the weights to
filename {str} -- Name of the checkpoint
Keyword Arguments... | 12,506 |
def analyze(tokens):
"""
表达式元素组合,形成操作树
"""
assert_non_empty(tokens)
# 数字或者操作符
token = analyze_token(tokens.pop(0))
# 如果是数字,直接放回就好了,继续求下一个,因为数字是自求解的,本身就是解
if type(token) in (int, float):
return token
# 如果是操作符,则需要组合为Exp表达式
if token in known_operators:
# 当前是操作符, 则需要检... | 12,507 |
def copy_dict(dic: Mapping[str, Any], depth: int = 1) -> Mapping[str, Any]:
"""Deep copy a dict
Args:
dic: The dict to be copied
depth: The depth to be deep copied
Returns:
The deep-copied dict
"""
if depth <= 1:
return dic.copy()
return {
key: copy_dic... | 12,508 |
def set_token(jq_mob, jq_pwd):
"""
:param jq_mob: str
mob是申请JQData时所填写的手机号
:param jq_pwd: str
Password为聚宽官网登录密码,新申请用户默认为手机号后6位
:return: None
"""
with open(file_token, 'wb') as f:
pickle.dump([jq_mob, jq_pwd], f) | 12,509 |
def get_wrf_config(wrf_config, start_date=None, **kwargs):
"""
precedence = kwargs > wrf_config.json > constants
"""
if start_date is not None:
wrf_config['start_date'] = start_date
for key in kwargs:
wrf_config[key] = kwargs[key]
return wrf_config | 12,510 |
def pdb_to_structure(filename):
"""Import a structure object from a PDB file.
"""
try:
from Bio import PDB
except ImportError:
print("I can't import Biopython which is needed to handle PDB files.")
raise
p = PDB.PDBParser()
structure = p.get_structure("S", filename)
... | 12,511 |
def allocation_ncsist():
"""
Real Name: Allocation NCSIST
Original Eqn: IF THEN ELSE( ShiMen Reservoir Depth>=ShiMenReservoir Operation Rule Lower Limit , 6048, IF THEN ELSE( ShiMen Reservoir Depth >=ShiMenReservoir Operation Rule Lower Severe Limit, 6048*0.9 , 6048*0.8 ) )
Units: m3
Limits: (N... | 12,512 |
def hamming(s1, s2):
"""Return the hamming distance between 2 DNA sequences"""
return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2)) + abs(len(s1) - len(s2)) | 12,513 |
def extract_geometric_plane(polygon: Polygon, plane_triangle_indices, tri_mesh: HalfEdgeTriangulation, normal: np.ndarray):
"""Will extract geometric details from the polygon and plane of interest
Args:
polygon (Polygon): Shapely Polygon of a flat surface
plane_triangle_indices (ndarray uint64)... | 12,514 |
def get_org_df(pr_label_f, metadata_df, seq_len):
"""
Returns the org_df given pr_label_f,metadata_df,
"""
org_r, org_c = torch.nonzero(pr_label_f, as_tuple=True)
org_df = cudf.DataFrame()
org_df["seq_row"] = cudf.Series(org_r)
org_df["org_seq_col"] = cudf.Series(org_c)
org_df = org_... | 12,515 |
def rotate_cube(cube, up_direction):
"""Generator function that rotates the cube clockwise around the given up_direction"""
while True:
for i in range(SIZE * 4 - 4):
c = cube.copy()
for layer in range(SIZE // 2):
# layer 0 is outermost
layer_size = SIZE * 4 - 4 - 8 * layer
la... | 12,516 |
def binomial_proportion(nsel, ntot, coverage=0.68):
"""
Calculate a binomial proportion (e.g. efficiency of a selection) and its confidence interval.
Parameters
----------
nsel: array-like
Number of selected events.
ntot: array-like
Total number of events.
coverage: float (optio... | 12,517 |
def nasnet_dual_path_scheme_ordinal(module,
x,
_):
"""
NASNet specific scheme of dual path response for an ordinal module with dual inputs/outputs in a DualPathSequential
module.
Parameters:
----------
module : nn.Module
... | 12,518 |
def ifttt_budget_options():
""" Option values for the budget field """
if "IFTTT-Service-Key" not in request.headers or \
request.headers["IFTTT-Service-Key"] != get_ifttt_key():
return json.dumps({"errors": [{"message": "Invalid key"}]}), 401
try:
data = get_ynab_budgets()
... | 12,519 |
def get_exp_date_stats(db_file_name, Table):
"""Caculate exp date stats of collection"""
conn = sqlite3.connect(db_file_name)
c = conn.cursor()
c.execute('''SELECT exp, count(exp) FROM {} GROUP BY exp'''.format(Table))
exp_dict = {}
results = c.fetchall()
for result in results:
exp... | 12,520 |
def create_default_identifier(node_address, token_address, target):
"""
The default message identifier value is the first 8 bytes of the sha3 of:
- Our Address
- Our target address
- The token address
- A random 8 byte number for uniqueness
"""
hash_ = sha3('{}{}{}{}'.for... | 12,521 |
def set_layers_to_non_trainable(model, layers):
""" Set layers of a model to non-trainable """
layers_to_non_trainable = [model.layers[i] for i in layers]
for layer in layers_to_non_trainable:
layer.trainable = False
for layer in model.layers:
logging.debug("Layer %s is trainable: %s"... | 12,522 |
def print_scientific_16(value: float) -> str:
"""
Prints a value in 16-character scientific notation.
This is a sub-method and shouldnt typically be called
.. seealso:: print_float_16 for a better method
"""
if value == 0.0:
return '%16s' % '0.'
python_value = '%16.14e' % value # ... | 12,523 |
def _interpolate_target(bin_edges, y_vals, idx, target):
"""Helper to identify when a function y that has been discretized hits value target.
idx is the first index where y is greater than the target
"""
if idx == 0:
y_1 = 0.
else:
y_1 = y_vals[idx - 1]
y_2 = y_vals[idx]
edg... | 12,524 |
def process_alpha(alpha, experiments, filename):
"""
Save experiment results to CSV file
:param alpha: Value of alpha to run for
:param experiments: List of (data, dictionary) for experiments ('no_normalization', 'd_normalization', 'x_normalization', 'full_normalization')
:param filename: filename f... | 12,525 |
def reinstall_fonts_sb(fonts_path):
"""
Reinstall all fonts.
"""
print_section_header("REINSTALLING FONTS", Fore.BLUE)
# Copy every file in fonts_path to ~/Library/Fonts
for font in get_abs_path_subfiles(fonts_path):
font_lib_path = get_fonts_dir()
dest_path = os.path.join(font_lib_path, font.split("/")[-1])
... | 12,526 |
def azimuth_range_to_lat_lon(azimuths, ranges, center_lon, center_lat, geod=None):
"""Convert azimuth and range locations in a polar coordinate system to lat/lon coordinates.
Pole refers to the origin of the coordinate system.
Parameters
----------
azimuths : array_like
array of azimuths d... | 12,527 |
def count_path_recursive(m, n):
"""Count number of paths with the recursive method."""
def traverse(m, n, location=[1, 1]):
# return 0 if past edge
if location[0] > m or location[1] > n:
return 0
# return 1 if at end position
if location == [m, n]:
return ... | 12,528 |
def markdown(caller):
"""Renders the argument to markdown. Useful in `{% filter markdown() %} `
blocks
Args:
caller (str): Markdown source
Returns:
str: rendered HTML
"""
return render_markdown(caller) | 12,529 |
def aggregate_threedi_results(gridadmin: str, results_3di: str, demanded_aggregations: List[Aggregation],
bbox=None, start_time: int = None, end_time: int = None, subsets=None, epsg: int = 28992,
interpolation_method: str = None, resample_point_layer: bool = F... | 12,530 |
def color_menu(colno: int, colname: str, entry: Dict[str, Any]) -> int:
# pylint: disable=unused-argument
"""color the menu"""
if entry.get("__shadowed") is True:
return 8
if entry.get("__deprecated") is True:
return 9
return 2 | 12,531 |
def likelihood(sent, ai, domain, temperature):
"""Computes likelihood of a given sentence according the giving model."""
enc = ai._encode(sent, ai.model.word_dict)
score, _, _= ai.model.score_sent(enc, ai.lang_h, ai.ctx_h, temperature)
return score | 12,532 |
def simulator(
theta,
model="angle",
n_samples=1000,
delta_t=0.001, # n_trials
max_t=20,
no_noise=False,
bin_dim=None,
bin_pointwise=False,
):
"""Basic data simulator for the models included in HDDM.
:Arguments:
theta : list or numpy.array or panda.DataFrame
... | 12,533 |
def logical_not(x: ArrayOrScalar) -> Union[Array, bool]:
"""
Returns the element-wise logical NOT of *x*.
"""
if isinstance(x, SCALAR_CLASSES):
# https://github.com/python/mypy/issues/3186
return np.logical_not(x) # type: ignore
assert isinstance(x, Array)
from pytato.utils im... | 12,534 |
def _build_xyz_pow(name, pref, l, m, n, shift=2):
"""
Builds an individual row contraction line.
name = pref * xc_pow[n] yc_pow[m] * zc_pow[n]
"""
l = l - shift
m = m - shift
n = n - shift
if (pref <= 0) or (l < 0) or (n < 0) or (m < 0):
return None
mul = " "
if pref =... | 12,535 |
def create_decode_network(width=width, height=height, Din=Din, Dout=Dout, d_range=d_range):
"""
data flow with traffic on:
input IO ->
tag horn ->
(pre-fifo valve) ->
FIFO ->
(post-fifo valve) ->
TAT ->
AER_tx ->
neurons ->
AER_rx ->
(neuron output valve) ->
PAT ... | 12,536 |
def canny(img, low_threshold, high_threshold):
"""Applies the Canny transform"""
return cv2.Canny(img, low_threshold, high_threshold) | 12,537 |
def pscmd(item, pid=os.getpid()):
"""Invoke ps -o %(item)s -p %(pid)d and return the result"""
pscmd = PSCMD
if item == 'sid' and os.uname()[0] == 'AIX':
pscmd = '/usr/sysv/bin/ps'
if item == 'sid' and os.uname()[0] == 'Darwin':
item = 'sess'
assert pscmd, 'ps command not found (%s),... | 12,538 |
def dGcthetalnorm(w: Wilson, cthetal):
"""Normalized distribution 1D cthetal"""
return tauBp / Btaul * dGcthetal(w, cthetal) | 12,539 |
def test_image_signatures():
"""Test image signatures."""
for method in dir(Image):
if method.startswith('_'):
continue
method_signature = signature(getattr(Image, method)).parameters
base_signature = signature(getattr(BaseImage, f'_{method}')).parameters
specific_ar... | 12,540 |
def user_deposit_address_fixture(
deploy_smart_contract_bundle_concurrently: FixtureSmartContracts,
) -> Optional[UserDepositAddress]:
""" Deploy UserDeposit and fund accounts with some balances """
services_smart_contracts = deploy_smart_contract_bundle_concurrently.services_smart_contracts
if service... | 12,541 |
def vonNeumann(t, rho, H):
"""(quantum Liouville-)von Neumann equation"""
H = H(t)
rho = rho.reshape(H.shape)
rho_dot = -1j*(np.dot(H, rho) - np.dot(rho, H))
return rho_dot.flatten() | 12,542 |
def conjure_categories(path):
"""
Look for all pngs in the path. They are generated by quicklook.py and organised into
folders by resolution. Each resolution has a number of variables associated to it
and each variable can have a number of vertical levels and lead times associated to
it. We want to... | 12,543 |
def nicer_array(a, mm_cutoff=0.3):
"""
Returns a scaled array, the scaling, and a unit prefix
Example:
nicer_array( np.array([2e-10, 3e-10]) )
Returns:
(array([200., 300.]), 1e-12, 'p')
"""
if np.isscalar(a):
x = a
elif len(a) == 1:
x = a[0... | 12,544 |
def sender(cl, stanza, cb=None, args={}):
"""
Sends stanza. Writes a crashlog on error
Parameters:
cl: the xmpp.Client object
stanza: the xmpp.Node object
cb: callback function
args: callback function arguments
"""
if cb:
cl.SendAndCallForResponse(stanza, cb, args)
else:
try:
cl.send(stanza)
exce... | 12,545 |
async def test_setting_attribute_with_template(hass, mqtt_mock):
"""Test the setting of attribute via MQTT with JSON payload."""
await help_test_setting_attribute_with_template(
hass, mqtt_mock, number.DOMAIN, DEFAULT_CONFIG
) | 12,546 |
async def _process_recorder_platform(
hass: HomeAssistant, domain: str, platform: Any
) -> None:
"""Process a recorder platform."""
instance: Recorder = hass.data[DATA_INSTANCE]
instance.queue_task(AddRecorderPlatformTask(domain, platform)) | 12,547 |
def build_playground():
"""
build a playground based on user's input building and algorithm type
input: userid, algorithm, target building
output: none
"""
userid, building, algo_type = request.form['userid'], request.form['building'], request.form['algo_type']
user = User.objects(userid=use... | 12,548 |
def menuItemDirective(_context, menu, for_,
action, title, description=u'', icon=None, filter=None,
permission=None, layer=IDefaultBrowserLayer, extra=None,
order=0, item_class=None):
"""Register a single menu item."""
return menuItemsDirective(_... | 12,549 |
def getQueueStatistics ():
"""
Returns a 4-tuple containing the numbers of identifiers in the
Crossref queue by status: (awaiting submission, submitted,
registered with warning, registration failed).
"""
q = ezidapp.models.CrossrefQueue.objects.values("status").\
annotate(django.db.models.Count("status"... | 12,550 |
def assign_targeting_score_v2(
base,
manual_selected_objids=None,
gmm_parameters=None,
ignore_specs=False,
debug=False,
n_random=50,
seed=123,
remove_lists=None,
low_priority_objids=None,
**kwargs,
):
"""
Last updated: 05/19/2020
100 Human selection and Special targe... | 12,551 |
def authenticate(controller, password = None, chroot_path = None, protocolinfo_response = None):
"""
Authenticates to a control socket using the information provided by a
PROTOCOLINFO response. In practice this will often be all we need to
authenticate, raising an exception if all attempts to authenticate fail.... | 12,552 |
def test_sum():
"""
test sum pattern 1, 11, 10, 01, 001, 010, 100, 110, 011, 111, 0011, 0101, 0111, 1011, 1111
test sum pattern implemented with reshape:
1000, 0100, 0010, 0001, 11111
others implemented by reshape that are not tested
0011,0101,0110,1001,1010,1100
1110,1101,1011
TODO: ... | 12,553 |
def test_ctm_distribution_d1(nsymbols):
"""Check normalization of CTM distributions."""
bdm = BDM(ndim=1, nsymbols=nsymbols)
total = 0
for dct in bdm._ctm.values():
for key, cmx in dct.items():
n = len(set(key))
mult = factorial(nsymbols) / factorial(nsymbols - n)
... | 12,554 |
def naive(edges: List[Edge[T]]) -> Iterator[Matching[T]]:
"""Enumerate best matchings"""
MAX_HEAPSIZE = 100
graph = nx.Graph()
for n1, n2, w in edges:
graph.add_node(n1)
graph.add_node(n2)
graph.add_edge(n1, n2, weight=w)
if not bprt.is_bipartite(graph):
raise Runtim... | 12,555 |
def create_compressed_generator(
original_generator: CompressorArg,
compressed_cse_list: List[List[Union[List[uint64], List[Union[bytes, None, Program]]]]],
) -> BlockGenerator:
"""
Bind the generator block program template to a particular reference block,
template bytes offsets, and SpendBundle.
... | 12,556 |
def parse(path):
"""
Returns generator which yields Quotes
"""
with codecs.open(path, 'r') as f:
while f.readline():
f.readline()
f.readline()
line4 = f.readline()
f.readline()
# title, author = re.findall(r'^(.*) \((.*)\)$', line1)[0]... | 12,557 |
def csv_to_db_func(file_name):
"""The function reads a file that was uploaded by the user to the server.
It creates connection to the database and that file was dumped to the database.
: param file_name : csv file uploaded by the user."""
logging.info("Welcome to csv func")
df_data = pd.rea... | 12,558 |
def run_mcmc(meas, x, nsamples, covm=None, scales=None):
"""
Sample the likelihood space with a Markov Chain Monte Carlo.
:param meas: TemplateMeasurement
measurement whose spectrum likelihood space is to be probe
:param x: [float]
parameter values where to start the chain
:param co... | 12,559 |
def unconfig_extended_acl(device,acl_name):
""" Unconfigure the extended acls
Args:
device ('obj'): device to use
acl_name ('str'): name of acl
Returns:
None
Raises:
SubCommandFailure
"""
try:
device.configure(["no ip access-lis... | 12,560 |
def get_vlan_list(dut, cli_type="click"):
"""
Get list of VLANs
Author : Prudvi Mangadu (prudvi.mangadu@broadcom.com)
:param dut:
:param cli_type:
:return:
"""
st.log("show vlan to get vlan list")
rv = show_vlan_config(dut, cli_type=cli_type)
vlan_list = list(set([eac['vid'] for... | 12,561 |
def begin_organization_creation_task(registered_id):
"""
Asynchronously create our tenant schema. Email owner when process completes.
"""
# Run the sub-routine for taking the OrganizationRegistration object
# creating our Tenant from it.
call_command('populate_organization', str(registered_id)) ... | 12,562 |
def rewrite_blockwise(inputs):
"""Rewrite a stack of Blockwise expressions into a single blockwise expression
Given a set of Blockwise layers, combine them into a single layer. The provided
layers are expected to fit well together. That job is handled by
``optimize_blockwise``
Parameters
---... | 12,563 |
def sort_drugs(processed_data, alpha_sort, **kwargs):
"""
Sorts all drug names, as primary keys of processed data dictionary. Sorting
is governed by primary criteria of decreasing cost, then secondary criteria
of alphabetical order. Secondary criteria ignores unsafe characters if
"alpha_sort" is Tru... | 12,564 |
def log_k2ex_and_get_msg(ex, prefix, topology):
""" LOG K2 exception and extracted message. Return NLS message """
LOG.exception(ex)
detail = {}
k2msg = _("None")
if isinstance(ex, K2Error) and ex.k2response:
detail['Request_headers'] = ex.k2response.reqheaders
detail['Response_heade... | 12,565 |
def fetch_ticket(identifier):
"""Return data of ticket with given identifier as pandas dataframe."""
try:
return pd.read_csv(f'./data/tickets/{identifier}.csv')
except:
return None | 12,566 |
def dice_loss(logits, targets, smooth=1.0):
"""
logits: (torch.float32) shape (N, C, H, W)
targets: (torch.float32) shape (N, H, W), value {0,1,...,C-1}
"""
outputs = F.softmax(logits, dim=1)
targets = torch.unsqueeze(targets, dim=1)
targets = torch.zeros_like(logits).scatter_(dim=1, index=targets.type(torch.in... | 12,567 |
def deltaG_methanogenesis_early_Earth(T, pCO2, pH2, pCH4):
"""
Equation: CO2 (g) + 4H2 (g) --> CH4 (g)+ 2H2O (l)
Assumes bar, 1bar total pressure, for gases.
T must be array (even if just 1 entry)
"""
R=8.314E-3 #kJ mol^-1 K^-1
deltaG_0=deltaG_F_PSat_T_CH4_g(T)+2.0*deltaG_F_PSat_T_H2O_l... | 12,568 |
def optimize_on_joints(j2d,
model,
cam,
img,
prior,
try_both_orient,
body_orient,
n_betas=10,
regs=None,
conf=Non... | 12,569 |
def make_axis_angle_matrix(axis, angle):
"""construct a matrix that rotates around axis by angle (in radians)"""
#[RMS] ported from WildMagic4
fCos = math.cos(angle)
fSin = math.sin(angle)
fX2 = axis[0]*axis[0]
fY2 = axis[1]*axis[1]
fZ2 = axis[2]*axis[2]
fXYM = axis[0]*axis[1]*(1-fCos)
... | 12,570 |
def get_agent_type_from_project_type():
""" use project type to determine agent type """
if 'METRIC' in if_config_vars['project_type']:
if if_config_vars['is_replay']:
return 'MetricFileReplay'
else:
return 'CUSTOM'
elif if_config_vars['is_replay']:
return 'Lo... | 12,571 |
def close_server(is_rebooting = False):
"""
Close the Unity server and tell clients to react appropriately.
Set `is_rebooting` to handle cases like domain reload when Unity is expected to come back shortly.
Returns True if the server was closed by this call, False if it was already closed.
"""
... | 12,572 |
def pip_install(path: PathType, package_name: str) -> ContextManagerFunctionReturnType[None]:
"""
Installs a package with pip located in the given path and with the given name.
This method is intended to use with `with`, so after its usage, the package will be
uninstalled.
"""
pip_main(["instal... | 12,573 |
def dict_decode(node_dict: dict) -> Node:
"""Convert a dictionary to an `Entity` node (if it has a `type` item)."""
if "type" not in node_dict:
return node_dict
node_type = node_dict.pop("type")
class_ = getattr(types, node_type, None)
if class_ is None:
return node_dict
node_... | 12,574 |
def compute_purges(snapshots, pattern, now):
"""Return the list of snapshots to purge,
given a list of snapshots, a purge pattern and a now time
"""
snapshots = sorted(snapshots)
pattern = sorted(pattern, reverse=True)
purge_list = []
max_age = pattern[0]
# Age of the snapshots in minute... | 12,575 |
def design_partial_factorial(k: int, res: int) -> DataFrame:
"""
design_partial_factorial
This function helps design 2 level partial factorial experiments. These experiments are often
described using the syntax l**(k-p) where l represents the level of each factor, k represents
the total number of f... | 12,576 |
def title_first_word(field: Field = None) -> Optional[str]:
"""
Returns an uppercase first word (skipping any articles) of
the title field (245 MARC tag subfield $a).
Args:
field: pymarc.Field instance
Returns:
word
"""
pass | 12,577 |
def train(model, target_label=1, epochs=1, learning_rate=5.0):
""" Learns the patch for taget_label
Args:
model: Model to be trained (ModelContainer object)
target_label: Target label for which the patch will be trained
epochs: Number of iteration through the training set
Returns:
... | 12,578 |
def find_latest(message_ts: str, post_dir: Path) -> str:
"""Retrieves the latest POST request timestamp for a given message."""
latest_ts = message_ts
for postfile in os.listdir(os.fsencode(post_dir)):
if (filename := os.fsdecode(postfile)).endswith('.json'):
request_ts = filename.strip(... | 12,579 |
def command_line_code_generation(filename, language, out_path=None):
"""Starts a code generator without starting the GUI.
filename: Name of wxg file to generate code from
language: Code generator language
out_path: output file / output directory"""
from xml_parse import CodeWriter
try:
... | 12,580 |
def get_trending_queries(filename):
"""Extract trends from a file."""
f = open(filename, 'r')
trend_tuples_list = []
for line in f:
trend_tuples_list.append(tuple((line.strip()).split(',')))
f.close()
return trend_tuples_list | 12,581 |
def get_bio(x, lang='en'):
"""Get the one-sentence introduction"""
bio = x.loc[16][lang]
return bio | 12,582 |
def create_tf_example(filename, source_id, encoded_jpeg, annotations, resize=True):
"""
This function creates a tf.train.Example in object detection api format from a Waymo data frame.
args:
- filename [str]: name of the original tfrecord file
- source_id [str]: original image source id (he... | 12,583 |
def format_oids(oids_parameters):
"""
Format dictionary OIDs to ``cryptography.x509.oid.NameOID`` object list
:param oids_parameters: CA Object Identifiers (OIDs).
The are typically seen in X.509 names.
Allowed keys/values:
``'country_name': str (two letters)``,
``'locality_... | 12,584 |
def Phases(*args):
"""Number of phases"""
# Getter
if len(args) == 0:
return lib.Generators_Get_Phases()
# Setter
Value, = args
lib.Generators_Set_Phases(Value) | 12,585 |
def create_channel(logger: Logger,
connection: komand.connection,
team_id: str,
channel_name: str,
description: str) -> bool:
"""
Creates a channel for a given team
:param logger: (logging.logger)
:param connection: Object (kom... | 12,586 |
def getMoveValue(board, table, depth, move):
""" Sort criteria is as follows.
1. The move from the hash table
2. Captures as above.
3. Killers.
4. History.
5. Moves to the centre. """
# As we only return directly from transposition table if hashf == hashfEXACT
#... | 12,587 |
def activate_user(username):
"""Activate a user account."""
user = annotator.credentials.find_one({'username': username})
if not user['active']:
annotator.credentials.update_one(user, {'$set': {'active': True}})
flash("User {0} activated successfully".format(username), 'success')
else:
... | 12,588 |
def query_all():
"""Queries all matches in Elasticsearch, to be used further for suggesting
product names when a user is not aware of them.
"""
query_all = {
"query": {"match_all": {}},
}
return query_all | 12,589 |
def cmd():
"""
A command-line interface for downloading wildfire perimeter and incident points data from NIFC.
Returns GeoJSON.
"""
pass | 12,590 |
def _mesh_homogeneous_cell(cell_vect, mesh_path):
"""Generate a simple mesh for a homogeneous cell.
cell_vect: np.array 2x2 colonnes = vecteurs periodicité
"""
name = mesh_path.stem
geometry.init_geo_tools()
geometry.set_gmsh_option("Mesh.MshFileVersion", 4.1)
# Mesh.Algorithm = 6; Frontal... | 12,591 |
def test_get_effective_tip_length(
mock_labware_store: MagicMock,
geometry_store: GeometryStore
) -> None:
"""It should get the effective tip length from a labware ID and pipette config."""
pipette_config: PipetteDict = cast(PipetteDict, {
"tip_overlap": {
"default": 10,
... | 12,592 |
async def async_setup_entry(hass, config_entry):
"""Initialize the sharkiq platform via config entry."""
ayla_api = get_ayla_api(
username=config_entry.data[CONF_USERNAME],
password=config_entry.data[CONF_PASSWORD],
websession=hass.helpers.aiohttp_client.async_get_clientsession(),
)
... | 12,593 |
def fetch_incidents(client: Client, max_incidents: int,
last_run: Dict[str, Union[Optional[int], Optional[str]]], first_fetch: Optional[int],
priority: Optional[str], activity_status: Optional[str],
progress_status: Optional[str], business_units: Optional[str]... | 12,594 |
def extractWordFeatures(x):
"""
Extract word features for a string x. Words are delimited by
whitespace characters only.
@param string x:
@return dict: feature vector representation of x.
Example: "I am what I am" --> {'I': 2, 'am': 2, 'what': 1}
"""
# BEGIN_YOUR_CODE (our solution is 4... | 12,595 |
def delete_user(user_id):
"""
Delete user specified in user ID
Note: Always return the appropriate response for the action requested.
"""
user = mongo_mgr.db.user.find_one({'_id': user_id})
if user:
user.deleteOne({'_id': user_id})
result = {'id': user_id}
else:
resul... | 12,596 |
def query_attention_one(**kwargs):
"""
查询当前用户是否关注指定的物件
:param kwargs: {'user_id': user_id, 'object_id': object_id}
:return: 0 or 1
"""
session = None
try:
session = get_session()
results = session.query(func.count('*')).filter(and_(Attention.OPEN_ID == kwargs['user_id'],
... | 12,597 |
def _dict_empty_map_helper(values, empty, delim, av_separator, v_delimiter,
parser):
"""
A helper to consolidate logic between singleton and non-singleton mapping.
Args:
values: The value to parse.
empty: The empty representation for this value in CoNLL-U format.
... | 12,598 |
def get_full_json(msa, component, sessionkey, pretty=False, human=False):
"""
Form text in JSON with storage component data.
:param msa: MSA DNS name and IP address.
:type msa: tuple
:param sessionkey: Session key.
:type sessionkey: str
:param pretty: Print in pretty format
:type pretty... | 12,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.