content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def cropDetectionSegments(ffBinRead, segmentList, cropSize = 64): """ Crops small images around detections. ffBinRead: read FF bin structure segmentList: list of coordinate tuples [(x1, y1), (x2, y2),...] cropSize: image square size in pixels (e.g. 64x64 pixels)""" ncols = ffBinRead.ncols - 1...
749f13efabc60f9b443ea84cabd459d9a8a70241
3,632,428
def delete_site_request(site_id): """Request deletion of a site.""" site = InventorySite.query.filter_by(id=site_id).first() if site is None: abort(404) return render_template('inventory/manage_site.html', site=site)
3b137e3140fb5fa9cf9f79dce2cc8b283d3a4a70
3,632,429
def twoD_Gaussian(tup, amplitude, xo, yo, sigma_x, sigma_y, theta, offset): """ A 2D Gaussian to be used to fit the cross-correlation Args: tup (tuple): A two element tuple containing the (x,y) coordinates where the 2D Gaussian will be evaluated amplitude (float): The am...
35a4d6362f8751294e460dc7ae529bcb7a48022a
3,632,430
from itertools import combinations def generate_synthetic_example(n_stations=65, lat_lims=(45, 50), lon_lims=(10, 20), u_0=0, A=.1, phi_2=60, B=.01, phi_4=20, amplitude_noise=.05): """ Helper function to generate a simple synthetic example. Constant anisotropy in entire region. :param n_stations: Num...
7879af1efcbb7204f454b337f2197f0442673e1f
3,632,431
import yaml def get_palette(col, col_unique=None, as_dict=True): """Get palette for column. Parameters ---------- col : {'subject_name', 'model', 'scaling', 'cell_type', str} The column to return the palette for. If we don't have a particular palette picked out, the palette will conta...
ab134032798d1679366533968c4bc0f277f764bf
3,632,433
import ROOT def array2hist(array, hist, errors=None): """Convert a NumPy array into a ROOT histogram Parameters ---------- array : numpy array A 1, 2, or 3-d numpy array that will set the bin contents of the ROOT histogram. hist : ROOT TH1, TH2, or TH3 A ROOT histogram. ...
40522a374321b768fac800a4fce22440991de05f
3,632,434
def adjust_update_rules_for_fixed_nodes(predecessor_node_lists, truth_tables, fixed_nodes): """ Adjust "update rules" matrix and its free element vector so that the fixed nodes will end up in their fixed states on each time step automatically, with no manual interventions required. :param predecessor_n...
f41609ae25c3622100674372de5a364b095650f8
3,632,435
def obs_data(): """ Dictionary with variables as top keys and available observations directly below. For each observation data set, path and file pattern must be defined. """ meta_dict = { # ------------------------------------------------------------------------ # 2m temperature '...
f3db013fa2b99cdaee26b82075674a69a662030c
3,632,436
def create_class_prediction_error_chart(classifier, X_train, X_test, y_train, y_test): """Create class prediction error chart. Tip: Check Sklearn-Neptune integration `documentation <https://docs-beta.neptune.ai/essentials/integrations/machine-learning-frameworks/sklearn>`_ for the full ...
c0aadac243614914952d10d484ea4a9a7c89da26
3,632,437
def footer_embed(message: str, title) -> Embed: """ Constructs embed with fixed green color and fixed footer showing website, privacy url and rules url. :param message: embed description :param title: title of embed :return: Embed object """ content_footer = ( f"Links: [Website]({co...
cb4637e479d5eabb3afedb965209271553e1f238
3,632,438
def joins_for_results(basetables, external_info): """ Form and return the `results` table """ # Get one table per result_type, then stack them, # kind_problem # kind_pathproblem # # Concatenation with an empty table triggers type conversion to float, so don't # include empty ta...
1b2821a11a9a3df65ef9a3dfbf11262175307b9d
3,632,440
def newton_wedge_fringe_sep(alpha, wavelength): """Calculate the separation between fringes for an optical flat with angle alpha.""" d = wavelength/(2*np.sin(alpha)) return d
fc29c6bfcfb6ed19e91588263ef12190bb9ec699
3,632,441
def train_test_split(shp, savedir, config, client = None): """Create the train test split Args: shp: a filter pandas dataframe (or geodataframe) savedir: directly to save train/test and metadata csv files client: optional dask client Returns: None: train.shp and test.shp ar...
46c8becd416877306e9d28914f3032ff99946321
3,632,443
def parse_list_from_string(value): """ Handle array fields by converting them to a list. Example: 1,2,3 -> ['1','2','3'] """ return [x.strip() for x in value.split(",")]
51e9c654b9d18b8be61c37aab5f5029dfdea2213
3,632,444
def add_evaluation_args(parser): """Evaluation arguments.""" group = parser.add_argument_group('validation', 'validation configurations') group.add_argument('--eval-batch-size', type=int, default=None, help='Data Loader batch size for evaluation datasets.' 'De...
437a77987e9a4a461b98c9cb08b78a016efca9e9
3,632,445
import itertools def merge(d1, d2): """Merge to dicts into one. Args: d1 (dict): dataset 1 d2 (dict): dataset 2 Returns: dict: merged dict """ return dict(itertools.chain(list(d1.items()), list(d2.items())))
bb1d38f3cb45de6e98855fb04ae1d3d7e73e4a40
3,632,446
import re def is_valid(number): """ Check if number is roman :param number: string to check :type number: str :return: True or False :rtype: bool """ return re.match( r"^(M{0,3})(D?C{0,3}|C[DM])(L?X{0,3}|X[LC])(V?I{0,3}|I[VX])$", number )
52e1937418d28701ee3d30da139f16ae64cfe480
3,632,447
def lammps_created_gsd(job): """Check if the mdtraj has converted the production to a gsd trajectory for the job.""" return job.isfile("prod.gsd")
1b05e085970de4d875044e2e6604c1874a0a0e83
3,632,448
def has_open_quotes(s): """Return whether a string has open quotes. This simply counts whether the number of quote characters of either type in the string is odd. Returns ------- If there is an open quote, the quote character is returned. Else, return False. """ # We check " first...
a9adbcd42518a71458c69c9aa1ff751fa3998573
3,632,449
def get_task(name, context=None, exception_if_not_exists=True): """ Returns item for specified task :param name: Name of the task :param context: Lambda context :param exception_if_not_exists: true if an exception should be raised if the item does not exist :return: Task item, raises exception i...
9eb3007c230b75543c5227a44d282ed2ca6b3d9e
3,632,450
def GetResourceReference(project, organization): """Get the resource reference of a project or organization. Args: project: A project name string. organization: An organization id string. Returns: The resource reference of the given project or organization. """ if project: return resources.R...
fd986df9ced20a6b8edbd910d7268806841d2139
3,632,451
def pauli_block_y(M, norb): """ y compoenent of a matrix, see pauli_block """ ret = zeros_like(M) tmp = (M[:norb, norb:] * 1j + M[norb:, :norb] * (-1j)) / 2 ret[:norb, norb:] = tmp * (-1j) ret[norb:, :norb] = tmp * 1j return tmp, ret
848d70de19723ee22f2adc750c7dd9ec8c47d784
3,632,452
def permission_required_raise(perm, login_url=None, raise_exception=True): """ A permission_required decorator that raises by default. """ return permission_required(perm, login_url=login_url, raise_exception=raise_exception)
7a26f7ac1e858cfcba6961856ecf428d0de03982
3,632,453
def get_dips_value_around_300(l_cusp): """ 300°付近の凹みの L* 値および、それを指す Hue の Index を計算する。 """ dips_300 = np.min(l_cusp[DIPS_300_SAMPLE_ST:DIPS_300_SAMPLE_ED]) dips_300_idx = np.argmin(l_cusp[DIPS_300_SAMPLE_ST:DIPS_300_SAMPLE_ED]) dips_300_idx += DIPS_300_SAMPLE_ST return dips_300, dips_300_idx
6db8f0ee9d92c14c50bee096830a9fa0cadc6a94
3,632,455
def get_filtered_enviro_df(lat_filter, long_filter): """ This function takes the latitude and longitude filters and queries the database to obtain City of Chicago Environmental complaint and enforcement information that fits within those filters. A pandas dataframe of filtered database information ...
b09c2cced6f17c8b4814982eb68f2af1589ad97a
3,632,456
def is_valid_time_stamp_normal_response(response): """ Returns true if a time_stamp_normal response is valid. str -> bool """ try: respones_to_datetime(response, constants.DATETIME_FORMATE_NORMAL) return True except ValueError: return False
37e521ab18f8a21f311b07a96082ea65d2c3a57e
3,632,457
def find_best_capacity_value(desired_capacity, data_file='data/capacities.csv'): """Return the closest capacity to the desired one from the possible capacity combinations. Parameters ---------- desired_capacity: float The desired capacity value needed for the circuit. data_file: str Re...
19fd7cca9b45b088c2dafa97f75d37c8bae570d8
3,632,459
def _qt(add_row, secondary_dict_ptr, cols, key): """ This sub-function is called by view_utils.qt to add keys to the secondary_dict and is NOT meant to be called directly. """ if cols[key]: if cols[key] in secondary_dict_ptr: return add_row, secondary_dict_ptr[cols[key]] ...
ce1cec842822077cbfbd908ff92b1552626cd5f2
3,632,460
from datetime import datetime def conv_to_schedule(src: datetime) -> str: """Convert given datetime to schedule date string.""" return datetime.strftime(src, FMT_STD)
571fd18bff08e4e9be9929a75b23c5b023122400
3,632,461
def create(title): """Create a Tk root title - a title for the application """ assert isinstance(title, str) root = tk.Tk() root.title = title rx.concurrency.TkinterScheduler(root) return root
aaa710b6429c0abafe40e7c7ea51f886f15624c4
3,632,462
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Homekit lock.""" hkid = config_entry.data["AccessoryPairingID"] conn = hass.data[KNOWN_DEVICES][hkid] @callback def async_add_service(service): if service.short_type != ServicesTypes.LOCK_MECHANISM: r...
1ebfa72ffc700a873cff642cbd0a92b2a64cdc35
3,632,463
from typing import List from typing import Tuple import torch def bounding_boxes_to_tensor(bboxes: List[dict], image_size: Tuple[int, int], cell_size: Tuple[int, int], classes: List[str], device: torch.device) -> Tuple[torch.Tensor]: """ Converts a lis...
1530748ddc02527edea938542b1e60dcfac5a36b
3,632,464
def compartment_size_uncommon_keys(base): """ Provide a model with different amounts metabolites for each compartment. """ base.add_metabolites( [cobra.Metabolite(i, compartment='ml') for i in "ABCD"]) base.add_metabolites( [cobra.Metabolite(i, compartment='om') for i in "EFG"]) ...
d00f1da728b5f8cf9399a8e8810d90cd919c45c6
3,632,465
def steady_state_step(population: list, reproduction_pipeline: list, insert, probes = (), evaluation_op = ops.evaluate): """An operator that performs steady-state evolution when placed in an (otherwise generational) pipeline. This is a metaheuristic component that can be parameterized to define many kinds ...
e6e03e4b0d70ba4b3a10124e4170988b0774e9f1
3,632,466
def get_gym_environs(): """ List all valid OpenAI ``gym`` environment ids. """ return [e.id for e in gym.envs.registry.all()]
899013b5621e63b44bd0600bd037da389fcdb0ff
3,632,467
import time def single_classic_cv_evaluation( dx_train, dy_train, name, model, sample_weight, scoring, outer_cv, average_scores_across_outer_folds, scores_of_best_model, results, names, random_state): """Non nested cross validation of single model.""" if (isinstance(scoring, list) or i...
530fd65ed867a4f43a1fcc688970c6a6b1e6ffc7
3,632,468
from nnabla import logger def get_extension_context(ext_name, **kw): """Get the context of the specified extension. All extension's module must provide `context(**kw)` function. Args: ext_name (str) : Module path relative to `nnabla_ext`. kw (dict) : Additional keyword arguments for cont...
c5f3bf4c6f4053207009e3412c23133df28d6b61
3,632,469
def resolve_byprop(prop, value, minimum=1, timeout=FOREVER): """Resolve all streams with a specific value for a given property. If the goal is to resolve a specific stream, this method is preferred over resolving all streams and then selecting the desired one. Keyword arguments: prop -- The St...
a3c81185ad3d972e997399d41480e3f814945c52
3,632,470
import math def create_plot(model_filenames, ncols=3, projection=None, nplots_increment=0): """Create base figure for multipanel plot. Creates matplotlib figure and set of axis that corespond to the number of models that should be plotted. Parameters ---------- model_filenames: OrderedDict ...
11a5e36b641946c5994919845818dcecef98eadf
3,632,471
import time def get_sample_records(n): """get sample records for testing""" tsk, target = get_sample_task() inps, ress = [], [] for i in range(n): inps.append(MeasureInput(target, tsk, tsk.config_space.get(i))) ress.append(MeasureResult((i + 1,), 0, i, time.time())) return list(zi...
136398926d2638aa0542e76e1e6757484aaf82d1
3,632,472
def build_get_boolean_tfft_request( **kwargs # type: Any ): # type: (...) -> HttpRequest """Get boolean array value [true, false, false, true]. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code flow. :return: Returns an :class:`~azu...
0711739e4a97a7356f5f69a12e27f940e03e79ff
3,632,473
def grøn(tekst: str): """ Farv en tekst der udskrives via Click grøn. """ return farvelæg(tekst, "green")
b85629c384c8918bca38093af99a7840cce0aec2
3,632,474
def update(dbs, user, role_id=None, org_id=None, create_user=None): """ 更新用户信息 :param dbs: :param user: :param role_id: :param org_id: :param create_user: :return: """ try: with transaction.manager: if org_id and org_id != '' and org_id != 0: d...
a345e9edfd0e7174c7ce8e881d3b3699a9222610
3,632,476
def analogy_making_model(inputs, params, is_training, reuse, output_length=None): """Factory function to retrieve analogy-making model.""" latent_encoder = _get_network(Z_ENC_FN) latent_decoder = _get_network(Z_DEC_FN) outputs = analogy_seq_encoding_model(inputs, params, is_training, reuse) with tf.variable...
3c83c27ebefcc9d3b080441be5a45c52193a40eb
3,632,477
import torch def test_model(dataloader, model, gpu=False): """Tests model performance on a data from dataloader and prints accuracy. Args: dataloader (DataLoader) model (torchvision model) gpu (bool): Use GPU if True, otherwise CPU Returns: test_acc (float): model predict...
f5e1f63b8e0a3e2ee94d579f552807af103e2c1a
3,632,478
import io import struct def decrypt_chunk(chunk, password=None): """Decrypts the given encrypted chunk with the given password and returns the decrypted chunk. If password is None then saq.ENCRYPTION_PASSWORD is used instead. password must be a byte string 32 bytes in length.""" if password is ...
f6578fd445c44a2fd4aecc3009278ddd2a45add0
3,632,479
import time from datetime import datetime def epochFromNice(timeToConvert=None): """ Get the epoch time from the passed in string of the format: YYYY-mm-dd_HH-MM-SS.UUUUUU returns time.time() if timeToConvert is not specified """ if timeToConvert is None: retTime = time.time() else: year...
db6378dd2d47cc17377507474d9726a2f6de22b0
3,632,480
def prepare_tensor_SVD(tensor, direction, D=None, thresh=1E-32, normalize=False): """ prepares and truncates an mps tensor using svd Parameters: --------------------- tensor: np.ndarray of shape(D1,D2,d) an mps tensor direction: int if >0 returns left orthogonal decomp...
ad71c7f2b16624bc9f24e060376a9359c8585c07
3,632,481
from datetime import datetime def calc_easter(year): """ Returns Easter as a date object. Because Easter is a floating mess year - the year to calc easter for """ a = year % 19 b = year // 100 c = year % 100 d = (19 * a + b - b // 4 - ((b - (b + 8) // 25 + 1) // 3) + 15) % 30 ...
c02c2a45f55a8f80273759bbf9c06bb2234b0b8a
3,632,482
def MACDFIX(ds, count, signalperiod=-2**31): """Moving Average Convergence/Divergence Fix 12/26""" ret = call_talib_with_ds(ds, count, talib.MACDFIX, signalperiod) if ret == None: ret = (None, None, None) return ret
8b440e666d0ac1c669e26da9974136fdd18f5e6e
3,632,483
def create_dataset(form_data, params=None, use_doi=False): """ Create dataset in Metax. Arguments: form_data {object} -- Object with the dataset data that has been validated and converted to comply with the Metax schema. params {dict} -- Dictionary of key-value pairs of query parameters. ...
b288c021df3cf37467ea304c2105eceb0fc5f2be
3,632,484
def blrPredict(W, data): """ blrObjFunction predicts the label of data given the data and parameter W of Logistic Regression Input: W: the matrix of weight of size (D + 1) x 10. Each column is the weight vector of a Logistic Regression classifier. X: the data matrix of siz...
86374a43e6c7cbe69a6789f532ea3be3bf3238f5
3,632,485
def get_pair(expr, index): """Get the field of an expression using python syntax Arguments: - `expr`: an expression - `index`: an integer equal to 0 or 1 """ if index == 0: return Fst(expr) elif index == 1: return Snd(expr) else: raise Exception("Index applie...
5b25163562fb8399d2e948dd8fc9d47aa6467b07
3,632,488
import functools def get_standardized_layers(hparams, dp=None, ps_devices=None): """Get the common attention and feed-forward layers. The returned layer functions will have the following signature: y, extra_loss = fct(x) extra_loss is set to 0.0 if the layer doesn't have extra loss. If dp is provided, ...
99972e4106928ff4c71e0f52c159a74650310c74
3,632,489
def row_contains_data(fieldnames, row): """Returns True if the value of atleast on of the fields is truthy""" for field in fieldnames: if row.get(field): return True return False
7575d1280186c582a652ab37deb4a93e667b51b2
3,632,490
def create_model(name, batch_size, learning_rate = 0.0001, wd = 0.00001, concat = False, l2_loss = False, penalty = False, coef = 0.4, verbosity = 0): """ Create a model from model.py with the given configuration Args: name : name of the model (used to create a specific folder to save/load para...
63b4755e20fc877d9231427ed2cf118efbe37bb0
3,632,491
def fs(path:str, mode:Mode='rb'): """Opens file locally or via s3 depending on path string.""" s3 = s3fs.S3FileSystem() return partial( {True: s3.open, False: open}[is_s3_path(path)], mode=mode )(path)
18ffc654e66bdd2c9315d5104fa145a195ee2ce3
3,632,492
import six def _check_stop_list(stop): """ Check stop words list ref: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L87-L95 """ if stop == "thai": return THAI_STOP_WORDS elif isinstance(stop, six.string_types): raise ValueError("not...
8c47875f42fdfcb1f0b7c7c18b8363783f1ebcbb
3,632,494
from typing import Callable from typing import Any def protect_with_lock() -> Callable: """ This is a decorator for protecting a call of an object with a lock The objects must adhere to the interface of having: - A mapping of ids to query_lock objects Objects adhering to this interface(LockableQu...
60901e775f1a6a8d3408000f3517f1c3ddedd199
3,632,495
from datetime import datetime def _handle_dates(): """Collect and return data information.""" currentdate = datetime.date.today() year = currentdate.year month = currentdate.month print(f"[INFO] Current year / month: {year:04d} / {month:02d}") return currentdate
54735562fe0366f286eeac33f897a98a8d34374a
3,632,496
def add_to_five(number): """Add to the 5 by any number. :param number: """ gifs = FrozenGif() acceptable = (int, float) type_number = type(number) if type_number in acceptable: # get answer answer = 5 + number response = int(input("Ente...
0387af4a7d8587865c3c7e38eeab1af5a00423a2
3,632,497
def test_url(url, size=17): """Test whether the given URL is accessible.""" try: with gopen(url) as stream: data = stream.read(size) if len(data) == size: return True return False except Exception as e: print(e) return False
13023fc5fd346572b3c31e4f4dd491e285e33b6b
3,632,499
import gdata.gauth def credentials_to_token(credentials): """ Transforms an Oauth2 credentials object into an OAuth2Token object to be used with the legacy gdata API """ credentials.refresh(httplib2.Http()) token = gdata.gauth.OAuth2Token( client_id=credentials.client_id, clie...
549b1041c275c542d96e1d048832f71969d727d7
3,632,500
def solve2x2(lhs, rhs): """Solve a square 2 x 2 system via LU factorization. This is meant to be a stand-in for LAPACK's ``dgesv``, which just wraps two calls to ``dgetrf`` and ``dgetrs``. We wrap for two reasons: * We seek to avoid exceptions as part of the control flow (which is what :func:`nu...
2f773a0e452ce1401dc5fb5c17256b662614c366
3,632,501
def fetch_global_notifications(count=0) -> dict: """ Always returns notifications in user view. """ cfg = get_config() if count == 0: count = cfg.default_max_notes global_feed = get_global_feed() global_notes = global_feed.get_notifications(count=count, user_view=True) return glo...
661232b2477eabd0c5a3b706b8253e4956e1aabd
3,632,502
def getClusterPositionsRedshift(hd_clu, cluster_params, redshift_limit): """ Function to get the positions and redshifts of the clusters that pass the required criterion @hd_clu :: list of cluster headers (each header ahs info on 1000 clusters alone) @cluster_params :: contains halo_mass_500c and centra...
4b30bb44a82daa3f2f113c14b7f044ac22d20c6c
3,632,503
def lark_to_field_definition_node(tree: "Tree") -> "FieldDefinitionNode": """ Creates and returns a FieldDefinitionNode instance extracted from the parsing of the tree instance. :param tree: the Tree to parse in order to extract the proper node :type tree: Tree :return: a FieldDefinitionNode ins...
f00d0ed11d3ff61d8017cecbb0226b88accb9854
3,632,504
def variant_wraps(vfunc, wrapped_attributes=VARIANT_WRAPPED_ATTRIBUTES): """Update the variant function wrapper a la ``functools.wraps``.""" f = vfunc.__main_form__ class SentinelObject: """A unique sentinel that is not None.""" sentinel = SentinelObject() for attr in wrapped_attributes: ...
4143a0e2cb5676c80314096575c9d33fbdcdb788
3,632,505
from typing import Iterable def gradient_activity(activity, periods=1, append=True, columns=None): """Compute the gradient for all given columns. Read more in the :ref:`User Guide <gradient>`. Parameters ---------- activity : DataFrame The activity to use to compute the gradient. pe...
fd05c9323d406b9f0c5089f7715b8ec55ceeaae2
3,632,506
def password_validators_help_texts(password_validators=None): """ Return a list of all help texts of all configured validators. """ help_texts = [] if password_validators is None: password_validators = get_default_password_validators() for validator in password_validators: help_t...
3df7b1a669ee7ef01b1e28645d3d7fca5816cf8d
3,632,507
import torch def spherical_schwarzchild_metric(x,M=1): """ Computes the schwarzchild metric in cartesian like coordinates""" bs,d = x.shape t,r,theta,phi = x.T rs = 2*M a = (1-rs/r) gdiag = torch.stack([-a,1/a,r**2,r**2*theta.sin()**2],dim=-1) g = torch.diag_embed(gdiag) print(g.shape)...
4e65d520a88f4b9212bab43c7ebc4dfc30245bd3
3,632,508
def _get_pathless_grib_file_names( init_time_unix_sec, model_name, grid_id=None, lead_time_hours=None): """Returns possible pathless file names for the given model/grid. :param init_time_unix_sec: Model-initialization time. :param model_name: See doc for `nwp_model_utils.check_grid_name`. :para...
6435348fa760b5bd36e8c54df192b024210dcf4f
3,632,509
def get_picard_mrkdup(config): """ input: sample config file output from BALSAMIC output: mrkdup or rmdup strings """ picard_str = "mrkdup" if "picard_rmdup" in config["QC"]: if config["QC"]["picard_rmdup"] == True: picard_str = "rmdup" return picard_str
87e24c0bf43f9ac854a1588b80731ed445b6dfa5
3,632,510
import random def ChoiceColor(): """ 模板中随机选择bootstrap内置颜色 """ color = ["default", "primary", "success", "info", "warning", "danger"] return random.choice(color)
15779e8039c6b389301edef3e6d954dbe2283d54
3,632,511
import platform def filter_command_line(line): """Returns and updates the command line starting with the flag""" line_flag = line.strip().split(":")[0].strip() new_line = line.strip()[len(line_flag) + 1:].strip().lstrip(":").strip() if line_flag == EXEC_FLAG: return new_line elif line_flag...
ff5560b1ba23544902e0904bc08030b2d24a40e4
3,632,512
def load_image(path: str): """ Return a loaded image from a given path. :param path: (str) relative path of the iamge. :return: PIL image. """ image = Image.open(path) return image
8c9d96d5cea2fdac67ba937b7d01bc01a860d1d7
3,632,513
from operator import concat def mergeSeries(sdata, resetIdx=False): """ Merge Series Inputs: > sdata: Either a list of dictionary of Series data > resetIdx (False by default): should we reset the indices? Output: > The merged Series """ if isinstance(sdata, list):...
dc0382581d3e14dc46abe9c5b40d685f3d80ec20
3,632,514
def ranking_overview(request): """ Show history of rankings for top N teams in current ranking """ # Check which rounds are complete rnd_complete = get_completed_rounds() # Calculate ranking after each of these rounds increment_rnds = [] ranking_matrix = [] round_names = [] ...
c68505833f72d529d4ea1617d4d8455120c5321d
3,632,515
def release_lock(lock_name, identifier): """ :param lock_name: 锁名称 :param identifier: uid :return: True or False """ lock = "string:lock:" + lock_name pip = redis_client.pipeline(True) while True: try: pip.watch(lock) lock_value = redis_client.get(lock) ...
8df9f174d11a36ffad9ed2310c2293630669dc4c
3,632,516
def add_user(): """ Add a user""" payload = request.json for required_key in users_schema: if required_key not in payload.keys(): return jsonify({"message": f"Missing {required_key} parameter"}), 400 user = db.users.find_one({"email": payload["email"]}) if user is not None: ...
1c674dbb70caa0ae43819391c97694d3dd82a235
3,632,517
import hashlib def __get_str_md5(string): """ 一个字符串的MD5值 返回一个字符串的MD5值 """ m0 = hashlib.md5() m0.update(string.encode('utf-8')) result = m0.hexdigest() return result
1d55cd42dc16a4bf674907c9fb352f3b2a100d6c
3,632,518
from typing import List def create_optimizers() -> List[OptimizationProcedure]: """Creates a list of all optimization procedures""" optimizers: List[OptimizationProcedure] = [] ordering_rules = TaskOrderingRule.__subclasses__() for rule in ordering_rules: optimizers.append(StationOriented...
f5cade59c03b017435c18a97423eb059418a6e20
3,632,519
import urllib def command_get_file_list(ip_addr, directory): """command.cgi?op=100: Get list of files in a directory. Not recursive. :raise FlashAirBadResponse: When API returns unexpected/malformed data. :raise FlashAirDirNotFoundError: When the queried directory does not exist on the card. :raise F...
40f8c9b84113be84358959f246a868424d382947
3,632,520
def axml_content(d): """ OwcContent dict to Atom XML :param d: :return: """ # <owc:content type="image/tiff" href=".." if is_empty(d): return None else: try: content_elem = etree.Element(ns_elem("owc", "content"), nsmap=ns) mimetype = extract_p(...
c35c266d4ae7c5026958cbb271598f76369ecc6f
3,632,521
def average_water_consumed(wn): """ Compute average water consumed at each node, qbar, computed as follows: .. math:: qbar=\dfrac{\sum_{k=1}^{K}\sum_{t=1}^{lcm_n}qbase_n m_n(k,t mod (L(k)))}{lcm_n} where :math:`K` is the number of demand patterns at node :math:`n`, :math:`L(k)` is the number o...
bf88a45035b993d00fb31ff7151e48a0a1d59c83
3,632,522
def _shuffle(arr1, arr2): """ Shuffles arr1 and arr2 in the same order """ random_idxs = np.arange(len(arr1)) np.random.shuffle(random_idxs) return arr1[random_idxs], arr2[random_idxs]
785ecd0b9e92d5695cd2466fec6649d463f55feb
3,632,523
def make_pipeline(tfidf_vectorizer, model): """ Creates sklearn NLP pipeline :param vectorizer: Vectorizer object :param model: Model object :return: Pipeline object """ tfidf_vectorizer = tfidf_vectorizer model = model pipeline = Pipeline([("tfidf", tfidf_vectorizer), ...
423b59d2635bf34169091c7456e71eca2dbdf5d6
3,632,525
def pnf_peeling_mechanism(item_counts, k, epsilon): """Computes epsilon-DP top-k counts by the permute-and-flip peeling mechanism. The peeling mechanism (https://arxiv.org/pdf/1905.04273.pdf) adaptively uses the counts as a utility function for the exponential mechanism. Once an item is selected, the item is ...
2c2fe9e59addc4905211ca70efd1f88bdeb5a976
3,632,526
from datetime import datetime def format_date(timestamp): """Reusable timestamp -> date.""" return datetime.date.fromtimestamp(timestamp).isoformat()
0f735dc18700332238ab4441677c786f9accc069
3,632,527
import time def train(model, optimizer, loader, epoch): """ Train the models on the dataset. """ # running statistics batch_time = AverageMeter("time", ":.2f") data_time = AverageMeter("data time", ":.2f") # training statistics top1 = AverageMeter("top1", ":.3f") top5 = AverageMet...
3d65714a50f1842c32c85fe0cd3c02d7069a88f9
3,632,529
import functools def ResidualBlock(name, input_dim, output_dim, filter_size, inputs, resample=None, he_init=True): """ resample: None, 'down', or 'up' """ if resample == 'down': conv_shortcut = functools.partial(lib.ops.conv2d.Conv2D, stride=2) conv_1 = functools.partial( l...
1b78b86ea42dd225f5a2bde6bcb6ed47b055ec00
3,632,530
def run_uGLAD_direct( Xb, trueTheta=None, eval_offset=0.1, EPOCHS=250, lr=0.002, INIT_DIAG=0, L=15, VERBOSE=True ): """Running the uGLAD algorithm in direct mode Args: Xb (np.array 1xMxD): The input sample matrix trueTheta (np.array 1xDxD): The corresp...
5b362abfec18a217c768bbe45bce3059ece8be22
3,632,531
def twitter_api(): """Returns an authenticated tweepy.API instance. Returns None on failure. """ try: auth = tweepy.OAuthHandler(TWITTER_API_KEY, TWITTER_API_KEY_SECRET) auth.set_access_token(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET) ap...
5f0e748740025d4065c6317fdf03eead25e7ba95
3,632,532
def as_general_categories(cats, name="cats"): """Return a tuple of Unicode categories in a normalised order. This function expands one-letter designations of a major class to include all subclasses: >>> as_general_categories(['N']) ('Nd', 'Nl', 'No') See section 4.5 of the Unicode standard fo...
391185d75dce63df7deb724f8dea035389122b94
3,632,533
from pathlib import Path import glob def upload_directory( directory: str = './', upsert=False, ignore_duplicate_error=False, recursive=False, pattern='*'): """ Upload files in a directory to the database. :param directory: [Optional] The root directory to upload. ...
d156c44f511182958172ba30bfb5422bb5da8dcd
3,632,534
def tExtract(rft, T_INDEX): """T_INDEX is either of T_WL, T_SPEC, T_COM """ tdat = [dat[T_INDEX] for dat in rft[RFT_T] if (dat[T_WL] >= rft[RFT_R][R_WL] and dat[T_WL] <= rft[RFT_R][R_WH])] return tdat
c1cdf75b377851316a5da050b8f248f14cfd34e5
3,632,535
from typing import Union from pathlib import Path from typing import Optional def open_txt(path: Union[str, Path], cf_table: Optional[dict] = cmor) -> xr.Dataset: """Extract daily HQ meteorological data and convert to xr.DataArray with CF-Convention attributes.""" meta, data = extract_daily(path) return t...
3a77ed5a501c1d455299504e4dd36e55cea580e9
3,632,536
def dc_coordinates(): """Return coordinates for a DC-wide map""" dc_longitude = -77.016243706276569 dc_latitude = 38.894858329321485 dc_zoom_level = 10.3 return dc_longitude, dc_latitude, dc_zoom_level
c07812ad0a486f549c63b81787a9d312d3276c32
3,632,537
def request_id_to_key(request_id): """Converts a request id into a TaskRequest key. Note that this function does NOT accept a task id. This functions is primarily meant for limiting queries to a task creation range. """ return ndb.Key(TaskRequest, request_id ^ task_pack.TASK_REQUEST_KEY_ID_MASK)
a5c3ef9939390d43264ba397e4c123af44758471
3,632,539
from typing import Optional def get_web_app_premier_add_on_slot(name: Optional[str] = None, premier_add_on_name: Optional[str] = None, resource_group_name: Optional[str] = None, slot: Optional[str] = None, ...
764101a407305b1f6e03fe8b1ccb17cb2ecbd86f
3,632,540