content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def Landsat_Reflect(Bands,input_folder,Name_Landsat_Image,output_folder,shape_lsc,ClipLandsat,Lmax,Lmin,ESUN_L5,ESUN_L7,ESUN_L8,cos_zn,dr,Landsat_nr, proyDEM_fileName): """ This function calculates and returns the reflectance and spectral radiation from the landsat image. """ Spec_Rad ...
4c6e49e22ac2b4b12dece71c3c3e73afdc72d0ca
3,639,300
def second(lst): """Same as first(nxt(lst)). """ return first(nxt(lst))
aa49e089a06a4b3e7d781966d8b4f98b7fe15841
3,639,301
def gaussian_noise(height, width): """ Create a background with Gaussian noise (to mimic paper) """ # We create an all white image image = np.ones((height, width)) * 255 # We add gaussian noise cv2.randn(image, 235, 10) return Image.fromarray(image).convert("RGBA")
6243fde57b3e7415edc2024eebbe10f059b93a55
3,639,302
def draw_box(image, box, color): """Draw 3-pixel width bounding boxes on the given image array. color: list of 3 int values for RGB. """ y1, x1, y2, x2 = box image[y1:y1 + 1, x1:x2] = color image[y2:y2 + 1, x1:(x2+1)] = color image[y1:y2, x1:x1 + 1] = color image[y1:y2, x2:x2 + 1] = colo...
4d1e713c6cb6a3297b4f7d8ab9682205947770da
3,639,303
def get_statuses_one_page(weibo_client, max_id=None): """获取一页发布的微博 """ if max_id: statuses = weibo_client.statuses.user_timeline.get(max_id=max_id) else: statuses = weibo_client.statuses.user_timeline.get() return statuses
4a214489aa5696c9683c9cfa96d79ee169135eb5
3,639,304
def do_nothing(ax): """Do not add any watermark.""" return ax
6fbe32dc45ca1a945e1c45bf0319770c4d683397
3,639,305
def exec_lm_pipe(taskstr): """ Input: taskstr contains LM calls separated by ; Used for execute config callback parameters (IRQs and BootHook) """ try: # Handle config default empty value (do nothing) if taskstr.startswith('n/a'): return True # Execute individual ...
8854b5de0f408caf9292aecbcfa261744166e744
3,639,306
def term_size(): """Print out a sequence of ANSI escape code which will report back the size of the window. """ # ESC 7 - Save cursor position # ESC 8 - Restore cursor position # ESC [r - Enable scrolling for entire display # ESC [row;colH - Move to cursor position ...
bc0b09163b48f821315f52c52b0a58b6b5fb977a
3,639,307
def get_dashboard(request, project_id): """ Load Project Dashboard to display Latest Cost Estimate and List of Changes """ project = get_object_or_404(Project, id=project_id) # required to determine permission of user, # if not a project user then project owner try: project_user = P...
36257741b2ef220d35e4593bd080a82b4cc743a0
3,639,308
def _scan_real_end_loop(bytecode, setuploop_inst): """Find the end of loop. Return the instruction offset. """ start = setuploop_inst.next end = start + setuploop_inst.arg offset = start depth = 0 while offset < end: inst = bytecode[offset] depth += inst.block_effect ...
9cff8ab77563a871b86cdbb14236603ec58e04b6
3,639,309
def six_node_range_5_to_0_bst(): """Six nodes covering range five to zero.""" b = BST([5, 4, 3, 2, 1, 0]) return b
1afe6c613b03def6dc9d8aed41624e40180e5ae5
3,639,310
def IndividualsInAlphabeticOrder(filename): """Checks if the names are in alphabetic order""" with open(filename, 'r') as f: lines = f.readlines() individual_header = '# Individuals:\n' if individual_header in lines: individual_authors = lines[lines.index(individual_header) + 1:] sorted_auth...
4753bbf41498373695f921555c8f01183dbb58dc
3,639,311
import mxnet from mxnet.gluon.data.vision import transforms from PIL import Image def preprocess_img_imagenet(img_path): """Preprocessing required for ImageNet classification. Reference: https://github.com/onnx/models/tree/master/vision/classification/vgg """ img = Image.open(img_path) img ...
f181e3376f26ee14c6314a8a730e796eefb09e2e
3,639,312
def create_lambertian(color): """ create a lambertion material """ material = bpy.data.materials.new(name="Lambertian") material.use_nodes = True nodes = material.node_tree.nodes # remove principled material.node_tree.nodes.remove( material.node_tree.nodes.get('Principled BSDF')...
e291817853ec26d6767d8fd496ee5ced15ff87f2
3,639,313
def submission_view(request, locker_id, submission_id): """Displays an individual submission""" submission = get_object_or_404(Submission, pk=submission_id) newer = submission.newer() newest = Submission.objects.newest(submission.locker) if not newest: newest = submission oldest = Submis...
f473c7ad2c59dfd27a96fa4478f6b9652e740296
3,639,314
from pathlib import Path def add_filename_suffix(file_path: str, suffix: str) -> str: """ Append a suffix at the filename (before the extension). Args: path: pathlib.Path The actual path object we would like to add a suffix suffix: The suffix to add Returns: path with suffix appended a...
546bb95f694ee5d5cb26873428fcac8453df6a54
3,639,315
def list_dropdownTS(dic_df): """ input a dictionary containing what variables to use, and how to clean the variables It outputs a list with the possible pair solutions. This function will populate a dropdown menu in the eventHandler function """ l_choice = [] for key_cat, value_cat in d...
fcd0474fa6941438cb39c63aa7605f1b776fd538
3,639,316
import itertools import random def get_voice_combinations(**kwargs): """ Gets k possible combinations of voices from a list of voice indexes. If k is None, it will return all possible combinations. The combinations are of a minimum size min_n_voices_to_remove and a max size max_n_voices_to_remove. Whe...
d3addbfe5023b5ee6e25f190c53b469593bb9ff4
3,639,317
def data(request): """This is a the main entry point to the Data tab.""" context = cache.get("data_tab_context") if context is None: context = data_context(request) cache.set("data_tab_context", context, 29) return render(request, "rundb/data/data.html", context)
2763617afc7d865acaf3f0dcbf9190bd084ad5ae
3,639,318
def setup_root(name: str) -> DLogger: """Create the root logger.""" logger = get_logger(name) msg_format = "%(message)s" level_style = { "critical": {"color": "magenta", "bright": True, "bold": True}, "debug": {"color": "green", "bright": True, "bold": True}, "error": {"color":...
9cad79c254fcb8f075d549c457d7e09dacc9bb33
3,639,319
import typing import pathlib import pickle def from_pickle( filepath: typing.Union[str, pathlib.Path, typing.IO[bytes]] ) -> typing.Union[Categorization, HierarchicalCategorization]: """De-serialize Categorization or HierarchicalCategorization from a file written by to_pickle. Note that this uses the...
e268f8c1467965bbba47c65ebba5f021171fc6ce
3,639,320
def recostruct(encoded, weights, bias): """ Reconstructor : Encoded -> Original Not Functional """ weights.reverse() for i,item in enumerate(weights): encoded = encoded @ item.eval() + bias[i].eval() return encoded
e17aeb6a819a6eec745c5dd811460049fa4a92cd
3,639,321
import math def get_file_dataset_from_trixel_id(CatName,index,NfilesinHDF,Verbose=True):#get_file_var_from_htmid in Eran's library """Description: given a catalog basename and the index of a trixel and the number of trixels in an HDF5 file, create the trixel dataset name Input :- ...
b9d0482780ae2a191175f1549513f46c047bb1cf
3,639,322
def calc_element_column(NH, fmineral, atom, mineral, d2g=0.009): """ Calculate the column density of an element for a particular NH value, assuming a dust-to-gas ratio (d2g) and the fraction of dust in that particular mineral species (fmineral) """ dust_mass = NH * mp * d2g * fmineral # g cm^{-...
d1e24602e6d329132d59f300543f306502867fc1
3,639,323
def output_dot(sieve, column_labels=None, max_edges=None, filename='structure.dot'): """ A network representation of the structure in Graphviz format. Units in the produced file are in bits. Weight is the mutual information and tc is the total correlation. """ print """Compile by installing graphviz...
aa63e5ffb0bd1544f29391821db9ac49e690e3fe
3,639,324
def projectSimplex_vec(v): """ project vector v onto the probability simplex Parameter --------- v: shape(nVars,) input vector Returns ------- w: shape(nVars,) projection of v onto the probability simplex """ nVars = v.shape[0] mu = np.sort(v,kind='quicksort')[:...
ace378ed84c61e05e04fdad23e3d97127e63df3a
3,639,325
from typing import Collection from typing import List from typing import Sized def render_list(something: Collection, threshold: int, tab: str) -> List[str]: """ Разложить список или что то подобное """ i = 1 sub_storage = [] order = '{:0' + str(len(str(len(something)))) + 'd}' for eleme...
a7eb47df956fc4404bae6e29e75b280cd2b70cba
3,639,326
from typing import Optional from typing import List from typing import Tuple def combine_result( intent_metrics: IntentMetrics, entity_metrics: EntityMetrics, response_selection_metrics: ResponseSelectionMetrics, interpreter: Interpreter, data: TrainingData, intent_results: Optional[List[Inten...
86942bbb30fe86fcd8e3453e7ac661b97832ec1a
3,639,327
import jobtracker def get_fns_for_jobid(jobid): """Given a job ID number, return a list of that job's data files. Input: jobid: The ID number from the job-tracker DB to get files for. Output: fns: A list of data files associated with the job ID. """ query...
ab867ec7b86981bfd06caf219b77fbb9410277ad
3,639,328
def linear_schedule(initial_value: float): """ Linear learning rate schedule. :param initial_value: Initial learning rate. :return: schedule that computes current learning rate depending on remaining progress """ def func(progress_remaining: float) -> float: """ Progress w...
afb0c9f050081f7e84728051535a899d9ece43f3
3,639,329
def download(os_list, software_list, dst): """ 按软件列表下载其他部分 """ if os_list is None: os_list = [] arch = get_arch(os_list) LOG.info('software arch is {0}'.format(arch)) results = {'ok': [], 'failed': []} no_mindspore_list = [software for software in software_list if "MindSpore" no...
9def81d5c1f127cab08add62a16df35c2a9dbc80
3,639,330
import hashlib def get_hash_bin(shard, salt=b"", size=0, offset=0): """Get the hash of the shard. Args: shard: A file like object representing the shard. salt: Optional salt to add as a prefix before hashing. Returns: Hex digetst of ripemd160(sha256(salt + shard)). """ shard.see...
94c399d41b56598e4ecac3f0c2d917a226e9e9db
3,639,331
def boltzmann_statistic( properties: ArrayLike1D, energies: ArrayLike1D, temperature: float = 298.15, statistic: str = "avg", ) -> float: """Compute Boltzmann statistic. Args: properties: Conformer properties energies: Conformer energies (a.u.) temperature: Temperature (...
5c5ea2d9ff43e9e068856d73f1e6bdc1f53c42b0
3,639,332
def _check_n_pca_components(ica, _n_pca_comp, verbose=None): """Aux function""" if isinstance(_n_pca_comp, float): _n_pca_comp = ((ica.pca_explained_variance_ / ica.pca_explained_variance_.sum()).cumsum() <= _n_pca_comp).sum() logger.info('Selected %...
1295de84f6054cac3072e2ba861c291cf71fdb72
3,639,333
def parse(text): """ This is what amounts to a simple lisp parser for turning the server's returned messages into an intermediate format that's easier to deal with than the raw (often poorly formatted) text. This parses generally, taking any lisp-like string and turning it into a list of nested...
a608d50a7425c6bd6420433aff673cddd8aa612f
3,639,334
def model_fn(): """ Renvoie un modèle Inception3 avec la couche supérieure supprimée et les poids pré-entraînés sur imagenet diffusés. """ model = InceptionV3( include_top=False, # Couche softmax de classification supprimée weights='imagenet', # Poids pré-entraînés sur Imagenet # input...
3ee68e9874025d94cc1d73cf4857fecf6241e415
3,639,335
def find_correspondance_date(index, csv_file): """ The method returns the dates reported in the csv_file for the i-subject :param index: index corresponding to the subject analysed :param csv_file: csv file where all the information are listed :return date """ return csv_f...
915b9a493247f04fc1f62e614bc26b6c342783c8
3,639,336
def get_config(object_config_id): """ Returns current and previous config :param object_config_id: :type object_config_id: int :return: Current and previous config in dictionary format :rtype: dict """ fields = ('config', 'attr', 'date', 'description') try: object_config = O...
5eb31025494dbcf17890f3ed9e7165232db9e087
3,639,337
import unicodedata def normalize_to_ascii(char): """Strip a character from its accent and encode it to ASCII""" return unicodedata.normalize("NFKD", char).encode("ascii", "ignore").lower()
592e59ae10bb8f9a04dffc55bcc2a1a3cefb5e7e
3,639,338
def verify_certificate_chain(certificate, intermediates, trusted_certs, logger): """ :param certificate: cryptography.x509.Certificate :param intermediates: list of cryptography.x509.Certificate :param trusted_certs: list of cryptography.x509.Certificate Verify that the certificate is valid, accord...
5d96fa38f22a74ae270af3ab35fc90274ed487e0
3,639,339
import json def update_strip_chart_data(_n_intervals, acq_state, chart_data_json_str, samples_to_display_val, active_channels): """ A callback function to update the chart data stored in the chartData HTML div element. The chartData element is used to store the existing data ...
67902561bc4d0cec2a1ac2f8d385a2accf4c03e9
3,639,340
import uuid def genuuid(): """Generate a random UUID4 string.""" return str(uuid.uuid4())
c664a9bd45f0c00dedf196bb09a09c6cfaf0d54b
3,639,341
def watsons_f(DI1, DI2): """ calculates Watson's F statistic (equation 11.16 in Essentials text book). Parameters _________ DI1 : nested array of [Dec,Inc] pairs DI2 : nested array of [Dec,Inc] pairs Returns _______ F : Watson's F Fcrit : critical value from F table """ ...
db1f6be50657f4721aac4f800b7896afcbd71db7
3,639,342
def encode(integer_symbol, bit_count): """ Returns an updated version of the given symbol list with the given symbol encoded into binary. - `symbol_list` - the list onto which to encode the value. - `integer_symbol` - the integer value to be encoded. - `bit_count` - the number of bits from ...
fe8fb04245c053bb4387b0ac594a778df5bce22c
3,639,343
def superkick(update, context): """Superkick a member from all rooms by replying to one of their messages with the /superkick command.""" bot = context.bot user_id = update.message.from_user.id boot_id = update.message.reply_to_message.from_user.id username = update.message.reply_to_message.from_use...
2a6550bb533a51cc8ebb79ca7f5cdbd214af4a5a
3,639,344
import typing from datetime import datetime def encrypt_session( signer: typing.Type[Fernet], session_id: str, current_time: typing.Optional[typing.Union[int, datetime]] = None, ) -> str: """An utility for generating a token from the passed session id. :param signer: an instance of a fernet obje...
9d924dcbc0abdf8facb31e256c5c67ccca3850be
3,639,345
def construct_chargelst(nsingle): """ Makes list of lists containing Lin indices of the states for given charge. Parameters ---------- nsingle : int Number of single particle states. Returns ------- chargelst : list of lists chargelst[charge] gives a list of state indic...
e94044566d0acc7106d34d142ed3579226706a65
3,639,346
import json def parse(json_string): """Constructs the Protocol from the JSON text.""" try: json_data = json.loads(json_string) except: raise ProtocolParseException('Error parsing JSON: %s' % json_string) # construct the Avro Protocol object return make_avpr_object(json_data)
f95854e8c0b8e49ec71e03ee8487f88f4687ebf0
3,639,347
import os def create_script_dict(allpacks, path, file, skip_lines): """Create script dict or skips file if resources cannot be made""" allpacks["name"] = "FILL" allpacks["title"] = "FILL" allpacks["description"] = "FILL" allpacks["citation"] = "FILL" allpacks["licenses"] = [{"name": "FILL"}] ...
8bc229a3343676cf8b70c524119994e1ca49e054
3,639,348
def get_architecture(model_config: dict, feature_config: FeatureConfig, file_io): """ Return the architecture operation based on the model_config YAML specified """ architecture_key = model_config.get("architecture_key") if architecture_key == ArchitectureKey.DNN: return DNN(model_config, fe...
a7c58770a07c225ae79a03699639e19498d3a0c6
3,639,349
def get_properties_dict(serialized_file: str, sparql_file: str, repository: str, endpoint: str, endpoint_type: str, limit: int = 1000) -> ResourceDictionary: """ Return a ResourceDictionary with the list of properties in the ontology :param serialized_file: The file where the propert...
3a31bd8b23cb7a940c6386225dd39a302f3d3f3a
3,639,350
def get_duplicate_sample_ids(taxonomy_ids): """Get duplicate sample IDs from the taxonomy table. It happens that some sample IDs are associated with more than taxon. Which means that the same sample is two different species. This is a data entry error and should be removed. Conversely, having more than...
c01315d6d51ec8e62a0f510944d724a18949aeb8
3,639,351
def get_settings_text(poll): """Compile the options text for this poll.""" text = [] locale = poll.user.locale text.append(i18n.t('settings.poll_type', locale=locale, poll_type=translate_poll_type(poll.poll_type, locale))) text.append(i18n.t('settings.l...
24ef467070324dac6a8c698b791a1fe577a5d928
3,639,352
import ffmpeg from datetime import datetime import time import os import math def acd(strymobj= None, window_size=30, plot_iteration = False, every_iteration = 200, plot_timespace = True, save_timespace = False, wave_threshold = 50.0, animation = False, title = 'Average Centroid Distance', **kwargs): """ Aver...
ffd239f28b3abc801e4a0755e97133e409a058cc
3,639,353
import functools def pass_none(func): """ Wrap func so it's not called if its first param is None >>> print_text = pass_none(print) >>> print_text('text') text >>> print_text(None) """ @functools.wraps(func) def wrapper(param, *args, **kwargs): if param is not None: return func(param, *args, **kwargs) ...
2264ca5978485d8fc13377d17eb84ee522a040b9
3,639,354
def create_values_key(key): """Creates secondary key representing sparse values associated with key.""" return '_'.join([key, VALUES_SUFFIX])
e8a70bc4ef84a7a62a9d8b8d915b9ddbc0990429
3,639,355
def make_mask(variable, **flags): """ Return a mask array, based on provided flags For example: make_mask(pqa, cloud_acca=False, cloud_fmask=False, land_obs=True) OR make_mask(pqa, **GOOD_PIXEL_FLAGS) where GOOD_PIXEL_FLAGS is a dict of flag_name to True/False :param variable: ...
fcdd7247359b5127d14a906298e20a05fd63b108
3,639,356
def _normalize_block_comments(content: str) -> str: """Add // to the beginning of all lines inside a /* */ block""" comment_partitions = _partition_block_comments(content) normalized_partitions = [] for partition in comment_partitions: if isinstance(partition, Comment): comment = pa...
76c2c1d0b80cf40f647033aa8745058f1546076e
3,639,357
from datetime import datetime def check_holidays(date_start, modified_end_date, holidays): """ Here app check if holidays in dates of vacation or not. If Yes - add days to vacation, if Not - end date unchangeable """ # first end date for check loop because end date move +1 for every weekend da...
c2b8145f9963cd2679e238c2c378535eea2e08db
3,639,358
import os import warnings import logging def getHouseholdProfiles( n_persons, weather_data, weatherID, seeds=[0], ignore_weather=True, mean_load=True, cores=mp.cpu_count() - 1, ): """ Gets or creates the relevant occupancy profiles for a building simulation or optimization. ...
b5284b03633699337075634d3484860d9c062e40
3,639,359
from typing import Optional from pathlib import Path import platform def get_local_ffmpeg() -> Optional[Path]: """ Get local ffmpeg binary path. ### Returns - Path to ffmpeg binary or None if not found. """ ffmpeg_path = Path( get_spotdl_path(), "ffmpeg" + ".exe" if platform.system()...
2495a1153da32f3ffb21075172cd0fb82b7809ea
3,639,360
def remaining_time(trace, event): """Calculate remaining time by event in trace :param trace: :param event: :return: """ # FIXME using no timezone info for calculation event_time = event['time:timestamp'].strftime("%Y-%m-%dT%H:%M:%S") last_time = trace[-1]['time:timestamp'].strftime("%Y...
87e961ca4091e8cc572c845968476a264aad5f27
3,639,361
def _water_vapor_pressure_difference(temp, wet_bulb_temp, vap_press, psych_const): """ Evaluate the psychrometric formula e_l - (e_w - gamma * (T_a - T_w)). Parameters ---------- temp : numeric Air temperature (K). wet_bulb_temp : numeric Wet-bulb temperature (K). ...
cee814a44ae1736dc35f08984cdb15fe94576716
3,639,362
def _service_description_required(func): """ Decorator for checking whether the service description is available on a device's service. """ @wraps(func) def wrapper(service, *args, **kwargs): if service.description is None: raise exceptions.NotRetrievedError('No service descrip...
27b962616026ad3987d2c214138d903971e2461c
3,639,363
def vector(*args): """ A single vector in any coordinate basis, as a numpy array. """ return N.array(args)
41da98ad36bff55fc4b71ce6b4e604262b2ecd1a
3,639,364
def arcmin_to_deg(arcmin: float) -> float: """ Convert arcmin to degree """ return arcmin / 60
9ef01181a319c0c48542ac57602bd7c17a7c1ced
3,639,365
def soft_embedding_lookup(embedding, soft_ids): """Transforms soft ids (e.g., probability distribution over ids) into embeddings, by mixing the embedding vectors with the soft weights. Args: embedding: A Tensor of shape `[num_classes] + embedding-dim` containing the embedding vectors. E...
4b831b8f23a226aac74c0bb3919e3c27bb57dc60
3,639,366
def param_11(i): """Returns parametrized Exp11Gate.""" return Exp11Gate(half_turns=i)
5458c8a4e992bd38dbb114e9ae4c4bac8a86fc75
3,639,367
def resolve_link(db: Redis[bytes], address: hash_t) -> hash_t: """Resolve any link recursively.""" key = join(ARTEFACTS, address, "links_to") link = db.get(key) if link is None: return address else: out = hash_t(link.decode()) return resolve_link(db, out)
b8087b2d015fc4b8515c35e437e609a935ccfcb2
3,639,368
def image_ppg(ppg_np): """ Input: ppg: numpy array Return: ax: 画布信息 im:图像信息 """ ppg_deps = ppg.DependenciesPPG() ppg_M = Matrix(ppg_np) monophone_ppgs = ppg.reduce_ppg_dim(ppg_M, ppg_deps.monophone_trans) monophone_ppgs = monophone_ppgs.numpy().T fig, ax = p...
714ccc3e294a5f02983a9aa384c2d6aa313ee4e5
3,639,369
def is_hex_value(val): """ Helper function that returns True if the provided value is an integer in hexadecimal format. """ try: int(val, 16) except ValueError: return False return True
6ba5ac1cfa9b8a4f8397cc52a41694cca33a4b8d
3,639,370
from typing import Optional def create_cluster(*, cluster_name: str) -> Optional[Operation]: """Create a dataproc cluster """ cluster_client = dataproc.ClusterControllerClient(client_options={"api_endpoint": dataproc_api_endpoint}) cluster = { "project_id": project_id, "cluster_name"...
1657190a7605f28f3c4dd2f2dc6c32230fb44087
3,639,371
import math def gc_cache(seq: str) -> Cache: """Return the GC ratio of each range, between i and j, in the sequence Args: seq: The sequence whose tm we're querying Returns: Cache: A cache for GC ratio lookup """ n = len(seq) arr_gc = [] for _ in seq: arr_...
7118cc96d0cd431b720b099b399c64ee419df5aa
3,639,372
def ParseVariableName(variable_name, args): """Parse a variable name or URL, and return a resource. Args: variable_name: The variable name. args: CLI arguments, possibly containing a config name. Returns: The parsed resource. """ return _ParseMultipartName(variable_name, args, ...
1073739195ca1bb0ac427e89e66525a7e7ada40b
3,639,373
def index(request): """Home page""" return render(request, 'read_only_site/index.html')
623c0cdc3229d1873e50ebc3065ca1ba55da50e7
3,639,374
def parse_calculation_strings_OLD(args): """form the strings into arrays """ calculations = [] for calculation in args.calculations: calculation = calculation.split("/") foreground = np.fromstring( ",".join(calculation[0].replace("x", "0")), sep=",") background = np.f...
04c979cc09bd25d659dad0a96ca89b88b43267cb
3,639,375
import tempfile import os import shutil def fixture_hdf5_scalar(request): """fixture_hdf5_scalar""" import h5py # pylint: disable=import-outside-toplevel tmp_path = tempfile.mkdtemp() filename = os.path.join(tmp_path, "test.h5") with h5py.File(filename, 'w') as f: f.create_dataset('int8', data=np.int8...
6919238dbc879f2bc08c8c397895f890a5c428a0
3,639,376
def find_border(edge_list) : """ find_border(edge_list) Find the borders of a hexagonal graph Input ----- edge_list : array List of edges of the graph Returns ------- border_set : set Set of vertices of the border ...
718a2b56438caf60d3ca4e3cd7419452c8fbbb63
3,639,377
from typing import Set from datetime import datetime def get_all_files(credentials: Credentials, email: str) -> Set['DriveResult']: """Get all files shared with the specified email in the current half-year (January-June or July-December of the current year)""" # Create drive service with provided credenti...
eb7e491cac08bada675f0d39414ae3d907686741
3,639,378
def _split_kwargs(model, kwargs, lookups=False, with_fields=False): """ Split kwargs into fields which are safe to pass to create, and m2m tag fields, creating SingleTagFields as required. If lookups is True, TagFields with tagulous-specific lookups will also be matched, and the returned tag_fields...
f73cb84bab0889b51962ed3504b6de265831d18f
3,639,379
def sliceResultToBytes(sr): """Copies a FLSliceResult to a Python bytes object. Does not free the FLSliceResult.""" if sr.buf == None: return None lib.FLSliceResult_Release(sr) b = bytes( ffi.buffer(sr.buf, sr.size) ) return b
0e2207a99749b4cd3df4b71ca7338de4c0ad6a06
3,639,380
def cycle_dual(G, cycles, avg_fun=None): """ Returns dual graph of cycle intersections, where each edge is defined as one cycle intersection of the original graph and each node is a cycle in the original graph. The general idea of this algorithm is: * Find all cycles which ...
a923a4cea0f1d158e6936a68e513bd2285ea6b15
3,639,381
from sys import path import os import shutil def main(): """Entry point""" if check_for_unstaged_changes(TARGET_FILE): print("ERROR: You seem to have unstaged changes to %s that would be overwritten." % (TARGET_FILE)) print("Please clean, commit, or stash them before running this...
0c628c917e596d3e1283dd729eac13d9a23a2d42
3,639,382
def get_timebucketedlog_reader(log, event_store): """ :rtype: TimebucketedlogReader """ return TimebucketedlogReader(log=log, event_store=event_store)
676e38a446f60dd8f2c90b38df572b2f5fc9c21e
3,639,383
def get_database_name(url): """Return a database name in a URL. Example:: >>> get_database_name('http://foobar.com:5984/testdb') 'testdb' :param str url: The URL to parse. :rtype: str """ name = compat.urlparse(url).path.strip("/").split("/")[-1] # Avoid re-encoding the n...
2916e5a5999aae68b018858701dfb5e695857f7f
3,639,384
def get_tags(): """ 在这里希望根据用户来获取,和用户有关的tag 所以我们需要做的是,获取用户所有的post,然后找到所有的tag :return: """ result_tags = [] # 找到某个用户的所有的文章,把所有文章的Tag都放在一块 def append_tag(user_posts): tmp = [] for post in user_posts: for tag in post.tags.all(): tmp.append(tag.ta...
821ca1bb222e4fe15ea336282fed0eb172d460f9
3,639,385
import os def get_selinux_modules(): """ Read all custom SELinux policy modules from the system Returns 3-tuple (modules, retain_rpms, install_rpms) where "modules" is a list of "SELinuxModule" objects, "retain_rpms" is a list of RPMs that should be retained during the upgrade and "install_rp...
20c548c3f2227551a51ce774014d63754251e1e6
3,639,386
def a_star_search(graph, start, goal): """Runs an A* search on the specified graph to find a path from the ''start'' node to the ''goal'' node. Returns a list of nodes specifying a minimal path between the two nodes. If no path exists (disconnected components), returns an empty list. """ all_nodes =...
f2eabef1e30f12460359ea45cbc089f8fb28e5f9
3,639,387
import click def output_format_option(default: OutputFormat = OutputFormat.TREE): """ A ``click.option`` for specifying a format to use when outputting data. Args: default (:class:`~ape.cli.choices.OutputFormat`): Defaults to ``TREE`` format. """ return click.option( "--format", ...
9f73a8b8d270975d16ec9d3b2962f4fd61491aab
3,639,388
def compute_errors(u_e, u): """Compute various measures of the error u - u_e, where u is a finite element Function and u_e is an Expression. Adapted from https://fenicsproject.org/pub/tutorial/html/._ftut1020.html """ print('u_e',u_e.ufl_element().degree()) # Get function space V = u.functi...
c9fbd459ab1c3cd65fb4d290e1399dd4937ed5a2
3,639,389
def list_to_str(input_list, delimiter=","): """ Concatenates list elements, joining them by the separator specified by the parameter "delimiter". Parameters ---------- input_list : list List with elements to be joined. delimiter : String, optional, default ','. The separato...
4decfbd5a9d637f27473ec4a917998137af5ffe0
3,639,390
def strategy_supports_no_merge_call(): """Returns if the current `Strategy` can operate in pure replica context.""" if not distribution_strategy_context.has_strategy(): return True strategy = distribution_strategy_context.get_strategy() return not strategy.extended._use_merge_call() # pylint: disable=prote...
dc2b609a52d7e25b372e0cd1a04a0637d76b8ec1
3,639,391
def is_group(obj): """Returns true if the object is a h5py-like group.""" kind = get_h5py_kind(obj) return kind in ["file", "group"]
37c86b6d4f052eab29106b9d51c17cdd36b1dc98
3,639,392
from bs4 import BeautifulSoup def analyze_page(page_url): """ Analyzes the content at page_url and returns a list of the highes weighted words.json/phrases and their weights """ html = fetch_html(page_url) if not html: return soup = BeautifulSoup(html, "html.parser") word_counts = {}...
55928add263defa51a171a2dfb20bffe6491430c
3,639,393
from typing import Iterable from typing import List def load_config_from_paths(config_paths: Iterable[str], strict: bool = False) -> List[dict]: """ Load configuration from paths containing \*.yml and \*.json files. As noted in README.config, .json will take precedence over .yml files. :param config_...
8e32c46e7e620ae02dffcc652b32bb0098a0a2b3
3,639,394
from typing import List def sort_flats(flats_unsorted: List[arimage.ARImage]): """ Sort flat images into a dictionary with "filter" as the key """ if bool(flats_unsorted) == False: return None flats = { } logger.info("Sorting flat images by filter") for flat in flats_unsorted: fl =...
d0e3fe2c7e1a8f34cf7ed8f6985d3dd7bc82f3f1
3,639,395
import concurrent import logging def run_in_parallel(function, list_of_kwargs_to_function, num_workers): """Run a function on a list of kwargs in parallel with ThreadPoolExecutor. Adapted from code by mlbileschi. Args: function: a function. list_of_kwargs_to_function: list of dictionary from string to ...
24b99f68ba1221c4f064a65540e6c165c9474e43
3,639,396
import os import requests def upload(host, key, path): """ Upload one file at a time """ url= urljoin(host, 'api/files?key=' + key) os.chdir(path[0]) f = open(path[1], 'rb') r = requests.post(url, files={"File" : f}) r.raise_for_status() return r.json()['id']
78e8cac5239d631f5dea8dae0bb0a52e43e1b307
3,639,397
def show_project(project_id): """return a single project formatted according to Swagger spec""" try: project = annif.project.get_project( project_id, min_access=Access.hidden) except ValueError: return project_not_found_error(project_id) return project.dump()
3f7108ec7cb27270f91517bef194f3514c3eb4e5
3,639,398
def pollard_rho(n: int, e: int, seed: int = 2) -> int: """ Algoritmo de Pollard-Rho para realizar a quebra de chave na criptografia RSA. n - n da chave pública e - e da chave pública seed - valor base para executar o ciclo de testes """ a, b = seed, seed p = 1 while (p == 1): ...
4870627a5fca863d4110f3cadfdc1e7b618c2a48
3,639,399