content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def view_folio_contact(request, folio_id=None): """ View contact page within folio """ folio = get_object_or_404(Folio, pk=folio_id) if not folio.is_published and folio.author_id != request.user: return render( request, 'showcase/folio_is_not_published.html' ...
0269fea6322486912cdd462961fb847ffd8d038a
3,658,000
def faom03(t): """ Wrapper for ERFA function ``eraFaom03``. Parameters ---------- t : double array Returns ------- c_retval : double array Notes ----- The ERFA documentation is below. - - - - - - - - - - e r a F a o m 0 3 - - - - - - - - - - Fundamental ...
3e3d1c7e650d6034ed0793e4f1bc8605e9e82e32
3,658,001
from datetime import datetime import calendar def get_dtindex(interval, begin, end=None): """Creates a pandas datetime index for a given interval. Parameters ---------- interval : str or int Interval of the datetime index. Integer values will be treated as days. begin : datetime D...
32f0992365b075fb8601276bd3680c7db43a677e
3,658,002
import numpy def asanyarray(a, dtype=None, order=None): """Converts the input to an array, but passes ndarray subclasses through. Parameters ---------- a : array_like Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tupl...
c079d114ab224c487a65929b7710450262c66733
3,658,003
import os def envi_header(inputpath): """ Convert a envi binary/header path to a header, handling extensions Args: inputpath: path to envi binary file Returns: str: the header file associated with the input reference. """ if os.path.splitext(inputpath)[-1] == '.img' or os.path...
45df7507017676648cd4fae955da26916bbf4738
3,658,004
import base64 import struct from datetime import datetime def parse_fernet_timestamp(ciphertext): """ Returns timestamp embedded in Fernet-encrypted ciphertext, converted to Python datetime object. Decryption should be attempted before using this function, as that does cryptographically strong tests on t...
216d314c84679cc5806d6a483f68bff485375b36
3,658,005
def tagcloud(guids): """Get "tag cloud" for the search specified by guids Same return format as taglist, impl is always False. """ guids = set(guids) range = (0, 19 + len(guids)) tags = request.client.find_tags("EI", "", range=range, guids=guids, order="-post", flags="-datatag") return [(tagfmt(t.name), t, False...
fb94fab24040b3c38a68a2731d9b1bba0cccd3bc
3,658,006
def _ValidateContent(path, expected_content): """Helper to validate the given file's content.""" assert os.path.isfile(path), 'File didn\'t exist: %r' % path name = os.path.basename(path) current_content = open(path).read() if current_content == expected_content: print '%s is good.' % name else: try...
ddf6e3089f66d157f281655357753ff2b746d4a2
3,658,007
import os from sys import path def _test_image_path(): """ A 100 x 50 pixel GeoTIFF image, with 0 as NODATA value """ return os.path.join(path, "test.tiff")
b719a46fc7cdec952953502473000a7adb9b4625
3,658,008
from typing import Optional from typing import Sequence def api_ofrecord_image_decoder_random_crop( input_blob: remote_blob_util.BlobDef, blob_name: str, color_space: str = "BGR", num_attempts: int = 10, seed: Optional[int] = None, random_area: Sequence[float] = [0.08, 1.0], random_aspect_...
bcf8ad7deb97677e52b04e3204281a7ecc89c89c
3,658,009
def student_add_information(adding_student_id, student_information): """ 用于添加学生的详细信息 :@param adding_student_id: int :@param student_information: dict or str :@return : 运行状态(True or False) """ if type(student_information) == dict: adding_information = student_information elif type...
8a44177b90c1f3e10077313f6765a4699ded676b
3,658,010
from typing import Optional import os import importlib def import_file_as_module(filename: str, name: Optional[str] = None) -> ModuleType: """ NOTE(2020-11-09|domanchi): We're essentially executing arbitrary code here, so some thoughts should be recorded as to the security of this feature. This should not...
5aa9a54f8a8ed4a42bc49f806c2ac38d01b8ccfa
3,658,011
async def get_show_by_month_day(month: conint(ge=1, le=12), day: conint(ge=1, le=31)): """Retrieve a Show object, based on month and day, containing: Show ID, date and basic information.""" try: show = Show(database_connection=_database_connection) shows = show.retrieve_by_month_day(month, d...
e774f61254a3d7cdfc9a49ca1a9eea4f65853f55
3,658,012
import random def generate_random_tag(length): """Generate a random alphanumeric tag of specified length. Parameters ---------- length : int The length of the tag, in characters Returns ------- str An alphanumeric tag of specified length. Notes ----- The ge...
b62a103663b69f0a27d8ba23134473dc01932409
3,658,013
import io def loadmat(filename, check_arrays=False, **kwargs): """ Big thanks to mergen on stackexchange for this: http://stackoverflow.com/a/8832212 This function should be called instead of direct scipy.io.loadmat as it cures the problem of not properly recovering python dictionaries fr...
3b054cbabc03b468ec0c80a4ed544b1c054ef223
3,658,014
def _export_output_to_tensors(export_output): """Get a list of `Tensors` used in `export_output`. Args: export_output: an `ExportOutput` object such as `ClassificationOutput`, `RegressionOutput`, or `PredictOutput`. Returns: a list of tensors used in export_output. Raises: ValueError: ...
913c1b232f8ac6e66e9104c055c9d34726db1027
3,658,015
import logging def train_city_s1(city:str, pollutant= 'PM2.5', n_jobs=-2, default_meta=False, search_wind_damp=False, choose_cat_hour=False, choose_cat_month=True, add_weight=True, instr='MODIS', op_fire_zone=False, op_fire_twice=False, op_lag=True, search_tpot=False, main_data_folder: str ...
43cd4ff89068feba1bca3c316e40b19f852c1da2
3,658,016
def constructCbsdGrantInfo(reg_request, grant_request, is_managing_sas=True): """Constructs a |CbsdGrantInfo| tuple from the given data.""" lat_cbsd = reg_request['installationParam']['latitude'] lon_cbsd = reg_request['installationParam']['longitude'] height_cbsd = reg_request['installationParam']['height'] ...
aff6a37f7831a185a7c1a3168c42a692768ae4e9
3,658,017
def download_raw_pages_content(pages_count): """download habr pages by page count""" return [fetch_raw_content(page) for page in range(1, pages_count + 1)]
77e369a986ff09887a71d996226d147fef9a36ec
3,658,018
def tseries2bpoframe(s: pd.Series, freq: str = "MS", prefix: str = "") -> pd.DataFrame: """ Aggregate timeseries with varying values to a dataframe with base, peak and offpeak timeseries, grouped by provided time interval. Parameters ---------- s : Series Timeseries with hourly or quart...
6b97bc3b8c925be68ba79e8a9abdc2795500df76
3,658,019
def calc_buffered_bounds( format, bounds, meters_per_pixel_dim, layer_name, geometry_type, buffer_cfg): """ Calculate the buffered bounds per format per layer based on config. """ if not buffer_cfg: return bounds format_buffer_cfg = buffer_cfg.get(format.extension) if f...
5bbf9720525126e3dcd000329493c894c8249771
3,658,020
async def read_users_me( current_user: models.User = Depends(security.get_current_active_user), ): """Get User data""" return current_user
4b2e37586a4e13074ec009f4cd7e64e7a357d539
3,658,021
import os def cal_energy_parameters_for_one_channel(sub_sample_label_dict, channel, importance=1): """ the loss comes equally from four sources: connected component (0D), boundary (1D), area (2D), and rim_enhance e.g. a small region with long boundaries means it accounts for lots of 1D loss and little of ...
7d82fb2b2e232fee027971913475ff310b1b736e
3,658,022
import logging def get_logger(logfile): """Instantiate a simple logger. """ fmt = "%(levelname)s:%(filename)s:%(lineno)s:%(funcName)s: %(message)s" #fmt = '%(levelname)s:%(filename)s:%(lineno)s:%(funcName)s:%(asctime)s: %(message)s'] datefmt = '%Y-%m-%dT%H:%M:%S' logger = logging.getLogger(...
a3bd9387b745e3cb001a44c4f3c11488fef3c106
3,658,023
import logging def __to_signed(val, bits): """ internal function to convert a unsigned integer to signed of given bits length """ logging.debug(" in: value = %d", val) mask = 0x00 for i in range(int(bits / 8)): mask |= 0xff << (i * 8) if val >= (1 << (bits - 1)): va...
618b02ad5a67c31a5942430ec64abcad59708ddd
3,658,024
from typing import Iterable from typing import Tuple def compute_qp_objective( configuration: Configuration, tasks: Iterable[Task], damping: float ) -> Tuple[np.ndarray, np.ndarray]: """ Compute the Hessian matrix :math:`H` and linear vector :math:`c` of the QP objective function: .. math:: ...
623997bbaf7ce92c39084fa44960593b55a0b3a0
3,658,025
def _is_existing_account(respondent_email): """ Checks if the respondent already exists against the email address provided :param respondent_email: email of the respondent :type respondent_email: str :return: returns true if account already registered :rtype: bool """ respondent = party_...
4cb0462f748d0b80dbb12f89364d279a3436b632
3,658,026
import socket def basic_checks(server,port): """Perform basics checks on given host""" sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 2 seconds timeout sock.settimeout(2) return sock.connect_ex((server,int(port))) == 0
4a31521089feb2c178bb5202fa818804dfe87142
3,658,027
import time def test(ipu_estimator, args, x_test, y_test): """ Test the model on IPU by loading weights from the final checkpoint in the given `args.model_dir`. """ def input_fn(): dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test)) dataset = dataset.prefetch(len(x_test...
083c2c830315ccf2602109a4a3e718cecd1b6760
3,658,028
def _get_service(): """Gets service instance to start API searches. Returns: A Google API Service used to send requests. """ # Create the AI Platform service object. # To authenticate set the environment variable # GOOGLE_APPLICATION_CREDENTIALS=<path_to_service_account_file> return g...
5d79698216626eff9618dc55b6b651a5da3f5187
3,658,029
def giq(scores, targets, I, ordered, cumsum, penalties, randomized, allow_zero_sets): """ Generalized inverse quantile conformity score function. E from equation (7) in Romano, Sesia, Candes. Find the minimum tau in [0, 1] such that the correct label enters. """ E = -np.ones((scores.shape[0],)) ...
99a877053cf095622184cbbd9043b742c6ae076f
3,658,030
def findUser(userId): """ :param userId: :return: The user obj Finds a particular user from a dataset. """ return user_collection.find_one({"user_id": userId})
ffca934689c554993ca5d33005a32e4f9afe48cd
3,658,031
def sub_sample_map(data, aug_map, n_input, n_output, n_teach, buffer): """ Expands an augmentation map to produce indexes that will allow targets values of previous outputs to be used as inputs """ n_io = n_input + n_output n_req = n_io teach_range = range(n_teach) tf_map = [] for ...
05f88939ad2e293e3370f5585ad30f1d9d6256d1
3,658,032
def capture_flow(pkt_hist): """ Monitors the flow in the file. :param pkt_hist: a list of raw eth packets :return: 0 (No errors) """ closedby = [] global numFlows, flow_buffer, sent_buffer, ackd_buffer, received_buffer, retransmissions, end_ts, retransmissions_timeout, retransmissions_fast ...
41a1628960aa4c95c2859fbbe10410fb49289d04
3,658,033
import time import subprocess import traceback def run_customcheck_command(check): """Function that starts as a thread (future) to process a custom check command Process a custom check command until a given timeout. The result will be added to the cached_customchecks_check_data object. proce...
aa4846d08190c16e4a1edb49d369ba093f767b3c
3,658,034
def rcGetBBModelEnum(): """ Get the BeagleBone model as member of the BBModel Enum. """ return BBModel(rcGetBBModel())
90cf6857f2754a1947d017a1a57b11790d534c05
3,658,035
def ordToString(ordList): """Use this function to convert ord values to strings.""" newStrList = [] cstr = "" for cint in ordList: cstr += chr(cint) if cint == 44: newStrList.append(cstr[:-1]) cstr = "" return newStrList
5a836f7fe34803744de90aa2608e3d99a081c7ff
3,658,036
def get_test_data_for_successful_build(): """Returns a test data set of test suites and cases that passed. """ return _get_test_data(["PASSED", "PASSED", "PASSED"])
8969d33f887dcc7c7f7fb8148cbcfc7a4eb4d7c1
3,658,037
import re import logging def fromOldAdjacencyList(adjlist, group=False, saturateH=False): """ Convert a pre-June-2014 string adjacency list `adjlist` into a set of :class:`Atom` and :class:`Bond` objects. It can read both "old style" that existed for years, an the "intermediate style" that existe...
0c54ee172948437f9cb075c5880eb7eb25d2893f
3,658,038
def read_arg_optional( src, args, n_optional=-1, tolerance=0, mode=MODE_NON_MATH, skip_math=False): """Read next optional argument from buffer. If the command has remaining optional arguments, look for: a. A spacer. Skip the spacer if it exists. b. A bracket delimiter. If the optional ar...
641fe9ab9a96b6e59e15b115abe843fa09a07659
3,658,039
def searcheduxapian_ajax_get_schlagwort(request, item_container): """ moegliche Schlagworte """ schlagworte = get_schlagworte(request.GET['query']) res = '<items>\n' for schlagwort in schlagworte: res += '<schlagwort>\n<name><![CDATA[%s]]></name>\n</schlagwort>\n' % schlagwort.name res += '</items>\n' r...
5a248ced5006d49f2dc303c68957d07ba187c3d5
3,658,040
def expanded_X_y_sample_weights(X, y_proba, expand_factor=10, sample_weight=None, shuffle=True, random_state=None): """ scikit-learn can't optimize cross-entropy directly if target probability values are not indicator vectors. As a workarou...
7398062d3eb75fa68c39e20415b944e58a20387e
3,658,041
def refine_uniformly(dom, seg): """ Refine all edges of the given domain and segmentation. :param dom: Domain to refine :type dom: :class:`viennagrid.Domain` :param seg: Segmentation of the domain to refine :type seg: :class:`viennagrid.Segmentation` :returns: A two-element tuple containing the output domain...
623b9fc2fa6c83133ca1e01714fecba7e70ab95e
3,658,042
def rename_tuning(name, new_name): """rename tuning""" session = tables.get_session() if session is None: return False, 'connect' try: tuning_table = TuningTable() if not tuning_table.check_exist_by_name(TuningTable, name, session): return False, 'tuning not exist' ...
1ea1498483fc9abe0bb5be7a7c892c6a171b5df9
3,658,043
import logging async def get_event(token: str, event_id: str) -> dict: """Get event - return new if no event found.""" event = {"id": event_id, "name": "Nytt arrangement", "organiser": "Ikke valgt"} if event_id != "": logging.debug(f"get_event {event_id}") event = await EventsAdapter().get...
a071da872e9a2f670926da5b7a8d4644acaf237e
3,658,044
import re def _xfsdump_output(data): """ Parse CLI output of the xfsdump utility. """ out = {} summary = [] summary_block = False for line in [l.strip() for l in data.split("\n") if l.strip()]: line = re.sub("^xfsdump: ", "", line) if line.startswith("session id:"): ...
dbc7fbf9dced99b83a7dc5917c473a1dee16d749
3,658,045
def get_current(): """Return the currently running interpreter.""" id = _interpreters.get_current() return Interpreter(id)
0949280d364cc6f2935b9109c19c508ed06352b8
3,658,046
def csstext(text: str, cls: str, span: bool=False, header: bool=False) -> str: """ Custom build HTML text element. """ if span: tag = 'span' elif header: tag = 'h1' else: tag = 'p' return f'<{tag} class="{cls}">{str(text)}</{tag}>'
0833fd9d83143e09b5c234e193a8e53ef653112b
3,658,047
def trans_exam_list_to_colum(example_list, headers=None): """ 将example列表转换成以列表示的形式,用于适配输出附加信息 :param example_list: example 列表 :param headers: 需要的属性,默认为("question", "answer", "yes_or_no") :return: {header1:[...],header2:[...],...} """ if headers is None: headers = ("question", "answer...
ff5a2e5f6e27ce0a32717e55ba35dbd864a11dbb
3,658,048
def member(): """ RESTful CRUD Controller """ return s3_rest_controller()
2f14df1f9b97ee4777c2ce0740207c691aedb1c2
3,658,049
from datetime import datetime def _now(): """Get EST localized now datetime.""" return EST_TIMEZONE.localize(datetime.datetime.now())
a7a62b5f5febdbacab0c0ac1e6ef0de843f09a11
3,658,050
def pydantic_model_to_pandas(pydantic_model_input) -> pd.DataFrame: """ Function that transforms <pydantic.BaseModel> child objects to <pandas.DataFrame> objects :param pydantic_model_input: Input validator for API """ return dict_to_pandas(pydantic_model_input.dict())
8397c39d7c760ad44565a7b89013d95c241413ed
3,658,051
def calculate_pair_energy(coordinates, i_particle, box_length, cutoff): """ Calculate the interaction energy of a particle with its environment (all other particles in the system) - rewrite Parameters ---------- coordinates : list The coordinates for all particles in the system ...
42150ff5282731b13e4ac512c08fd71566f0bdb4
3,658,052
def simulation_activation(model, parcel_df, aerosols_panel): """ Given the DataFrame output from a parcel model simulation, compute activation kinetic limitation diagnostics. Parameters ---------- model : ParcelModel The ParcelModel parcel_df : DataFrame used to generate the results to ...
41461da13062177124ca4ebedc801ff5d574fbb8
3,658,053
import os import sys import logging def create(options, args): """ Instantiate and return a Blueprint object from either standard input or by reverse-engineering the system. """ try: with context_managers.mkdtemp(): if not os.isatty(sys.stdin.fileno()): try: ...
556ac20f6b10c58011a99f217f8e4410faac6ee9
3,658,054
def create_config( case=None, Exp='Dummy', Type='Tor', Lim=None, Bump_posextent=[np.pi/4., np.pi/4], R=None, r=None, elong=None, Dshape=None, divlow=None, divup=None, nP=None, returnas=None, strict=None, SavePath='./', path=_path_testcases, ): """ Create easily a tofu.geom.Config object ...
e9f855ff614cd511f730afd34c34e1d610b06a43
3,658,055
def is_project_description(description): """Validates the specified project description. A valid description is simply a non-empty string. Args: description (str): A project description to validate. Returns: <bool, str|None>: A pair containing the value True if the specified descripti...
ef831f2ddeede75bb1dbd0730dccacba3e379c2b
3,658,056
import json def remove_friend(): """ Accepts an existing friend request. """ data = json.loads(request.data) friend_id = data['id'] user = interface.get_user_by_id(get_jwt_identity()) friend = interface.get_user_by_id(friend_id) interface.remove_friendship(user, friend) return '...
0d5e2c390d5da7ff1869d907bbe85bcda80a9513
3,658,057
import functools import logging def ensure_configured(func): """Modify a function to call ``basicConfig`` first if no handlers exist.""" @functools.wraps(func) def wrapper(*args, **kwargs): if len(logging.root.handlers) == 0: basicConfig() return func(*args, **kwargs) ret...
2c04afd53ab9c7341fc4913485a8a1f7f7e7e1b3
3,658,058
from typing import Dict from typing import Any from typing import Optional from typing import Type def get_loss(dataset_properties: Dict[str, Any], name: Optional[str] = None) -> Type[Loss]: """ Utility function to get losses for the given dataset properties. If name is mentioned, checks if the loss is co...
a9f75d6e2c35a0b9472e3fdc046f72eb1188e48d
3,658,059
def ten_to_base(value : int, base): """Converts a given decimal value into the specified base. :param value: The number to convert :param base: The base to convert the specified number to :return: The converted value in the specified base """ # Check if the base is 10, return the value if...
2f5ba92af48fe2ce19dbcb6001afadfde2514373
3,658,060
def get_style(selector, name): """ Returns the resolved CSS style for the given property name. :param selector: :param name: """ if not get_instance(): raise Exception("You need to start a browser first with open_browser()") return get_style_g(get_instance(), selector, name)
903e4abc09dc196d0d1dbbbb3c58869e3c0beb78
3,658,061
import inspect def argmod(*args): """ Decorator that intercepts and modifies function arguments. Args: from_param (str|list): A parameter or list of possible parameters that should be modified using `modifier_func`. Passing a list of possible parameters is useful when a fu...
5824d20568a3913be59941df0e4f657f05f08cc0
3,658,062
def group_update(group_id, group_min, group_max, desired): """ Test with invalid input >>> group_update('foo', 2, 1, 4) {} """ if group_min > group_max or desired < group_min or desired > group_max: return {} try: client = boto3.client('autoscaling') response = clien...
77eef10b7db604a3aa2e32bdd0d226fb44cf07ab
3,658,063
def remove_bookmark(request, id): """ This view deletes a bookmark. If requested via ajax it also returns the add bookmark form to replace the drop bookmark form. """ bookmark = get_object_or_404(Bookmark, id=id, user=request.user) if request.method == "POST": bookmark.delete() ...
9c8442d5a313e7babf71b9f9a4c41452c65c5aab
3,658,064
def parse_propa(blob): """Creates new blob entries for the given blob keys""" if "track_in" in blob.keys(): muon = blob["track_in"] blob["Muon"] = Table( { "id": np.array(muon)[:, 0].astype(int), "pos_x": np.array(muon)[:, 1], "pos_y...
ae7993d6e51287b6a88d125f63ef7d6edd001cf1
3,658,065
def parseParams(opt): """Parse a set of name=value parameters in the input value. Return list of (name,value) pairs. Raise ValueError if a parameter is badly formatted. """ params = [] for nameval in opt: try: name, val = nameval.split("=") except ValueError: ...
b932f74c8e5502ebdd7a8749c2de4b30921d518b
3,658,066
from ._sparse_array import SparseArray def asnumpy(a, dtype=None, order=None): """Returns a dense numpy array from an arbitrary source array. Args: a: Arbitrary object that can be converted to :class:`numpy.ndarray`. order ({'C', 'F', 'A'}): The desired memory layout of the output ...
54bea22ab6fe8327b3a4df93ac9e4447b4d65fec
3,658,067
def get_next_cpi_date(): """ Get next CPI release date """ df = pd.read_html(r"https://www.bls.gov/schedule/news_release/cpi.htm")[0][:-1] df["Release Date"] = pd.to_datetime(df["Release Date"], errors='coerce') df = df[df["Release Date"] >= current_date].iloc[0] df['Release Date'] = df['Rel...
e23b9bea0996ac442115163729ffeed1407e52b5
3,658,068
from typing import Tuple from datetime import datetime def date_arithmetic() -> Tuple[datetime, datetime, int]: """ This function is used to calculate what is the date after 3 days is given and the differences between two given dates """ date1: str = "Feb 27, 2020" date_2020: datetime = datetim...
1e2d4681578ccab11612771589a46f22246071eb
3,658,069
def get_words_from_line_list(text): """ Applies Translations and returns the list of words from the text document """ text = text.translate(translation_table) word_list = [x for x in text.split() if x not in set(stopwords.words('english'))] return word_list
aaa2a1476e887aa6a7d477d67528f838d6f229b9
3,658,070
def _get_name(dist): """Attempts to get a distribution's short name, excluding the name scope.""" return getattr(dist, 'parameters', {}).get('name', dist.name)
fd57e523c1a84a36f9ed56236e4b8db1e887575c
3,658,071
def compute_mean_std(all_X): """Return an approximate mean and std for every feature""" concatenated = np.concatenate(all_X, axis=0).astype(np.float64) mean = np.mean(concatenated, axis=0) std = np.std(concatenated, axis=0) std[std == 0] = 1 return mean, std
b102a045705efdab8d9783e04da192ec30e167f7
3,658,072
def GenerateConfig(context): """Generates configuration.""" key_ring = { 'name': 'keyRing', 'type': 'gcp-types/cloudkms-v1:projects.locations.keyRings', 'properties': { 'parent': 'projects/' + context.env['project'] + '/locations/' + context.properties['region'], 'keyRingId': context.env['d...
257b7217c1a08bba46866aff0b7faa1a03fe7fdc
3,658,073
def get_valid_collapsed_products(products, limit): """wraps around collapse_products and respecting a limit to ensure that uncomplete products are not collapsed """ next_min_scanid = get_next_min_scanid(products, limit) collapsed_products = [] for scanid, scan in groupby(products, itemgetter(...
df3ffa503855a020c7c011aa58cba20243e19be4
3,658,074
def get_imd(): """Fetches data about LA IMD status. The "local concentration" measure is used - this gives higher weight to particularly deprived areas Source: http://www.gov.uk/government/statistics/english-indices-of-deprivation-2019 """ imd = pd.read_csv( PROJECT_DIR / "inputs/data/so...
4e2495dda505bde8dd8ccf62234730a7227ffa97
3,658,075
def read_bgr(file): """指定ファイルからBGRイメージとして読み込む. # Args: file: イメージファイル名. # Returns: 成功したらイメージ、失敗したら None. """ return cv2.imread(file, cv2.IMREAD_COLOR)
ee96842899ffefa0508218d0a4b721f2ae5a7efb
3,658,076
def _remove_none_from_post_data_additional_rules_list(json): """ removes hidden field value from json field "additional_rules" list, which is there to ensure field exists for editing purposes :param json: this is data that is going to be posted """ data = json additional_rules = json.get...
c82aa568f82ba4abcb8f4e6f9c770969277d078f
3,658,077
import traceback def add_email(request, pk): """ This Endpoint will add the email id into the person contact details. It expects personId in URL param. """ try: request_data = request.data email = request_data.get("email") person = Person.objects.filter(id=pk).last...
5669b442e7ef4fb3e5a22053c368e6a4b68cfeef
3,658,078
from typing import Any def coords_extracter(): """Exctract coords to send command to robot. To be executed inside of xarm_hand_control module.""" SKIPPED_COMMANDS = 5 COEFF = 22 current = [0] def coords_to_command(data: Any): current[0] += 1 if current[0] < SKIPPED_COMMANDS:...
930cef91e517751da3c3fb441543ab736be6aa23
3,658,079
def NO_MERGE(writer, segments): """This policy does not merge any existing segments. """ return segments
0742365f30d59cb219ac60483b867180bd910ba8
3,658,080
import gzip import shutil def save_features(): """ Writes extracted feature vectors into a binary or text file, per args. :return: none """ extractor = args.extractor features = [] if extractor == 'multi': features = extract_multi() elif extractor == 'single': feature...
65fd172aa0ff0283111c9e8148eb33a1160255d3
3,658,081
def build_ntwk(p, s_params): """ Construct a network object from the model and simulation params. """ np.random.seed(s_params['RNG_SEED']) # set membrane properties n = p['N_PC'] + p['N_INH'] t_m = cc( [np.repeat(p['T_M_PC'], p['N_PC']), np.repeat(p['T_M_INH'], p['N_INH...
88a5b5c73edf015d9b2b4137db874252f63a3571
3,658,082
def createAaronWorld(): """ Create an empty world as an example to build future projects from. """ # Set up a barebones project project = makeBasicProject() # Create sprite sheet for the player sprite player_sprite_sheet = addSpriteSheet(project, "actor_animated.png", "actor_animated", "act...
7326aee61ee4977ccc422955fbd33c6a51b13e37
3,658,083
def builtin_ljustify(s, w, p): """Left-justify a string to a given width with a given padding character.""" sv = s.convert(BStr()).value pv = p.convert(BStr()).value return BStr(sv.ljust(w.value, pv))
dda28d65d1916a7e01aa36e7b90ee5ba98329c58
3,658,084
import os def package_files(directory): """package_files recursive method which will lets you set the package_data parameter in the setup call. """ paths = [] for (path, _, filenames) in os.walk(directory): for filename in filenames: paths.append(os.path.join('..', path, f...
e043de9a9e8ed9092f933df00b167b092ba6abaa
3,658,085
def get_effective_router(appname): """Returns a private copy of the effective router for the specified application""" if not routers or appname not in routers: return None return Storage(routers[appname])
dd0e3ccc8d05864b5a324541129845e5f82c2669
3,658,086
def is_activated(user_id): """Checks if a user has activated their account. Returns True or false""" cur = getDb().cursor() cur.execute('SELECT inactive FROM users where user_id=%s', (user_id,)) inactive = cur.fetchone()[0] cur.close() return False if inactive is 1 else True
704a5c3462be3612e5cd44057ee082d612ae8aa9
3,658,087
import base64 import json def _encode(dictionary): """Encodes any arbitrary dictionary into a pagination token. Args: dictionary: (dict) Dictionary to basee64-encode Returns: (string) encoded page token representing a page of items """ # Strip ugly base64 padding. return base...
e9a490e659a3a0e6d546fd2ab4dd89a5f6a748af
3,658,088
from typing import List from pathlib import Path import tempfile import gc import os def remove_duplicates_sharded( files: List[Path], outputs: List[Path], hashes_dir: FilesOrDir, field: str, group_hashes: int = 1, tmp_dir: Path = None, min_len: int = 0, ): """Remove duplicates in seve...
6ab2477cd3c3fb513af2fbb4808c0279212b1cd2
3,658,089
def selectPlate(plates, jdRange, normalise=False, scope='all'): """From a list of simulated plates, returns the optimal one.""" # Gets the JD range for the following night nextNightJDrange = _getNextNightRange(jdRange) # First we exclude plates without new exposures plates = [plate for plate in pl...
f48207a9be002e6b2295d4100e02ffaddde779e8
3,658,090
from typing import Union def get_events( raw: mne.io.BaseRaw, event_picks: Union[str, list[str], list[tuple[str, str]]], ) -> tuple[np.ndarray, dict]: """Get events from given Raw instance and event id.""" if isinstance(event_picks, str): event_picks = [event_picks] events = None for e...
d1b5c961160848607a40cfcb5b2ba8a47625ab21
3,658,091
def transplant(root, u, v): """ 注意, 这里要返回root, 不然修改不了 """ if u.parent == None: root = v elif u.parent.left == u: u.parent.left = v else: u.parent.right = v if v: v.parent = u.parent return root
cadf0433399e428596d1d0d4ab200e4d79285d21
3,658,092
def is_head_moderator(): """ Returns true if invoking author is a Head Moderator (role). """ async def predicate(ctx: Context): if not any(config.HEAD_MOD_ROLE in role.id for role in ctx.author.roles): raise NotStaff("The command `{}` can only be used by a Head Moderator.".format(ctx...
22f80251190d914d38052e67ca8fe47279eab833
3,658,093
def compute_adj_matrices(type, normalize=True): """ Computes adjacency matrices 'n', 'd' or 's' used in GCRAM. """ # Get channel names raw = mne.io.read_raw_edf('dataset/physionet.org/files/eegmmidb/1.0.0/S001/S001R01.edf', preload=True, verbose=False).to_data_frame() ch_names = raw.columns[2:]...
cecf0c94c5d1efe6c6210949736377d5d7d454c4
3,658,094
from typing import Optional def build_census_chart( *, alt, census_floor_df: pd.DataFrame, max_y_axis: Optional[int] = None, use_log_scale: bool = False ) -> Chart: """ This builds the "Admitted Patients" census chart, projecting total number of patients in the hospital over time. Args: alt: ...
315329e593e116dbf63fb02772bf9394722feb90
3,658,095
def hasNonAsciiCharacters(sText): """ Returns True is specified string has non-ASCII characters, False if ASCII only. """ sTmp = unicode(sText, errors='ignore') if isinstance(sText, str) else sText; return not all(ord(ch) < 128 for ch in sTmp);
c1627d1a0a26e7c4d4e04c84085197ba44b5e640
3,658,096
def draw_matches(image_1, image_1_keypoints, image_2, image_2_keypoints, matches): """ Draws the matches between the image_1 and image_2. (Credit: GT CP2017 course provided source) Params: image_1: The first image (can be color or grayscale). image_1_keypoints: The image_1 keypoints. ...
d2984de4c542fca7dda3863ad934e9eddc14a375
3,658,097
def copy_ttl_in(): """ COPY_TTL_IN Action """ return _action("COPY_TTL_IN")
a01acb2645e033ad658435e9ca0323aec10b720c
3,658,098
import torch from typing import Optional def neuron_weight( layer: str, weight: torch.Tensor, x: Optional[int] = None, y: Optional[int] = None, batch: Optional[int] = None, ) -> Objective: """Linearly weighted channel activation at one location as objective :param layer: Name of the l...
646966613249a02468e00b91157fd43459d246bb
3,658,099