content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from io import StringIO def create_payload(data, kwargs): """ Creates a new ``PayloadBase`` instance with the given parameters. Parameters ---------- data : (`list` of ``PayloadBase`` instances), ``BodyPartReader``, `bytes`, `bytearray`, `memoryview`, `str`, \ `BytesIO`, `StringIO...
c774e09907ddffc230ac62816978c87256c46ee1
3,622,326
def create_app(): """Creates the Flask app object.""" app = Flask(__name__) app.config.from_object(AppConfig) api = Api(app) configure_resources(api) configure_extensions(app) return app
18fd00a52a777aa72a4f87d0338a794f5f9a6afd
3,622,327
def ymdhms_format_from_tai(tai, sep="T", digits=None, suffix="", buffer=None): """Date and time in ISO format 'yyyy-mm-ddThh:mm:ss....' given seconds TAI. Works for both scalars and arrays. Input: tai number of elapsed seconds from TAI January 1, 2000. sep...
5dda1c30790290dd9388e9e8d466450f2739595a
3,622,328
def _get_project_ids(): """Return the GCE project IDs.""" return list(local_config.Config(local_config.GCE_CLUSTERS_PATH).get().keys())
b3a94b5130a9f3915dceb820750c6711d6778f0e
3,622,329
def drop_multiple_fha_numbers(df): """drops multiple fha_numbers by dropping issued data when a reissue is available in firm commitment activity""" #create df of rows unique fha_numbers unique_fha_list = df.fha_number.value_counts()[df.fha_number.value_counts() == 1] def in_unique_list(x): ...
f884e6ef22221308783a3cbb235d5c17801ad80b
3,622,330
from datetime import datetime def create_accelerate_order() -> jsonify: """ 生成刷票订单 :return: """ try: data = loads(request.get_data().decode('utf-8')) except ValueError: return jsonify({'code': '2000', 'message': '服务器内部错误'}) # 防止重复下单 order_list = TicketOrder().query.fi...
27f94a5449267b6243df1732f41ddd4d150edccd
3,622,331
def rect2ang(rect, zenith=False, axis=0): """The inverse of ang2rect.""" x,y,z = moveaxis(rect, axis, 0) r = (x**2+y**2)**0.5 phi = np.arctan2(y,x) if zenith: theta = np.arctan2(r,z) else: theta = np.arctan2(z,r) return moveaxis(np.array([phi,theta]), 0, axis)
71c80a7295203d53ca5afe65959b79632aa633fe
3,622,333
def mutate_single_base(base): """Takes single nucleic acid and changes it to a different nucleic acid.""" bases = "GATC" idx = bases.index(base) return choice(bases[:idx] + bases[idx + 1:])
04cfd6b33e02776485ffc64d4be1f016a23c859b
3,622,334
from typing import Iterable def filter_star_import( line: bytes, marked_star_import_undefined_name: Iterable[bytes], ) -> bytes: """Return line with the star import expanded.""" undefined_name = sorted(set(marked_star_import_undefined_name)) return Regex.STAR.sub(b", ".join(undefined_name), line)
99eff31b5ba081a5683e7a3e7df216c25e62bb7a
3,622,337
def zeros(shape, dtype, allocator=drv.mem_alloc, order="C"): """Returns an array of the given shape and dtype filled with 0's.""" result = GPUArray(shape, dtype, allocator, order=order) zero = np.zeros((), dtype) result.fill(zero) return result
ef7e7668378cdd5b2321caaeb0038e6e5784414d
3,622,338
def weighted_geometric_mean(values, weights): """ Returns the weighted geometric mean of values. Args: values (iterable): weights (iterable): Returns: float: """ assert len(values) == len(weights) return np.exp(sum([weights[i] * np.log(values[i]) for i in range(len...
f0d3eff6e5948685f16cc330e19b7650084c7dc8
3,622,339
from typing import Dict def make_information_functions() -> Dict[str, ecole.typing.InformationFunction]: """Create the information function used in benchmarking the observation. This is a combination of sloving features such as number of nodes, and the timing of observation functions. """ informa...
6de6cb6e40966a9e2f59f869d65a3e6fd47034c9
3,622,340
import struct def read64(f): """Read 8 bytes from a file and return as an 64-bit unsigned int (little endian). """ return struct.unpack("<Q", f.read(8))[0]
4a055188bd9db074ca3807771d779eccb25e5484
3,622,341
import math def get_cosine_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, num_cycles=.5, last_epoch=-1): """ Create a schedule with a learning rate that decreases following the values of the cosine function between 0 and `pi * cycles` after a warmup period during which it increases ...
31eaef9f633ded9b4853bda76a3600e27f83ca28
3,622,342
def neighbor_weights(dist): """Return the weights of neighbors in time seires estimates. Params ------ dist (np.ndarray): $M \times (N+1)$ array of Euclidean distances between a point to its nearest neighbors in the shadow data cloud (sorted by increasing o...
6a07b3853463d8ed7156b3c3e0a14661cc55f51b
3,622,343
from typing import Any from typing import Tuple from typing import Optional def get_train_and_validation_loaders( args: Any, image_size: Tuple[int, ...], task: Optional[Tasks] = None ): """ :param args: Object containing relevant configuration for the task :param image_size: A Tuple of integers repres...
e160dd10a1be710dbc08fddddbb8a3dd2906741c
3,622,344
def is_alef(archar): """Checks for Arabic Alef forms. ALEFAT = (ALEF, ALEF_MADDA, ALEF_HAMZA_ABOVE, ALEF_HAMZA_BELOW, ALEF_WASLA, ALEF_MAKSURA ) @param archar: arabic unicode char @type archar: unicode @return: @rtype:Boolean """ return archar in ALEFAT
246084efce49d17a2b2af34b9db39aa1440d6a03
3,622,345
import re def p_regex(regex, flags=0): """ p_regex returns a parser that matches a regex at the current offset """ r = re.compile(regex, flags=flags) @SugarParser def parse(str, offset=0): match = r.match(str, offset) if match is None: return None, -1 match = match...
fa5c2e4f18320a7ebeccebc71c29112033377a49
3,622,346
from typing import Optional from typing import Tuple def _decode_and_center_crop( image_bytes: tf.Tensor, jpeg_shape: Optional[tf.Tensor] = None, ) -> Tuple[tf.Tensor, tf.Tensor]: """Crops to center of image with padding then scales.""" if jpeg_shape is None: if image_bytes.dtype == tf.dtypes.string: ...
1baa7fa938d7adf2e3e1782414b5b1f654971294
3,622,347
def macd(X: pd.DataFrame, lower: int = 7, upper: int = 14, price_window: int = 63, window: int = 252): """ Computes the Moving Average Convergence Divergence. References: - https://arxiv.org/pdf/1911.10107.pdf Arguments: X : pd.DataFrame A ...
97279bc8ea56ee703bf910601dee898d1a439570
3,622,348
from sage.misc.latex import _run_latex_, _latex_file_ from sage.misc.temporary_file import tmp_filename def has_latex(): """ Test if Latex is available. EXAMPLES:: sage: from sage.doctest.external import has_latex sage: has_latex() # random True """ try: f = tmp_f...
329c7a053219901c6c2242ce99363b5b7e103fd9
3,622,350
def crop_to_bbox(objs, bbox): """ Filters objs to only those intersecting the bbox, and crops the extent of the objects to the bbox. """ if isinstance(objs, dict): return dict((k, crop_to_bbox(v, bbox)) for k,v in objs.items()) initial_type = type(objs) objs = to_list(ob...
c8b0e8742e5e2104c92708c4a067b3df6fe0a2c6
3,622,352
import glob def calibrate_camera(nx=9, ny=6, images_folder='camera_cal/calibration*.jpg'): """ Use the corners to calibrate camera """ # prepare object points, like (0,0,0), (1,0,0)...(6,5,0) # further study these two lines objp = np.zeros((nx*ny,3), np.float32) objp[:, :2] = np.mgrid[:nx, :ny].T...
94ccbe7372497baf30b628b7f4ff3ede84335af1
3,622,353
def run_command_async(cmd): """ Run a command using the asynchronous `tornado.process.Subprocess`. Parameters ---------- iterable An iterable of command-line arguments to run in the subprocess. Returns ------- A tuple containing the (return code, stdout) """ process = S...
28e184735cbdcf99bf35b6b2e648f09b59a35d9c
3,622,354
async def webhook(request): """Webhook to retrieve action calls.""" action_call = await request.json() try: response = await executor.run(action_call) except ActionExecutionRejection as e: logger.error(str(e)) response = {"error": str(e), "action_name": e.action_name} res...
96ee5097e6c81ed9918fb8509dfc8c2cd619717d
3,622,355
import re def contain_static(val): """ Check if URL is a static resource file - If URL pattern ends with """ if re.match(r'^.*\.(jpg|jpeg|gif|png|css|js|ico|xml|rss|txt).*$', val, re.M|re.I): # Static file, return True return True else: # Not a static f...
9b69c0e8c69f9a97abbea82855d0c387de2a381a
3,622,356
def text_messages_joint_log_prob(count_data, lambda_1, lambda_2, tau): """Joint log probability function.""" alpha = (1. / tf.reduce_mean(input_tensor=count_data)) rv_lambda = tfd.Exponential(rate=alpha) rv_tau = tfd.Uniform() lambda_ = tf.gather( [lambda_1, lambda_2], indices=tf.cast( ...
5c644fede815607179cc3d99451b04015c162f4d
3,622,357
from ooiservices.app.uframe.asset_tools import verify_cache def build_assets_cache(): """ Force update of asset information. """ try: asset_list = verify_cache(refresh=True) print '\n Completed compiling asset information.' print '\n Number of assets: ', len(asset_list) res...
562077350bce0dcf403a5cec69d22fd97a716142
3,622,358
def is_dataset(obj): """ True if the object is a h5py.Dataset-like object. :param obj: An object """ t = get_h5_class(obj) return t == H5Type.DATASET
0360e7fa312f4f49fd2b47fdcda7f290e516e998
3,622,359
def get_court_id_from_url(url): """Extract the court ID from the URL.""" parts = tldextract.extract(url) return parts.subdomain.split(".")[1]
18d6b0f5a817910c09b2cf2063770665a0e587f7
3,622,360
def insertgroup(request): """Insert group in database.""" # Get data group_name = request.POST.get('group', None) # Add to inventory inventory = spotmax.SPOTGroup() inventory.add_group(group_name) message = 'Group added!' return render( request, 'addgroup.htm', context={'message': m...
694909fbe91a179245a2b3c436d9fd53f992b431
3,622,361
def get_rockets(method=""): """Gets information related to SpaceX rockets Gets information related to rockets from the API Parameters ---------- method : str (optional) the method used for the request Returns ------- list a list of the rocke...
db0bc299b1a7683908ec1e691a0aff318a5aa409
3,622,362
def load_config(): """Load configuration file""" return load_properties_file(CONFIG_FILE_PATH)
7970c7b00f2912ffbf46c8666110b1ddd46ae434
3,622,364
def lerp10(h, h1, h2, o1, o2): """Returns 10**o, where o is the linear interpolation of value h between (h1, o1) and (h2, o2).""" return 10**np.interp(h, [h1, h2], [o1, o2])
76faddc8bbac17b8054bf3e2c1920351d81688dc
3,622,365
def get_all_urls(titles, title_data): """converts every title into """ urls = [] for title in titles: title_data[title].append(WIKI_URL+title) return urls
471dabeb4268afca4f96a3ae07b547ac221f1426
3,622,366
def find_system_symbol(img, instruction_addr, system_info=None): """Finds a system symbol.""" return DSymSymbol.objects.lookup_symbol( instruction_addr=instruction_addr, image_addr=img['image_addr'], image_vmaddr=img['image_vmaddr'], uuid=img['uuid'], cpu_name=get_cpu_nam...
b639b64747d396d539847d7e68e12feb849d3bc6
3,622,367
def make_univariate(F, T): """ Given a homogeneous bivariate polynomial `F(xi,xj)`, sitting inside a ring `K[x0,x1,x2]`, dehomogenise it into ring T (univariate), for later factoring. """ assert(F.is_homogeneous() and len(F.variables())<3) R = F.base_ring() S = F.parent() x0,x1,x2 = ...
0f2c230e9e19bcb61b687bcd7aff5ec6d5069347
3,622,368
def doConvertBlackAndWhiteFilter(image: Image.Image, mode: str): """Low level function... Convert an image to black and white based on a filter: filter-darker and lighter respectively make pixels darker than the average black and pixels that are lighter than the average black. Args: image (Image.Image): A PIL ...
a66654b00edb4d40b50a1137e698fe4313c5a443
3,622,369
def copy( store: BaseAccessStore, from_principal: str, from_principal_type: str, to_principal: str, to_principal_type: str, ) -> bool: """ copies a relationship from the from_principal to the to_principal for the given types """ # print(f'copying from {from_principal_type} {from_...
5f2495b6c5006e10c2e5a727d5e3d2381bb5aa13
3,622,371
def expand_list(inlist, keyname, expandables, defaults={}, fmt=[]): """[summary] Output is a a dictionary of an element that has an array of elements each has expandables set to the inlist values and for any optional value, revert to the default list. Example: inlist = [{"name": "abc", "writable": True}...
8a8a8dd73a3f995b64389ddbcaebf7d861d2e690
3,622,372
def get_answers(question_id, **params): """获得答案列表""" conditions = list() sort_conditions = list() query = Answer.query if 'ids' in params: conditions.append(Answer.question_id.in_(params['ids'])) if params.get('create_time_sort') is not None: sort_condition = ( Answ...
e1117a26dde9d6dccc661a1dc7c0279726f63107
3,622,373
import base64 def download_gift(gift): """Generates a link allowing the gift file to be downloaded in: test string data out: href string to gift formatted test """ b64 = base64.b64encode(gift.encode()).decode( ) # some strings <-> bytes conversions necessary here href = f'<a href="data:f...
f007e35133d2ea0d61471290e7ea3ad4b591db3e
3,622,374
def _showFloatDiffs(asserter, expect, actual, **kwargs): """Indicate the differences between two floats. :Parameters: expect, actual The expected and actual float. kwargs ignored. :Return: A string showing why the float values differ. """ ulpDiff = UlpCompare.u...
0a5af1867d35bfaf56ac43b82967800e59d50280
3,622,375
def is_recovery_active(): """Report whether recovery mode is active.""" return RECOVERY_ACTIVE
eb9d061aa2901f591d269543158ce63d8ab63458
3,622,376
def create_icon_score_stub(**kwargs) -> IconScoreInnerStub: """Create IconScoreInnerStub. Note that return value is actually `mock.Mock`. """ task: IconScoreInnerTask = AsyncMock(IconScoreInnerTask) task.validate_transaction.return_value = "result" task.query.return_value = { "result": ...
6d258a954d9950df8e76c34df59758e0be344243
3,622,377
import json def wait_message(): """ Wait message from websocket, return the message in the format of a dict. """ try: msg = connection.recv() except websocket._exceptions.WebSocketConnectionClosedException as e: print(e) global connection connection = connect() ...
d7e05ed51c2a74d6e37a50341973d02ed3facd42
3,622,378
def rectifier(x): """ element-wise ReLU """ return tensor.maximum(0., x)
bfc89136f7a6d0e7c8d0bbd0da1c73795e36bd7f
3,622,380
import json import re def unsubChange(doc, API, session): """ Calculate a mailing list unsub request """ diff = "" mls = {} with open("private/json/ml-modsubs.json") as f: mls = json.load(f) f.close() li = doc['listname'] l,d = li.split('@', 2) d = d.replace(".apache.org", ...
72b1e1d0886222b43ff0df4deccfbce5e4f55332
3,622,381
import json def get_wbt_dict(): """Generate a dictionary containing information for all tools. Returns: dict: The dictionary containing information for all tools. """ url = "https://github.com/giswqs/whiteboxgui/raw/master/whiteboxgui/data/whitebox_tools.json" response = urlopen(url) ...
f2c3c6a2f8881eec05cc4677098d104d30d4f8ea
3,622,382
def abs_path_from_ryven_dir(path_rel_to_ryven_dir: str): """Given a path string relative to the ryven dir '~/.ryven/', return the file/folder absolute path :param path_rel_to_ryven_dir: path relative to ryven dir (e.g. saves) :return: file/folder absolute path """ return abspath(join(ryven_dir_pat...
7eb365ad57e6a2ae6bb036699c53de98bc26a8a2
3,622,383
def get_points(features, fpn_strides): """Get points according to feature map sizes. Args: features (list[Tensor]): Multi-level feature map. Axis 0 represents the number of images `N` in the input data; axes 1-3 are channels, height, and width, which may vary between feature map...
37f452120c26091c170e7390fb5ee0f265b7b7d0
3,622,384
import tty def test_install_read_locked_requeue(install_mockery, monkeypatch, capfd): """Cover basic read lock handling for uninstalled package with requeue.""" orig_fn = inst.PackageInstaller._ensure_locked def _read(installer, lock_type, pkg): tty.msg('{0}->read locked {1}' .format(lock_type, p...
bfb360eb66ebe26d7046cff115f0a482dc531350
3,622,385
from typing import List import time async def get_proof_request( connection_id: str, schema_id: str, name_proof_request: str, zero_knowledge_proof: List[dict] = None, requested_attrs: List[str] = Query(None), self_attested: List[str] = None, revocation: int = None, exchange_tracing: bo...
b39aa7bc7ebad273baa0e1dfb153d0fb3e3ffefe
3,622,387
def add_saved_albums(auths=None, albums=(None,)): """ Adds/follows albums. :param auths: dict() being the 'destinations'-tree of the auth object as returned from authorize() :param albums: list() containing the albums IDs to add to the 'destinations' accounts :return: True """ for username i...
705dcd0a66e401866ce9a07c3ea7ca3eacf0dc19
3,622,388
def get_min(statistical_series): """ Get minimum value for each group :param statistical_series: Multiindex series :return: A series with minimum value for each group """ return statistical_series.groupby(level=0).agg('min')
c032f2f834cfe298a6c9f98c9116aaf354db0960
3,622,389
import time def now(): """ Get the current time function. :return: Time function. :rtype: function """ if hasattr(time, 'monotonic'): return time.monotonic return time.time
a50542697bbf4fa78d942fb564749e4e26b37ff4
3,622,390
def to_roman(value: int, make_upper: bool = True) -> str: """ The presence of 500 (D) and 50 (L), coupled with the special handling of 400, 900, 40, 90, 4 and 9, make table lookup seem like the best approach. """ if value == 0: return 'Zero' if value > 3999: return f'{value:,}' thousands, value ...
d74982f73848b2d64c421a10a2b3bed6c89a7c54
3,622,391
def plot_inventory_chart(remaining): """Update inventory chart. Parameters ---------- remaining : pandas.Series Series object containing the number of remaining items for each product category. Returns ------- fig : plotly.graph_objects.Figure Bar chart showing the ...
9661e1484936c39cc99cfa8522e4aff8aee9c7fd
3,622,392
import csv def readfile(path, filename): """ Parses a file created by the measurement software (which is based on LabVIEW) :param path: str :param filename: str :return: np.array """ rawfile = open(path + filename) file = csv.reader(rawfile, delimiter="\t") datalist = [] for row in...
6543a6ae878cd49d17e2961f2551975727085bd4
3,622,393
def get_isotropic_level(hierarchy_method, x_voxel_size, y_voxel_size, z_voxel_size): """Method to get the resolution level where the data is closest to isotropic Args: hierarchy_method(str): isotropic or anisotropic x_voxel_size(int): voxel size in x dimension y_voxe...
62b9bc3c730c4b41f2d6abf42858a51998859e9f
3,622,394
import scipy def pearson(exprDF, lMirUser = None, lGeneUser = None, n_core = 2, pval = True): """ Function to calculate the Pearson correlation coefficient, and pval of each pair of miRNA-mRNA, return a matrix of correlation coefficients with columns are miRNAs and rows are mRNAs. Args: ...
5decd8490edc5b2bc642fab188e09aba5991de9f
3,622,395
def detect_mode(editor): """ hook called to detect if this mode should be used for a file, returns True if it should be used, False otherwise """ workfile = editor.getWorkfile() global lexer try: filename = workfile.getFilename() if filename: lexer = get_lexer_for_filename(fi...
09809b245519a2cbbf47f435b6b672477450d4ed
3,622,396
def find_duplicate(strings: list): """find the first duplicate string from list:strings""" strings = [str(x) for x in strings.split(',')] map = defaultdict(int) duplicate_string = '' for word in strings: if map[word]: duplicate_string = word print(f'The duplicate string is "{word}"') break else: ...
fe94b14f1f425605bc2ae2dbb2ac4b3f01cdd2f4
3,622,397
def get_daily_returns(port_val): """Get daily returns of a portfolio value dataframe. Args: port_val (dataframe): daily portfolio value Returns: daily_ret (dataframe): daily returns """ daily_ret = port_val.copy() daily_ret[1:] = (port_val[1:] / port_val[:-1].values)-1 dail...
8d1a2dd03c2a5992b97b5d8d4b00cc65ebe4caba
3,622,399
def get_story(): # type: () -> Story """Get Story in session.""" return session[STORY_KEY]
d47b20ee0daca77240f92c94e227354f52f3fe8b
3,622,400
def align_vector_to_another(a=np.array([0, 0, 1]), b=np.array([1, 0, 0])): """Aligns vector a to vector b with axis angle rotation""" if np.array_equal(a, b): return None, None axis_ = np.cross(a, b) axis_ = axis_ / np.linalg.norm(axis_) angle = np.arccos(np.dot(a, b)) return axis_, ang...
4596d30b125f3a4d1bb1f7b06fcbb46368faf5ec
3,622,401
from typing import Sequence def rand_seq(alphabet, size, p=None): """Generate a random :class:`Sequence` of the given length from the given :class:`Alphabet`. Keyword Args: alphabet (Alphabet) size (int): The length of the randomly generated sequence. p (list): The discrete probab...
c8dd4b1a738489dd7a77918a6044a2eec56ff204
3,622,402
from pymantic.primitives import Literal def en(value): """Returns an RDF literal from the en language for the given value.""" return Literal(value, language='en')
4e3ff4a1a6a2965fd8a5acc81ed866e4b1aea9c7
3,622,403
import tempfile def minimal_sphinx_app(configuration=None, sourcedir=None): """Create a minimal Sphinx environment; loading sphinx roles, directives, etc. """ class MockSphinx(Sphinx): """Minimal sphinx init to load roles and directives.""" def __init__(self, confoverrides=None, srcdir=N...
5ad03e7def4958ee47e1ed083f9087be10fcd8e5
3,622,404
def add_sppc_args(parser): """Add args of SPP Container to app.""" parser.add_argument( '--dist-name', type=str, default='ubuntu', help="Name of Linux distribution") parser.add_argument( '--dist-ver', type=str, default='latest', help="Version ...
9458603e0ce6717858c2d844db85b159bff8714e
3,622,405
from typing import Iterable import re def rank4_naming(proteins_available: Iterable[str], best_match_protein_name: str) -> str: """ Given a list of proteins available as well as the best match name the function returns predicted name In this example the function extracts the first three letter patter...
ed3fe9f2563aa6cc808a8d4196c628872c2a1369
3,622,406
def init_infected_symptomatic_20(): """ Real Name: b'init Infected symptomatic 20' Original Eqn: b'0' Units: b'person' Limits: (None, None) Type: constant b'' """ return 0
c0cd99a5ce5180302946c54daef2d5bcb735cca2
3,622,407
def improve_p(time, b, I): """ calculate solution of Kolmogorov equation """ ret = odeint(deriv_improve_kolmog, [1, 0, 0], time, args=(b, I)) P_S, P_I, P_R = ret.T return P_S, P_I, P_R
b1bb905f1f00411aa344a87378b1b0a689674bc4
3,622,408
def has_singularity(order): """ Tests order for a 'Singularity', or a common reduction error resulting in huge counts""" order = order[4:-4] order_c = np.convolve(np.abs(order), [1, 1]) big = np.where(order_c > 500)[0] zero_crossings = np.where(np.diff(np.sign(order)))[0] return True if np.inter...
e9c66f7e29aa53dd7cf63775d4d5e61fe6ff2a95
3,622,409
import math def get_exact_angle(pt1, pt2): """ Given two cardinal points, returns the corresponding angle in *radians*. Args: * **pt1** (tuple): Point 1 * **pt2** (tuple): Point 2 Returns: float Angle (in radians) Example:: import picwriter.toolkit as tk ...
fea71b45bfdb2935caa619390959aa0dc1be917d
3,622,410
def _perceptive_hash(file_path, hash_size = 8): """Calculates a hash-value from an image Conversion uses a resized, grayscaled pixel-array of the image, converting the pixel-array to a number-array (differences between neighboring pixels) and finally converting these values to a hex-string of length ha...
be2363f084d3bdb5b360f849315a7b266e4aafee
3,622,411
def embed(x, vsz, dsz, initializer, finetune=True, scope="LUT"): """Perform a lookup table operation while freezing the PAD vector. Use the initializer to set the weights :param x: The input to this operation :param vsz: The size of the input vocabulary :param dsz: The output size or embedding dimensi...
b599db31526c851c370f12fd39e99d8a3899781d
3,622,412
def make_drf_request(request: HttpRequest = None, headers: dict = None): """ The request object made by APIRequestFactory is `WSGIRequest` which doesn't have `.query_params` or `.data` method as recommended by DRF. It only gets "upgraded" to DRF `Request` class after passing through the `APIView`, ...
31743159d452ce0e1cf8aa76182555a25f308c2c
3,622,413
def is_quit_event(event): """ Returns True if provided event is a quit event. :param event: Any pygame event. :return: True if QUIT signal is given, or ESC is pressed, or CMD + Q is pressed, or ALT + F4 is pressed. """ if event.type == pygame.QUIT: return True elif event.type == ...
57f4f884b43f6aa2a45e730f581269895f46a45e
3,622,414
def split_data(x, y, ratio, seed=1): """split the dataset based on the split ratio.""" # set seed np.random.seed(seed) # generate random indices num_row = len(y) indices = np.random.permutation(num_row) index_split = int(np.floor(ratio * num_row)) index_tr = indices[: index_split] in...
a1c51bebc53646459542047710cc547673a02c68
3,622,415
def trace_downstream( input_layer, split_distance=None, split_units="Kilometers", max_distance=None, max_distance_units="Kilometers", bounding_polygon_layer=None, source_database=None, generalize=True, output_name=None, context=None, ...
da0945b734c81b0f53fc9acf204db866eb9e4c82
3,622,416
from typing import Any from pathlib import Path def get_object_filepath(object: Any) -> str: """ Get object's filepath. """ path = Path(object.__code__.co_filename).absolute() try: filepath = "./" + path.relative_to(Path.cwd()).as_posix() except ValueError: filepath = path.as_p...
de30939b8699e812e712b4e5eea32cf6fe80eb4d
3,622,417
def linear_timeseries(start_value: float = 0, end_value: float = 1, length: int = 10, freq: str = 'D', start_ts: pd.Timestamp = pd.Timestamp('2000-01-01')) -> TimeSeries: """ Creates a TimeSeries with a starting value of `st...
4f41cb5dbba21cff1cb9496b6c8dda072a6a8ab3
3,622,418
import requests def get_blog_html(url: str) -> str: """ get the raw html of the blog post """ try: response = requests.get(url) if response.ok: return response.text else: return None except Exception as e: print(f"[!] Failed to get blog html: {str(e)...
8a155967919757db8f12dfabeee050ede2a04cfa
3,622,419
import math def calculate_mwp_mag(peak, epicentral_distance): """ Calculate Mwp magnitude. .. seealso:: [Tsuboi1999]_ and [Tsuboi1995]_ :type peak: float :param peak: Peak value of integral of displacement seismogram. :type epicentral_distance: float :param epicentral_distance: Great-cir...
5a12d8284fd0f133cd0cc03f42662f43eef95d0b
3,622,420
from unittest.mock import call def get_all_services(resource_root, cluster_name="default", view=None): """ Get all services @param resource_root: The root Resource object. @param cluster_name: Cluster name @return: A list of ApiService objects. """ return call(resource_root.get, SERVICES_PATH % (c...
781274c296c2c203dfa28e38b46492913cd7faa1
3,622,421
def _depgrep_rel_disjunction_action(_s, _l, tokens): """ Builds a lambda function representing a predicate on a tree node from the disjunction of several other such lambda functions. """ # filter out the pipe tokens = [x for x in tokens if x != "|"] # print 'relation disjunction tokens: ', t...
1daad27c573ff7e36083d422aacd9d232ecef32c
3,622,422
def get_buff(status): """获取人物指定的BUFF""" dm.use_dict(2) result = dm.find_str(142, 11, 1419, 48, status, color='C1E2DA-3B1D23|E4E0D7-1B1F28', sim=0.8) if result[0] > -1: return True
1bbda18e36de3eb39ad11b57ad9e6d4e1caf94b1
3,622,424
import struct def get_header_data(header_data_map: dict = {}, ecat_file: str = '', byte_offset: int = 0): """ Collects the header data from an ecat file, by default starts at byte position 0 (aka byte offset) for any header that is not the main header this offset will need to be provided :param header...
22af6780a9dd4197232ec80d42ceec729f1de107
3,622,425
import socket def _find_unused_port(): """ Finds a port that's available. Unfortunately, this port may not be available by the time the subprocess uses it, but this generally works. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) sock.bind(('127.0.0.1', 0)) sock.listen(socket.SOMAXCONN...
f715335d7e2bbc2a4a12cfb233e9d7a18fb6fdcf
3,622,426
def merge(batch, results): """ Merge clumped results files together """ merger = batch.new_job(name='merge-results') merger.image('ubuntu:18.04') if results: merger.command(f''' head -n 1 {results[0]} > {merger.ofile} for result in {" ".join(results)} do tail -n +2 "$result" >> {merg...
92037b34ff8db44381789f15518b5f44949b26a2
3,622,427
def model_with_buckets(encoder_inputs, decoder_inputs, targets, weights, buckets, seq2seq, softmax_loss_function=None, per_example_loss=False, name=None): """Create a sequence-to-sequence model with support for bucketing. The seq2seq argument is a function that defines ...
51455d3956f0117c23e50dad1250ba5727f779b9
3,622,428
import torch from typing import OrderedDict def torch_load_state_dict_without_module(ckp_file): """ this function using for load a model without module """ checkpoint = torch.load(ckp_file) state_dict =checkpoint['state_dict'] new_state_dict = OrderedDict() for k, v in state_dict.items():...
72f265b2087bd40d328d8760cc9668c9e6ccacf6
3,622,429
def resnet50c(config, norm_layer=nn.BatchNorm2D): """resnet50c implement The ResNet-50 [Heet al., 2016] with dilation convolution at last stage, ResNet-50 model Ref, https://arxiv.org/pdf/1512.03385.pdf Args: config (dict): configuration of network norm_layer: normalization layer t...
77864a3db2d50dc173564a69acb5e81d0cdab0a0
3,622,430
import json def set_parameters_in_cookie(response: Response) -> Response: """Set request parameters in the cookie, to use as future defaults.""" if response.status_code == status.HTTP_200_OK: data = {param: request.args[param] for param in PARAMS_TO_PERSIST if param in request.args} ...
ea186dc878a055f2c40143f1526af5c6200b71aa
3,622,431
def code_list_lengthener(code_list, parameter): """Ensures that code_list is long enough to accept an item in its parameter-th location""" while len(code_list) < parameter+1: code_list.append(0) return code_list
fd9a2d498ca1c679f44b0937a902bd95a7a882c8
3,622,432
import json def invoice(request): """Returns all invoices""" auth_client = AuthClient( settings.CLIENT_ID, settings.CLIENT_SECRET, settings.REDIRECT_URI, settings.ENVIRONMENT, ) client = QuickBooks( auth_client=auth_client, refresh_token=request.sessi...
59763a3bbe56fdef7f2372a3bdddfbb61af71b4a
3,622,434
def delete_user_account(): """ remove all character blueprint for current user """ if request.is_xhr: char_id = current_user.character_id try: delete_account(current_user) flash("Your account have been deleted.", 'info') return json_response('success', '', 200...
1867cfe34829f1f051d5008311c43de9fb8e0d1f
3,622,435
import unicodedata import re def unaccented_letters(s: str) -> str: """Return the letters of `s` with accents removed.""" s = unicodedata.normalize('NFKD', s) s = re.sub(r'[^\w -]', '', s) return s
e75b8929f8bd800ad4c79ae5688dea1067c351c5
3,622,436
def smooth_imgs(env: aneurysm_utils.Environment, mr_imgs: list, fwhm=1) -> list: """Smooth images.""" niimg_likes = get_nift_like(env, mr_imgs) smoothed = [] for img in niimg_likes: smoothed.append( nilearn.image.smooth_img(img, fwhm=fwhm).get_data().astype("<f4") ) retu...
8f8d781494779b45135e72f710bf081f0e60f958
3,622,438