content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def file_import(**kwargs):
"""
Fast import of exported log files containing messages from a bus.
Optional arguments:
- folder (str): Custom folder to import log files from.
- limit (int): The maximum number of lines/messages to read each time. Default value is '5000'.
- idle_sleep (int): ... | d284dde2623e5f7ff982865e99eeaebbb5e7fedd | 53,500 |
def main(useruid: str, old_passwd: str, new_passwd: str, email: str):
"""
修改個資
"""
user = User(useruid)
session = get_empty_session()
session.login(
user.userid, old_passwd, session.courses.index(user.course) + 1)
if session.active:
session = get_session(useruid)
i... | 7a303323a6421c4fd850ede18c85af1cd9cd5f72 | 53,501 |
from sys import path
def isexe(fpath):
"""Test if a file is executable.
Parameters
----------
fpath : path_like
Path to the file.
Returns
------
result : bool
Whether the file is executable.
"""
return path.exists(fpath) and access(fpath, X_OK) | ac150b84e499123e6ad14b762b61382176eb3952 | 53,502 |
import requests
def check_user_permission(access_token, job_requires):
"""
Check if user has permission to run the job or not
Args:
access_token(str): the access token
job_requires(dict): requirements so that job can run
{
"arborist_url": "http://arborist-servi... | c1069364b8d59965f78367e64b88206062c60b2b | 53,503 |
def FiskJohnsonDiscreteFuncExtrapolate(rho,F0,T):
"""Extrapolate samples of transform to sequence of target coordinates.
Extrapolate sequence of (few) Fourier-Bessel transform samples to
sequence of target coordinates following Eq. (9) of Ref. [1].
Args:
rho (numpy array, ... | ae5c86d1e616dc77404165d9df9a0e8b063cec61 | 53,504 |
def media_entity(props):
"""
Helper to construct elements of the form
<embed embedtype="custommedia" id="1"/>
when converting from contentstate data
"""
return DOM.create_element('embed', {
'embedtype': 'wagtailmedia',
'id': props.get('id'),
'title': props.get('title'),
... | 3cdaef6c88e88551a594a38f99c2c48344b27163 | 53,505 |
def ws_s_dt_wa_gauss(ws, wa, *params):
"""Models the function
\\[
\\frac{a_2}{1 + e^{a_0 - a_1x}} - a_3x^2 +
+ a_4\\exp\\left(\\frac{-(y - a_5)^2}{2a_6}\\right)
+ a_7\\exp\\left(\\frac{-((360 - y) - a_8)^2}{2a_9}\\right)
\\]
"""
wa = np.asarray(wa)
return (
s_sha... | 3c17ab5adb3ff71257f360d5caf3eb6a72e2b823 | 53,506 |
import sys
def get_bulk_selections(config: models.Config) -> models.Config:
"""Gets input in bulk mode if the user wants to only download specific consoles"""
print("Press Enter to download all of Vimm's roms or select from the" +
" following of what systems you would like to download")
print('E... | 3d29fb2c9397e969a5d4b3c113eab10936eaa4cd | 53,507 |
import io
def get_version(relpath):
"""Read version info from a file without importing it"""
for line in io.open(join(dirname(__file__), relpath), encoding="cp437"):
if "__version__" in line:
if '"' in line:
return line.split('"')[1]
elif "'" in line:
return line.split("'")[1] | 0e06b67f0aa44d84b9dfddfdb040e63534329fe8 | 53,508 |
def slice_array_d50(df,idNode):
"""
This function allows to slice the array resulting from the create_array function. The slicing is performed
by a boolean mask in which the array is filtered according to the ID_Node specified by the user and then
only the columns corresponding to time and mean diameter... | 565c4ea76de08a493f028e32052fcef60e7f42dd | 53,509 |
def to_upper(string):
"""The upper case version of a string"""
return string.upper() | 8d3bb60b7b4704479cb642b9ab910f7a1469fd44 | 53,510 |
def is_printable_as_block_string(value: str) -> bool:
"""Check whether the given string is printable as a block string.
For internal use only.
"""
if not isinstance(value, str):
value = str(value) # resolve lazy string proxy object
if not value:
return True # emtpy string is prin... | aab23c58fdbd3bd505392dff0224a9f342ca6afb | 53,511 |
def inbox(request, search_type='', search_word='', page=0, box=''):
"""Inbox"""
if int(page) < 1:
page = 1
list_count = settings.INBOX_LIST_COUNT
current_page = int(page) - 1
start_at = current_page * list_count
end_at = start_at + list_count
if box == 'inbox':
sq = (~Q(use... | 813ec39d77f0438d7fd5b54ef8f7847d108a3cbb | 53,512 |
def _after_arg(arg_name):
"""Return a finder for argument after arg_name."""
def generate(transform):
"""Generate three args, OTHER, arg_name and ARGUMENT."""
return "ONE {0} {1}".format(arg_name, transform("ARGUMENT"))
return generate | 0a0306760e8e9a2ad356a4f2d9ae2c6b76d53d2e | 53,513 |
import numpy
def load_cifar(dataset="training", path="cifar"):
"""
The Cifar Loading Method.
:param dataset: 'training' or 'testing', depending on the data to load
:param path: path to the cifar files
:return: X,y: data and labels
"""
if dataset == "training":
X = numpy.ndarray([50... | 92eb76ef9466bc6c04beed24d3c0b4587b24df2a | 53,514 |
def get_data_files(split, dataset_config):
"""
Get the path to the dataset (images and labels).
1. If the user has explicitly specified the data_sources, we simply
use those and don't do lookup in the datasets registered with VISSL
from the dataset catalog.
2. If the user h... | 392c618bfe602c66fcb2cbd56924f33d364c0a1e | 53,515 |
def create_s3_bucket(session, bname, region):
"""
IAM Permission Required:
- s3:CreateBucket
"""
try:
s3 = session.client('s3')
req = {
"Bucket": bname,
"ACL": "private"
}
if region != "us-east-1":
tmpObj = {
"L... | b7f1d07763db020a74968b93d4818efab1383abf | 53,516 |
def compute_predictions(example, n_best_size=10, max_answer_length=30):
"""
Converts an example into an NQEval object for evaluation.
:param example: EvalExample
:return: ScoreSummary
"""
predictions = []
for unique_id, result in example.results.items():
if unique_id not in example.... | ffdb662d0bfd2841caef18e64799685df79373e7 | 53,517 |
def validate_create_namespace(result, name):
"""
Validation function for integration testcases
"""
return name in get_system_namespace_list() | 075590d42d357b5410cd7b3bf152842cae9f6d92 | 53,518 |
def log5(request):
"""log5 is a version of log3 without conclusion. It is meant for
the version that has artificial words as terms in the syllogism."""
if request.method == "GET":
bValid = True
(usernumber_str, bValid) = getValue(request, u"uid", bValid)
(timelapse_str, bValid) = get... | e103f8f29deb751669722738df66a8933d2b8eac | 53,519 |
import torch
def load_datasets(args):
"""load the dataset (ColonDataset) and split the dataset into train and validation set
Args:
args: arguments from the parser.
Return:
train_dataset: a dataset for training
val_dataset: a dataset for validation
"""
dataset =... | ba8d0594a456f7878dffaa4dae4a7cec34179e82 | 53,520 |
import os
def read_FMI_weather(ID, start_date, end_date, sourcefile, CO2=380.0):
"""
reads FMI OBSERVED daily weather data from file
IN:
ID - sve catchment ID. set ID=0 if all data wanted
start_date - 'yyyy-mm-dd'
end_date - 'yyyy-mm-dd'
sourcefile - optional
CO2 - ... | 4e9d3c2187a52aa19a15ca368feb568a9e407901 | 53,521 |
def _get_unstarted_workflows():
"""Get a list of all workflows that should have a cycle started.
This function is used for fixing failed cycle starts.
Returns:
list of workflows that are missing any started cycles.
"""
return db.session.query(Workflow).filter(
Workflow.next_cycle_start_date < date... | 142853795f2b77fc61db01b2d85c85dedb996f10 | 53,522 |
def parse_list(elem):
"""Parse list of properties.
>>> parse_list(ET.XML('<Property />'))
[]
>>> xml = '''<Property>
... <Property>Hello</Property>
... <Property>World</Property>
... </Property>'''
>>> parse_list(ET.XML(xml))
['Hello', 'World']
"""... | a1fdb641fab345bc81ec1bd4891eb0d185ed4104 | 53,523 |
import os
import subprocess
from datetime import datetime
def changelog_contents(changelog_releases: str='') -> str:
"""
Generate the changelog and return the contents as a string
Parameters
----------
changelog_releases: str, optional
Comma separated list of releases to include in the ch... | 1c0602c6f4f4a19483c7551ab1aeb18e79749886 | 53,524 |
import collections
import fnmatch
import sys
def get_notes_by_version(reporoot, notesdir, branch=None):
"""Return an OrderedDict mapping versions to lists of notes files.
The versions are presented in reverse chronological order.
Notes files are associated with the earliest version for which
they we... | 561d987a14595582b068e072e3757b09ca4f9036 | 53,525 |
def deltaF(int_list, f_0_win=5):
""" Function for colculation ΔF/F0 for data series.
f_0_win - window for F0 calculation (mean of first 2 values by defoult).
"""
f_0 = np.mean(int_list[:f_0_win])
return np.asarray([(i - f_0)/f_0 for i in int_list]) | 6c43832c67811379ab125e34952afc5880a0cd11 | 53,526 |
def calculate_rcplvs(lv):
"""
Convert cartesian lattice vectors to the fractional lattice vectors
Args:
lv (:py:attr:`array_like`, optional): Lattice vectors
Returns:
rcplvs (:py:attr:`array_like`, optional): Reciprcocal lattice vectors
lengths (:py:attr:`array_like`, optional)... | 2be1e78289f209d87cff54177fcb24c9982f4939 | 53,527 |
import torch
def get_src_xyz_from_plane_disparity(meshgrid_src_homo,
mpi_disparity_src,
K_src_inv):
"""
:param meshgrid_src_homo: 3xHxW
:param mpi_disparity_src: BxS
:param K_src_inv: Bx3x3
:return:
"""
B, S = mpi_d... | 91492ba8782607e8500de5b886f9339b041a3513 | 53,528 |
import torch
def reduce_loss_dict(loss_dict):
"""
Reduce the loss dict from all processes so that process with rank 0 has the averaged results.
Returns a dict with the same fields as loss_dict, after reduction.
"""
world_size = get_world_size()
if world_size < 2:
return loss_dict
w... | ecbc363a9e7df4978a2bf81ffeb2e8f6d5636796 | 53,529 |
def geoserver_cascading_delete(self, *args, **kwargs):
"""
Runs cascading_delete.
"""
lock_id = f'{self.request.id}'
with AcquireLock(lock_id) as lock:
if lock.acquire() is True:
return cascading_delete(*args, **kwargs) | 5f944c619f3679fb0a63d4035191590bcdb943ac | 53,530 |
def create_vat(*, session: Session = Depends(get_session), schema: VatPostingGroupCreate):
"""«VAT Posting Group» («НДС Учетная Группа»)"""
return service.servicetype_s.create(db=session, schema=schema) | bfe38b86c18809ba58f0a17565e00d048f143bab | 53,531 |
def check_dns_cname(domain, prefix, code):
"""
Validates a domain by checking the existance of the CNAME record on the domain as:
{prefix}-{code}.{domain} pointing to a domain (usually yours) which the host is {prefix}
(i.e.: {prefix}.yourdomain.com).
Returns true if verification suceeded.
"""
... | 261173dabd0e6ff7c0f42e0a75ff577f3cdc3cf1 | 53,532 |
def local_test_pressure_unity(α_spt, p_lt=None, p_li=None, p_e=None, **kwargs):
"""Local test pressure unity check.
Reference:
DNVGL-ST-F101 (2017-12)
sec:5.4.2.1 eq:5.6 p:93
(local_test_press_unity)
"""
if p_e is None:
p_e = external_pressure(h_l, ρ_seawater, g)
if p_lt ... | 1336d9d3a6d38691f80c3d968725a6d412cce266 | 53,533 |
import ctypes
def getProgramState(hc, nbuf, wait=SYNCHRONOUS):
"""Returns program state"""
state = ctypes.c_int()
acs.acsc_GetProgramState(hc, nbuf, byref(state), wait)
return state.value | 2563015cecea556a30f659b5f10b6002fb86af4d | 53,534 |
import os
def read_specs(path):
"""
Get all IT declarations from the project looping through each of the spec files
"""
specs = []
for root, _, files in os.walk(path + '/spec/'):
for file in files:
if file.endswith(".rb"):
file_path = os.path.join(root, fil... | 96ef1eada4a7dd778db8c7fe88242b7da6797e8c | 53,535 |
def ip( source=None, source_hex=None, destination=None, destination_hex=None,
version=None, ihl=None,
tos=None, p=None, p_str=None, d=None, d_str=None, t=None, t_str=None, r=None, r_str=None,
tl=None, id=None,
flg=None, flg_str=None, frg=None, ttl=None,
pro=None, sum=None, su... | 5126d981ec9822c2c28dfa3918e59d2516b5e50d | 53,536 |
from typing import DefaultDict
def default_dict(_cls):
"""
Decorator that it create DefaultDict by attribute of class.
Support attribute alias:
@attrdict.default_dict
class CustomDict:
a=1
b=2
custom_dict = CustomDict()
custom_dict.a # return: 1
... | f9e3eadde4e7230acf64d544c9a4df146bb58e2e | 53,537 |
def trimmed_split(s, seps=(";", ",")):
"""Given a string s, split is by one of one of the seps."""
for sep in seps:
if sep not in s:
continue
data = [item.strip() for item in s.strip().split(sep)]
return data
return [s] | 192c75f7e346860010031cf9e621d7bb5664dde4 | 53,538 |
import torch
def mp2rage_old(pd, r1, r2s=None, transmit=None, receive=None, gfactor=None,
tr=6.25, ti1=0.8, ti2=2.2, tx=None, te=None, fa=(4, 5), n=160, eff=0.96,
sigma=None, device=None, return_combined=True):
"""Simulate data generated by a (simplified) MP2RAGE sequence.
The d... | 872be49a57514f4f4a85bcc94bfc3228b1ae8cf4 | 53,539 |
from typing import Dict
from typing import Tuple
def load_homonyms(synsets_file_name: str, senses_file_name: str, fasttext_model: FastText,
udpipe_pipeline: Language) -> Dict[str, Tuple[np.ndarray, str]]:
""" Create a special dictionary of RuWordNet homonyms and their distributional semantic rep... | c6d01b66c25f9f4f2218984817f5a30511517ed9 | 53,540 |
def descendant_selected(node):
"""Returns true if this node or a descendant of it is selected.
Use as e.g.: {% if descendant_selected node %}
"""
if node.selected:
return True
for child in node.children:
if descendant_selected(child):
return True
return Fals... | 974b95b8d658ec173ccbbf9488f309529c1f0d86 | 53,541 |
import torch
def create_mock_attention_data(number_of_nodes, edge_per_node, in_channels, periods):
"""
Creating a mock stacked feature matrix and edge index.
"""
graph = nx.watts_strogatz_graph(number_of_nodes, edge_per_node, 0.5)
edge_index = torch.LongTensor(np.array([edge for edge in graph.edge... | b08185a92bb906da3bc89941f737b9aa5a162c46 | 53,542 |
def pretty_labels_map(atom_labels):
"""
transforms all of these crazy tuples into the notation used in williams and
beer I_min PID
"""
rename_map = {}
for label in atom_labels:
new_label = str(label)
# eliminate commas and spaces
new_label = new_label.replace(',', '')
... | 2e7841062a7a5688ecd79b9fd772022e99648ef2 | 53,543 |
def 取最小数(数值列表):
"""
传入要对比的列表,如(1,2,3),返回里面最小的数字
:param 数值列表: (1,2,3)
:return: 1
"""
return min(数值列表) | 27f031613c6e95e4daf3022a2c14b29ada905e30 | 53,544 |
import warnings
def tile_iterator_1d(x,axis,n_tiles,block_size,n_block_overlap,guarantee='size'):
"""Tile iterator for one dimension of array x.
Parameters
----------
x : numpy.ndarray
Input array
axis : int
Axis which sould be tiled, all other axis not tiled
n_tiles : int
... | 09fa63a7b7d1d84e0db66b7cdfe2d2df5b47d88d | 53,545 |
from typing import List
import logging
def _plot_categorical_feature_numerical_label(
label_stats_data: pd.DataFrame, feature_stats_data: pd.DataFrame,
feature_name: str,
plot_style_params: _FeaturePlotStyles) -> List[axes.Axes]:
"""Plots the statistics of a categorical feature when label is numerical.
... | aae77e577016b2e4fd7d0f240fe24abda03ab12f | 53,546 |
def get_all_property_groups(connection):
"""
Get the meta-information for all the property groups in the portal.
:rtype: :class:`list` of :class:`PropertyGroup` instances
:raises hubspot.connection.exc.HubspotException:
End-point documentation:
http://developers.hubspot.com/docs/methods/contac... | 5d3a2745afe703ab2d6ece7cf4fdb5900b023d05 | 53,547 |
def get_infected(data: EoN.Simulation_Investigation, end_time: int):
"""Returns list of infected nodes."""
return get_type_of_nodes(data, end_time, 'I') | fffe3f52e47ebf534b8c48f2c8433baf0b68eb4d | 53,548 |
def create_product_storage_record(record_info: dict):
"""
创建一条库存变更记录
:param record_info:{
"shop_id": 1,
"product_id": 1,
"operator_type": 1,
"user_id": 1,
"type": 1,
"change_storage": 1,
"current_storage": 2,
"order_num": 1xxxxx,
}
:ret... | 8de739ea4b9d9fa4c98d76ba602c013e0049ffca | 53,549 |
def _includes_custom_type(content_type: str) -> bool:
"""
Evaluate whether a content type is a custom type or has a custom type as a sub-type.
:return: Boolean result
"""
if content_type.startswith("Optional"):
sub_type = _get_sub_types_of_compositional_types(content_type)[0]
result ... | 3d795d7667c8ec07aec8fac8d831c76d7398ecae | 53,550 |
def yet_another_hash_table():
"""Make a hash table with multiple values and keys."""
h = HashTable()
h.set('koala', 'kool')
h.set('dog', 'chihuahua')
h.set('cat', 'fat')
h.set('moose', 'bullwinkle')
return h | 4e009e96e75016c9e9ea4964a56d62a4169814ec | 53,551 |
from typing import List
from typing import Pattern
def matplotgraph_predictions(user: discord.Member, predictions: List[Pattern], min_max_pattern: Pattern, average_prices: List[float], testing=False) -> BytesIO:
"""Graph the predictions"""
x_axis = day_segment_names[2:]
abs_min_points = [price.min for pr... | 7a21c7ab6fe6af9823d9ad3a0194f84ad0ef8cc0 | 53,552 |
import sqlite3
def open_corpus_volatile(treebank_id, tigerxml_corpus_path, veeroot=True):
"""Indexes a TIGER-XML corpus using a volatile in-memory index."""
db = sqlite3.connect(":memory:")
_index_treebank(tigerxml_corpus_path, db, veeroot)
return Corpus(treebank_id, db, EmptyDbProvider()) | b9b3a37fd52fa2830806d9a99c61c4a12acc6f48 | 53,553 |
def char_to_bool(letter):
"""Transform character (J/N) to Bool."""
if letter.upper() == 'J':
return True
elif letter.upper() == 'N':
return False
else:
raise ValueError('Ongeldige letter, alleen J of N toegestaan.') | ab12ffae09afdcf1e0ad9319238bef94b8f147ef | 53,554 |
def parse_exception(definition, name, message):
"""Parse an exception.
:param definition: Definition.
:param name: Name.
:param message: Message.
:returns:
the parsed exception or :class:`UnknownException` if the exception is
not known.
"""
if definition == 'entangle':
... | 9d9bddc42fb9de10c998907d930cf1b5c49da2d5 | 53,555 |
import os
def write(configsetname, node, cnfxml):
"""
Write configuration file with content supplied as an XML string.
Return None for success, or a string containing error information.
"""
config = configPath(configsetname, node)
if config and os.path.exists(config):
return "Output fi... | ae5b7fcea3c50ce37f9b3ba1397ef29724ee99d6 | 53,556 |
def _prf_divide(numerator, denominator):
"""Performs division and handles divide-by-zero.
On zero-division, sets the corresponding result elements to zero.
"""
result = numerator / denominator
mask = denominator == 0.0
return ma.array(result, mask=mask) | 0e562c659b2fda9835bd16b1e762bc0a86113c97 | 53,557 |
from typing import Optional
def authenticate_user(username: str, password: str) -> Optional[Admin]:
"""Authentucate user process.
Check if the username is in the admin database and the password is correct.
If both conditions are correct, it returns an Admin instance; otherwise it returns None"""
user... | f8e3e081239bd9e968200c4daa2cee69af2e5ffc | 53,558 |
def mock_clipboard(monkeypatch, request):
"""Fixture mocking clipboard IO.
This mocks pandas.io.clipboard.clipboard_get and
pandas.io.clipboard.clipboard_set.
This uses a local dict for storing data. The dictionary
key used is the test ID, available with ``request.node.name``.
This returns th... | 7acf72b45050d35cd57ddf9310304950610744c5 | 53,559 |
import os
def get_xml_tree(xml_path):
"""Parses xml file and returns am xml tree.
Args:
xml_path (str): full path to xml file to parse
Returns:
ElementTree.Tree: ElementTree representing xml file
"""
if not os.path.exists(xml_path):
raise XMLHelperError("Could not find xm... | ae71060419c1560f2e929d126cc362d808b9e4b2 | 53,560 |
def fileNumber(filePath):
"""
Get the number of the file. foo.0080 would return 0080
"""
num = filePath.split('.')[-1]
return int(num) | 731918660f0c145c15ba99c2f5eb8be9745e8576 | 53,561 |
def dice(x, y):
"""Implementation of dice scores ofr 0/1 numy array"""
return 2 * np.sum(x * y) / (np.sum(x) + np.sum(y)) | 0a83c83377040123782576736a6d584f09f31186 | 53,562 |
def getAddressNode(network, address):
"""
Get the Layer3Address node of a host that has the igven address.
:param network: Hostnames the host could have -> Nmap scan
:type network: Layer3Network
:param address: Address to find
:type address: str
:returns: Layer3Address node or None
... | 3fc56c56c34df7d49f7d8fb872af19b29242534f | 53,563 |
def get_top_adj(full_results, num):
"""
Takes dictionary of results from run_adj_analysis and number of top results to return.
Returns the top num adjectives associated with male pronouns and female pronouns.
:param full_results: dictionary from result of run_adj_analysis
:param num: number of ... | 0eddb189f79bc9b18f2994f2a99aef1b07181691 | 53,564 |
import re
def create():
""" Create a new RSS feed over XHR
:return: Feed creation status response
:rtype: Response
"""
status = api.STATUS_FAIL
feed = "rss_{0}".format(re.sub('[^0-9a-zA-Z]+', '_', request.values['feed'].lower()))
if config.has_section(feed):
msg = "Duplicate feed... | 6e69211e8924d484d1b5cc4e88d09d1949f76e66 | 53,565 |
def get_host_token(profile=None):
""" Get the host and token for a profile from ~/.databrickscfg. """
cfg = provider.get_config() if profile is None else provider.get_config_for_profile(profile)
return (cfg.host,cfg.token) | 89e7fb425fb7965b560b70d51af46a68bf3cc233 | 53,566 |
import time
def loadAll(param=basic_param):
""" Charge toutes les colonnes selon les paramètres
Paramètres
----------
param : set
dictionnaire des paramètres
Retours
----------
df_global : pandas.dataframe
si Return == True renvoie le dataframe complet
"""
t1 = ti... | 4b9452c5b5cd4dfe322dd1b167c1181df01e09a5 | 53,567 |
def rfc_save_test(request, rfc_id, *args, **kwargs):
"""
"""
# Check user permissions
# Get the form data
form = RfcModuleForm(request.POST)
if not form.is_valid():
return HttpResponseBadRequest(form.errors)
# Get the rfc in question
update_rfc = request_for_change.objects.get(r... | 7372a992acde22d4e7366c21dc707b2fde98e18a | 53,568 |
def testPair(pair,coglist):
"""Determine the next cognate set to choose for a pair"""
curcog = cognateSet()
for cog in coglist:
curcog += cog
mycogs = [cognateSet()]
mycogs[0].noncognates += max((len(pair[0]),len(pair[1])))*2
newcogs = getListOfCognates(pair[0],pair[1],cognateSet())
... | c7a3a974823b82946dbaf2f45a63150090ba922b | 53,569 |
def _search_phrase_op(il, target_op):
""" Helper for finding parts of a phrase[+displacement] il """
op = il.operation
# Handle starting points
if op == LowLevelILOperation.LLIL_SET_REG:
return _search_phrase_op(il.src, target_op)
if op == LowLevelILOperation.LLIL_STORE:
return _search_phrase_op(il.... | f71a9ce5b949aea32077ec4b1b95dfcb19e7bcf5 | 53,570 |
def cube(path='./', pattern='', verbose=True):
""" Convenience wrapper around find.files to get *.cube files """
return files('cube', path=path, pattern=pattern, verbose=verbose) | 70ed21db1cb811ff6e8f118c12f7ff98989782ca | 53,571 |
def is_schema_compatible_in_topic(target_schema, topic):
"""Check whether given schema is a valid Avro schema and compatible
with existing schemas in the specified topic. Note that target_schema
is the avro json object.
"""
enabled_schemas = get_schemas_by_topic_name(topic.name)
for enabled_sche... | db30235c247ca41192ab80d3fd5e40a632286ead | 53,572 |
def JobStatus(jobid):
"""return status(es) of job
Parameter
---------
jobid
id of job
Returns
-------
list
state of each job in array
"""
status = []
for line in JobInfo(jobid, ['jobid', 'state'], noheader = True).split('\n'):
if (line.split() and '+' ... | fbeef89e588fdf7dda49d08cfc63992191a2ca7f | 53,573 |
def make_msg(comment, request):
""" Return a message from a comment & request. """
return build_msg('',
user_name = comment.user_name,
user_email = comment.user_email,
user_url = comment.user_email,
comment = comment.comment,
user_ip = request.META.get... | 4fed979fa478184e75c96fa3c78632797c210458 | 53,574 |
def DataFrameTableColumnComponent(
widget,
is_interactive,
column,
SpanOnBeginChange,
SpanOnEndChange,
TokenSpanOnBeginChange,
TokenSpanOnEndChange,
):
"""Constructs the widget component representing a single column of data within the table."""
column_items = []
# Begin with th... | 317b80a55a44eb42be0bf2456f50df5ca5fa6a08 | 53,575 |
import base64
import ast
from datetime import datetime
def get_user(data_encoded):
"""
Endpoint returning logged-in user
Args:
data_encoded: BASE64 encoded JSON
Returns:
Flask response, consisting of serialized user, response code, response message, affected class, and http code
"... | 14748526ec4bded7bb54777b3858208ed4c3a688 | 53,576 |
def arg_wrap(fft_func, **extra_args):
"""Decorator to add kwargs based on fft suite.
Args:
fft_func: the fft function to arg wrap
extra_args: extra args to add to the PyFFTW call
Returns:
the wrapped function
"""
using_fftw = FFTMODULE.__name__.split('.')[0] == 'pyfftw'
def ... | 0dd9ed0da78aebc1ba1b82dcd3d2f4fd9bc736f2 | 53,577 |
import healpy
def get_healpix_dec_mask(dec_lim, nside):
"""
Compute a Healpix binnary mask given a limit declinaison
Parameters
----------
- dec_lim (deg): the limit declinaison for the mask
- nside : Healpix Nside argument
Outputs
--------
- mask (int array): the binnary mask cu... | 6bf968dc9d3ea106bb5bd74d70235dfd0c41be15 | 53,578 |
def singleton(fn):
"""
Lazily instantiate a function
"""
_instance = None
def wrapped():
nonlocal _instance
if _instance is None:
_instance = fn()
return _instance
return wrapped | c15a0b8a41a102cf4360af0bddbbdb289a794f87 | 53,579 |
def manhattan_distance(x, y):
""" Returns the Manhattan (City Block) distance between two lists
"""
return sum(abs(a - b) for a, b in zip(x, y)) | 4887024603a8fe3398ec80a17d1d70fbe15fdfab | 53,580 |
def score_from_local(directory):
"""Calculate score from a local results directory"""
results = gym.monitoring.monitor.load_results(directory)
# No scores yet saved
if results is None:
return None
episode_lengths = results['episode_lengths']
episode_rewards = results['episode_rewards']
... | 378de4e5c8b4c23c62f887630362c0552426503e | 53,581 |
from _primefac._arith import ispower, gcd, ilog
from _primefac._prime import isprime, primegen
from six.moves import xrange
from random import randrange
import six
def ecm(n, B1=10, B2=20):
"""
TODO: Determine the best defaults for B1 and B2 and the best way to
increment them and iters "Modern" ECM ... | 3bc23c494ffd1b8faeea83ac106d20da3df4dc41 | 53,582 |
def generate_dispatcher(method_handler, parent_class=None):
"""
Create a dispatcher class and return an instance of it from a dispatcher
definition.
The definition is a class with the following attributes:
_ EXPORTED_METHOD: dictionary where keys are method names and values
class attribute nam... | 9ea218791ec3d2e54b782cad9fce36b2d343962a | 53,583 |
def show_slave_hosts(server):
"""Function: show_slave_hosts
Description: Return the output of the 'show slave hosts' command.
Arguments:
(input) server -> Server instance.
(output) Results of command in dictionary format.
"""
return server.col_sql("show slave hosts") | 7adadfad7c84cb5b93b401ff3661a646fd315b48 | 53,584 |
from typing import Dict
def get_used_materials(materials_map: Dict[int, str], path_info: pd.DataFrame) -> str:
"""Collect text of used materials specifications.
Args:
materials_map: map material number -> spec.
path_info: dataframe containing column with used material numbers.
Returns:
... | 62af20460a72d66d215d03a8cc0e9bb0553f7bc4 | 53,585 |
def starting_coordinates():
"""
Starting coordinates on a pixel matrix.
"""
return (10, 10) | 68f8b493e36cba56808cfbcea6a4ee9368e0c720 | 53,586 |
def get_args():
"""Eat command line arguments, return argparse namespace for settings"""
parser = ArgumentParser()
parser.add_argument("filename", nargs="?",
help="trace file dump, stdin if not given")
parser.add_argument("-s", "--start", type=float, default=0,
help="start timest... | 13d602b5f56a29e4bd87e12ee26ecea5af4b29fb | 53,587 |
def delete_machine(index):
"""Add a new machine"""
Machine.delete(index)
return '', 200 | 5cf62890386c6bd2fd8300350c80570d96b86b6f | 53,588 |
def strip_html_tags(i_string):
"""
Quick solution to remove html tags being returned in episode description.
Will probably replace eventually.
"""
strippable = ('<p>', '</p>')
spaces = (' ',)
breaks = ('<br>',)
for s in strippable:
i_string = i_string.replace(s, '')
for... | 9454c7ee5e9006756426ca1fdecb97df8beb2cc4 | 53,589 |
def dos_element_spd_spin_polarized(
folder,
element_spd_dict,
output='dos_element_spd_sp.png',
fill=True,
alpha=0.3,
linewidth=1.5,
sigma=0.05,
energyaxis='x',
soc_axis='z',
color_list=None,
legend=True,
total=True,
figsize=(4, 3),
erange=[-6, 6],
fontsize=12,... | 8b1db8c829545a6f20a7c2dacb32e66220e851d6 | 53,590 |
import numbers
def solve_weighted_kernel_ridge_gradient_descent(
Ks, Y, deltas, alpha=1., fit_intercept=False, step_sizes=None,
lipschitz_Ks=None, initial_dual_weights=None, max_iter=100, tol=1e-3,
double_K=False, random_state=None, debug=False):
"""Solve weighted kernel ridge regression u... | 2940efa2910f4c4de1d78e14e7bf6c72fe54fff8 | 53,591 |
def generate_index(csv_filepath):
"""
Generate an index 0...k for the k labels.
Parameters
----------
csv_filepath : str
Path to 'test.csv' or 'train.csv'
Returns
-------
tuple of dict and a list
dict : Maps a symbol_id as in test.csv and
train.csv to an integer in ... | 767d40f09405de3bddc85ba74c87c263a5adc612 | 53,592 |
import urllib
import json
def getPlayer(playerId,fullname):
"""
Retrieves player stats for the last game.
Career results can be added in the future
"""
url = "http://data.nba.net/prod/v1/2018/players/{}_gamelog.json".format(playerId)
with urllib.request.urlopen(url) as url2:
da... | ba91e44c4edd1f74a987fe98bc9d6c2667fe4aa1 | 53,593 |
def last_name_similarity_scorer(a: str, b: str):
"""Compares two first last strings, returns 1 if they match, 0 otherwise.
Uses Jaro-Winkler Distance Algorithm (JWDA) (en.wikipedia.org/wiki/Jaro–Winkler_distance).
JWDA "measurement scale is 0.0 to 1.0, where 0.0 is the least likely and 1.0 is a positiv... | 3851d22e2533133c0f76b863e9d184daee3a561a | 53,594 |
import random
def scoringInnings(team_1_array,
team_2_array,
innings,
bat_bowl_choice,
batting_score,
innings_data,
start_message,
max_overs,
max_wickets,
... | c285577203e86bb80db98ba21821eeeca8b67ea7 | 53,595 |
import uuid
import os
def get_tempfile():
"""Return tempfile."""
dirname = get_tempdir()
filename = uuid.uuid4().hex
return os.path.join(dirname, filename) | de6bbb058cc273f2228088ebded3c5129fb7c3d7 | 53,596 |
def fib_iter(n: int):
"""迭代解法,自低向上"""
dp = {}
dp[1] = dp[2] = 1
i = 3
while i <= n:
dp[i] = dp[i - 1] + dp[i - 2]
i += 1
return dp[n], dp | ec701c9f4b7c8a9c490e24bb90a309f1e0cdd7bf | 53,597 |
def convert_dashboard_tile_to_presentation_tile(element: dict) -> LookerPresentationTile:
"""Take the API response and convert into a LookerPresentationTile object"""
return LookerPresentationTile(
title=element['title'],
subtitle_text=element['subtitle_text'],
body=element['slide_params... | be08982305f5fdc7a2efee27344edc49238992ef | 53,598 |
def wrap_angle(array, wrap_count):
""" Wraps angle vector
Helper-function that wraps an angle vector containing angles in radian by
the number of elements specified by wrap count. The last wrap_count elements in
array are stacked to the beginning of the array and lowered by 2*pi and the
first... | a37d1a8e1e7ed42c3cc308df09c360e583d19fa6 | 53,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.