content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def get_wharton_sessionid(public=False): """ Try to get a GSR session id. """ sessionid = request.args.get("sessionid") cache_key = "studyspaces:gsr:sessionid" if sessionid: return sessionid if public: if db.exists(cache_key): return db.get(cache_key).decode...
83cc911185a8849ca7c37bf74ea0ae652b596461
3,657,600
def timing ( name = '' , logger = None ) : """Simple context manager to measure the clock counts >>> with timing () : ... whatever action is here at the exit it prints the clock counts >>> with timing () as c : ... whatever action is here at the exit it prints the clock coun...
f22769f267df8472f8b11db64ab6817db6e24414
3,657,601
def abs(x): """ complex-step safe version of numpy.abs function. Parameters ---------- x : ndarray array value to be computed on Returns ------- ndarray """ if isinstance(x, np.ndarray): return x * np.sign(x) elif x.real < 0.0: return -x return x
71503b89e3a78e12a50f88ce2e0a17301f985ec7
3,657,602
import time import re from operator import sub async def add_comm_post(request): # return json.dumps(current_id, title, link, proc_id) """current_id это id ветки""" # ip = request.environ.get('REMOTE_ADDR') data = await request.post(); ip = None print('data->', data) #get ip address client peername = request.tr...
1038edd1834786ba1325e7f28f77f505adc8fb4b
3,657,603
def reachable_from_node(node, language=None, include_aliases=True): """Returns a tuple of strings containing html <ul> lists of the Nodes and pages that are children of "node" and any MetaPages associated with these items. :params node: node to find reachables for :params language: if None, retur...
dcc93486fcae168293f17ee2a7c067dbc1eef5fe
3,657,604
def init_data(): """ setup all kinds of constants here, just to make it cleaner :) """ if args.dataset=='imagenet32': mean = (0.4811, 0.4575, 0.4078) std = (0.2605 , 0.2533, 0.2683) num_classes = 1000 else: raise NotImplementedError if args.whiten_image==0: ...
7d75af1f316a703041926d9a1875ae18f19c8342
3,657,605
def make_status_craft(): """ Cria alguns status de pedido de fabricação""" if Statusfabricacao.objects.count() == 0: status1 = Statusfabricacao(order=0, status='Pedido Criado') status2 = Statusfabricacao(order=1, status='Maturação') status3 = Statusfabricacao(order=2, status='Finalizaçã...
01b9e1cbb48654f3baab7a4e55cd0f22a0bb60fe
3,657,606
import requests import json def _call_rest_api(url, input_data, request_type): """Calls the other rest api's""" try: if request_type == 'post': req = requests.post(url, params=input_data, json=input_data, timeout=30) else: req = requests.get(url, params=input_data, time...
8c67e79c6867d1e63a1487c747682c24da229e46
3,657,607
def compute_tso_threshold(arr, min_td=0.1, max_td=0.5, perc=10, factor=15.0): """ Computes the daily threshold value separating rest periods from active periods for the TSO detection algorithm. Parameters ---------- arr : array Array of the absolute difference of the z-angle. min_td...
4188d4a290e884210351f928d18d6f4bdd4e8a0b
3,657,608
def run_generator(conversation_name): """ Input: conversation_name: name of conversation to analyze Output: username of next speaker, message for that speaker to send next """ state = settings.DISCORD_CONVERSATION_STATES.get(conversation_name, {}) ( next_speaker_username...
22735cdd46469976d079f065ee60e3a886dfc654
3,657,609
def count_uniques(row): """ Count the unique values in row -1 (becase nan counts as a unique value) """ return len(np.unique(row)) - 1
af28e419aba44992ee27c57dacb271ff692fc535
3,657,610
import numpy def gmres_dot(X, surf_array, field_array, ind0, param, timing, kernel): """ It computes the matrix-vector product in the GMRES. Arguments ---------- X : array, initial vector guess. surf_array : array, contains the surface classes of each region on the ...
89ab7b49ef8f55bdeddbd9676acdc6cbe0de321f
3,657,611
import torch def update_pris(traj, td_loss, indices, alpha=0.6, epsilon=1e-6, update_epi_pris=False, seq_length=None, eta=0.9): """ Update priorities specified in indices. Parameters ---------- traj : Traj td_loss : torch.Tensor indices : torch.Tensor ot List of int alpha : float ...
41648ae78f25618b2789d8dde41cffbe0445d16b
3,657,612
from typing import Sequence from pydantic import BaseModel # noqa: E0611 import hashlib def get_library_version(performer_prefix: str, schemas: Sequence[Schema]) -> str: """Generates the library's version string. The version string is of the form "{performer_prefix}_{latest_creation_date}_{library_hash}". ...
90bf2c695eece054f20bc0636b8e9759983affef
3,657,613
def sizeFromString(sizeStr, relativeSize): """ Converts from a size string to a float size. sizeStr: The string representation of the size. relativeSize: The size to use in case of percentages. """ if not sizeStr: raise Exception("Size not specified") dpi = 96.0 cm = 2.54 if len(sizeStr) > 2 and sizeStr[-2:...
5f53d7d1ea86d4c54beb3aaebca228f7706e5a9b
3,657,614
from typing import Union from typing import List def plot_r2( model: mofa_model, x="Group", y="Factor", factors: Union[int, List[int], str, List[str]] = None, groups_df: pd.DataFrame = None, group_label: str = None, views=None, groups=None, cmap="Blues", vmin=None, vmax=Non...
4898f56ca89ef55db775f0dc3b0106c36a2ced05
3,657,615
from typing import Union from typing import Optional from typing import Tuple from typing import List def all(x: Union[ivy.Array, ivy.NativeArray], axis: Optional[Union[int, Tuple[int], List[int]]] = None, keepdims: bool = False)\ -> ivy.Array: """ Tests whether all input array element...
3854912ea0d6fceb4dc51576dd4b11923da68876
3,657,616
import re def verify_time_format(time_str): """ This method is to verify time str format, which is in the format of 'hour:minute', both can be either one or two characters. Hour must be greater or equal 0 and smaller than 24, minute must be greater or equal 0 and smaller than 60 :param time...
fee469248d4d1d792c1ed858cf9043e5695c9f5d
3,657,617
def extract_region_df(region_code="11"): """ Extracts dataframes that describes regional-level vaccines data for a single region, making some analysis on it. :rtype: Dataframe """ df = RAW_DF df = df.loc[df['codice_regione_ISTAT'] == region_code] df = df.sort_values('data_somministrazione...
8c3e77c1548b8bf40d0be31ac52237c532a4c622
3,657,618
from bs4 import BeautifulSoup def get_title(offer_markup): """ Searches for offer title on offer page :param offer_markup: Class "offerbody" from offer page markup :type offer_markup: str :return: Title of offer :rtype: str, None """ html_parser = BeautifulSoup(offer_markup, "html.parser"...
72618da71ea63d1b3431ba76f5d8a9549af6fe76
3,657,619
import os import shutil def genome(request): """Create a test genome and location""" name = "ce10" # Use fake name for blacklist test fafile = "tests/data/small_genome.fa.gz" genomes_dir = os.path.join(os.getcwd(), ".genomepy_plugin_tests") if os.path.exists(genomes_dir): shutil.rmtree(g...
21f6b4c41fdfe5c8f934c358d78d9862a16e3324
3,657,620
def get_twinboundary_shear_structure(twinboundary_relax_structure, shear_strain_ratio, previous_relax_structure=None, **additional_relax_structures, ): """ If lates...
c155db78f4d3d7f939e7c38e0c05955c3bd0f8c9
3,657,621
def _map_spectrum_weight(map, spectrum=None): """Weight a map with a spectrum. This requires map to have an "energy" axis. The weights are normalised so that they sum to 1. The mean and unit of the output image is the same as of the input cube. At the moment this is used to get a weighted exposure...
5a1d9b9e3a94854e8c53947ca494f7448d2af570
3,657,622
def fetch_all_db_as_df(allow_cached=False): """Converts list of dicts returned by `fetch_all_db` to DataFrame with ID removed Actual job is done in `_worker`. When `allow_cached`, attempt to retrieve timed cached from `_fetch_all_db_as_df_cache`; ignore cache and call `_work` if cache expires or `allow_cach...
c7f049590c8405a862890944cfaabfefebea1d58
3,657,623
def tool_proxy_from_persistent_representation(persisted_tool, strict_cwl_validation=True, tool_directory=None): """Load a ToolProxy from a previously persisted representation.""" ensure_cwltool_available() return ToolProxy.from_persistent_representation( persisted_tool, strict_cwl_validation=strict_...
e1f96d66cb1634d4de82b3e31f0fb9dd81080262
3,657,624
def has_space_element(source): """ 判断对象中的元素,如果存在 None 或空字符串,则返回 True, 否则返回 False, 支持字典、列表和元组 :param: * source: (list, set, dict) 需要检查的对象 :return: * result: (bool) 存在 None 或空字符串或空格字符串返回 True, 否则返回 False 举例如下:: print('--- has_space_element demo---') print(has_space_...
ab8a968fb807654af73d9017145c0af2259ae41e
3,657,625
def return_latest_psm_is(df, id_col, file_col, instr_col, psm_col): """ Extracts info on PSM number, search ID and Instrument from the last row in DB """ last_row = df.iloc[-1] search_id = last_row[id_col] instr = last_row[instr_col] psm = last_row[psm_col] psm_string = str(psm) + ' PSMs in ...
73c5acc945b9a6ef40aa1ce102351152b948a4b6
3,657,626
def add_parser_arguments_misc(parser): """ Adds the options that the command line parser will search for, some miscellaneous parameters, like use of gpu, timing, etc. :param parser: the argument parser :return: the same parser, but with the added options. """ parser.add_argument('--use_gpu',...
706ec64dfd6393fd1bd4741568e5e1af1d22a4d0
3,657,627
from typing import Union import torch def colo_model_tensor_clone(t: Union[StatefulTensor, torch.Tensor], target_device: torch.device) -> torch.Tensor: """ Clone a model data tensor Args: t (Union[StatefulTensor, torch.Tensor]): a model data tensor target_device (torch.device): the target ...
799d23e5f69ad73ecef040e94fecb64bb7b8c7d9
3,657,628
def plugin_init(config): """Registers HTTP Listener handler to accept sensor readings Args: config: JSON configuration document for the South device configuration category Returns: handle: JSON object to be used in future calls to the plugin Raises: """ handle = config retur...
a3e81bebdc806073b720e0a3174e62240ba81724
3,657,629
import time import json def search(query,page): """Scrapes the search query page and returns the results in json format. Parameters ------------ query: The query you want to search for. page: The page number for which you want the results. Every page returns 11 results. ...
4bcc78aeb29715adaca7b99d98d94c28448e24f7
3,657,630
import os import json def get_jobs(job_filename): """Reads jobs from a known job file location """ jobs = list() if job_filename and os.path.isfile(job_filename): with open(job_filename, 'r') as input_fd: data = input_fd.read() job_dict = json.loads(data) del dat...
eaa091131a026c8a4c5f4e788406e185e1bbffde
3,657,631
def quote_with_backticks_definer(definer): """Quote the given definer clause with backticks. This functions quotes the given definer clause with backticks, converting backticks (`) in the string with the correct escape sequence (``). definer[in] definer clause to quote. Returns string with th...
ab87c8582d8081e324b494d7038916e984d5813a
3,657,632
import base64 def cvimg_to_b64(img): """ 图片转换函数,将二进制图片转换为base64加密格式 """ try: image = cv2.imencode('.jpg', img)[1] #将图片格式转换(编码)成流数据,赋值到内存缓存中 base64_data = str(base64.b64encode(image))[2:-1] #将图片加密成base64格式的数据 return base64_data #返回加密后的结果 except Exception as e: return...
c9f4c99ff24578ac4f6216ddefade0602c60c697
3,657,633
from PIL import Image from scipy.misc import fromimage from skimage.color import label2rgb from skimage.transform import resize from io import StringIO def draw_label(label, img, n_class, label_titles, bg_label=0): """Convert label to rgb with label titles. @param label_title: label title for each labels. ...
11b8f1e9c774df3e6312aa3dd0f71e7f300b5547
3,657,634
def inspect(template_dir, display_type=None): """Generates a some string representation of all undefined variables in templates. Args: template_dir (str): all files within are treated as templates display_type (str): tabulate.tabulate tablefmt or 'terse'. Examples: Yields an ov...
1f557da1742ca3c2118bb5629f228079ee14e729
3,657,635
def calc_fitness_all(chromosomes, video_list, video_data): """Calculates fitness for all chromosomes Parameters ---------- chromosomes : np.ndarrray List of chromosomes video_list : np.ndarray List of all video titles (in this case number identifiers) video_data : pd dataframe ...
e0a28880a31fb5d1546c4f959cd1836e89822471
3,657,636
from typing import List from typing import Set def grouping_is_valid( proposed_grouping: List[Set[str]], past_groups: List[Set[str]], max_intersection_size: int, ) -> bool: """Returns true if no group in the proposed grouping intersects with any past group with intersection size strictly greater t...
caeb7568a2e8fddea9058ccc512dc9c06070ece9
3,657,637
def next_wire_in_dimension(wire1, tile1, wire2, tile2, tiles, x_wires, y_wires, wire_map, wires_in_node): """ next_wire_in_dimension returns true if tile1 and tile2 are in the same row and column, and must be adjcent. """ tile1_info = tiles[tile1] tile2_info = tiles[tile2] ...
2c2b6a2cb4d117f2435568437d38f05311b7dd13
3,657,638
from typing import Optional def get(*, db_session, report_id: int) -> Optional[Report]: """ Get a report by id. """ return db_session.query(Report).filter(Report.id == report_id).one_or_none()
021a7d35e060a2c92c9443361beff03de9aaf048
3,657,639
import urllib def host_from_path(path): """returns the host of the path""" url = urllib.parse.urlparse(path) return url.netloc
95b362e8f20c514a77506356c3a4a0c1ef200490
3,657,640
def sampleM(a0, bk, njk, m_cap=20): """produces sample from distribution over M using normalized log probabilities parameterizing a categorical dist.""" raise DeprecationWarning() wts = np.empty((m_cap,)) sum = 0 for m in range(m_cap): wts[m] = gammaln(a0*bk) - gammaln(a0*bk+njk) + log(...
76cc9e0bd6a0594bd8b6350053957073ccf9caf9
3,657,641
def or_default(none_or_value, default): """ inputs: none_or_value: variable to test default: value to return if none_or_value is None """ return none_or_value if none_or_value is not None else default
43200fe3bd1308eed87de0ad905873fd3c629067
3,657,642
def find_optimal_components_subset(contours, edges): """Find a crop which strikes a good balance of coverage/compactness. Returns an (x1, y1, x2, y2) tuple. """ c_info = props_for_contours(contours, edges) c_info.sort(key=lambda x: -x['sum']) total = np.sum(edges) / 255 area = edges.shape[0...
016815811b6fa80378142303e3dce8f7736c514c
3,657,643
import re def scrape(html): """정규표현식으로 도서 정보 추출""" books = [] for partial_html in re.findall(r'<td class="left">Ma.*?</td>', html, re.DOTALL): #도서의 URL 추출 url = re.search(r'<a href="(.*?)">', partial_html).group(1) url = 'http://www.hanbit.co.kr' + url #태그를 제거해 도서의 제목 추출 ...
8703c48748607934491e92c3e0243e92cd7edf12
3,657,644
def get_time_zone_offset(area_code): """ Returns an integer offset value if it finds a matching area code, otherwise returns None.""" if not isinstance(area_code, str): area_code = str(area_code) if area_code in area_code_mapping: return area_code_mapping[area_code][1]
4697a07d53af25ef70facf30f4bbef2472494781
3,657,645
def true_false_counts(series: pd.Series): """ input: a boolean series returns: two-tuple (num_true, num_false) """ return series.value_counts().sort_index(ascending=False).tolist()
7fc7d0beb1d11aa7a4e3ccb6dd00155194deac3d
3,657,646
def phyutility(DIR,alignment,min_col_occup,seqtype,min_chr=10): """ remove columns with occupancy lower than MIN_COLUMN_OCCUPANCY remove seqs shorter than MIN_CHR after filter columns """ if DIR[-1] != "/": DIR += "/" cleaned = alignment+"-cln" if os.path.exists(DIR+cleaned): return cleaned assert alignment.end...
42a14d2588e71af5834179f0364925da31d9ef34
3,657,647
def configProject(projectName): """ read in config file""" if projectName==None:return filename=os.path.join(projectsfolder,unicode(projectName),u"project.cfg" ).encode("utf-8") if projectName not in projects: print 'Content-type: text/plain\n\n',"error in projects:",type(projectName),"projectName:",[projectName...
e11c31be073b8699c2bd077815720467b9fd6e2e
3,657,648
def bitwise_not(rasters, extent_type="FirstOf", cellsize_type="FirstOf", astype=None): """ The BitwiseNot operation The arguments for this function are as follows: :param rasters: array of rasters. If a scalar is needed for the operation, the scalar can be a double or string :param extent_type: on...
0edaeaf2b96a48520309dee4809c3251d47c98e8
3,657,649
import re def keyclean(key): """ Default way to clean table headers so they make good dictionary keys. """ clean = re.sub(r'\s+', '_', key.strip()) clean = re.sub(r'[^\w]', '', clean) return clean
0f28f0e92e2817a98a31396949690a46e7538ace
3,657,650
import collections def get_rfactors_for_each(lpin): """ R-FACTORS FOR INTENSITIES OF DATA SET /isilon/users/target/target/Iwata/_proc_ox2r/150415-hirata/1010/06/DS/multi011_1-5/XDS_ASCII_fullres.HKL RESOLUTION R-FACTOR R-FACTOR COMPARED LIMIT observed expected 5.84 60.4% 50.1...
937ad8e2cf01fa6ab92838d235a385f9bbfb1b63
3,657,651
def value_left(self, right): """ Returns the value of the right type instance to use in an operator method, namely when the method's instance is on the left side of the expression. """ return right.value if isinstance(right, self.__class__) else right
f28c2f0548d3e004e3dd37601dda6c1ea5ab36f6
3,657,652
def correct_throughput(inspec, spFile='BT-Settl_Asplund2009.fits', quiet=False): """ Main function Inputs: inspec - list of input spectra, each list item should be a 3xN array of wavelenghts (in microns), flux, and variance. One list item for each ...
1c1eecf308f738cce891176ab8e527be97839493
3,657,653
import numbers import collections def convert_list( items, ids, parent, attr_type, ): """Converts a list into an XML string.""" LOG.info('Inside convert_list()') output = [] addline = output.append if ids: this_id = get_unique_id(parent) for (i, item)...
3e73fa756e5bd2685d529bb21170ab35dd6dedff
3,657,654
def get_mid_surface(in_surfaces): """get_mid_surface gives the mid surface when dealing with the 7 different surfaces Args: (list of strings) in_surfaces : List of path to the 7 different surfaces generated by mris_expand Returns: (string) Path to the mid surface """ return in_surf...
718ab8fa7a3b716241ae05a4e507f40ab6cb0efd
3,657,655
def parse_type(msg_type): """ Parse ROS message field type :param msg_type: ROS field type, ``str`` :returns: base_type, is_array, array_length, ``(str, bool, int)`` :raises: :exc:`ValueError` If *msg_type* cannot be parsed """ if not msg_type: raise ValueError("Invalid empty type") ...
1dfe4f3abb7b69bed17b60ee2666279081666dc6
3,657,656
from typing import List from typing import Optional import glob def preprocess(feature_modules: List, queries: List[Query], prefix: Optional[str] = None, process_count: Optional[int] = None): """ Args: feature_modules: the feature modules used to generate features, each ...
2896482423d9306d01d225ef785e0680844a13a4
3,657,657
def to_distance(maybe_distance_function): """ Parameters ---------- maybe_distance_function: either a Callable, which takes two arguments, or a DistanceFunction instance. Returns ------- """ if maybe_distance_function is None: return NoDistance() if isinstance(maybe_...
4e801a948d86594efdb1d05f352eb449e8bbdd02
3,657,658
def echo(text): """Return echo function.""" return text
c128bc86bc63006a1ac5b209c10b21f787b7100a
3,657,659
import os def predict(): """Renders the predict page and makes predictions if the method is POST.""" if request.method == 'GET': return render_predict() # Get arguments checkpoint_name = request.form['checkpointName'] if 'data' in request.files: # Upload data file with SMILES ...
bd3fb9d7ca6c54946e6c65e281682e69f3550340
3,657,660
def zernike_name(index, framework='Noll'): """ Get the name of the Zernike with input index in input framework (Noll or WSS). :param index: int, Zernike index :param framework: str, 'Noll' or 'WSS' for Zernike ordering framework :return zern_name: str, name of the Zernike in the chosen framework ...
33e73739c11bc2340a47162e161ba7d87e26d279
3,657,661
def discriminator_train_batch_mle(batches, discriminator, loss_fn, optimizer): """ Summary 1. watch discriminator trainable_variables 2. extract encoder_output, labels, sample_weight, styles, captions from batch and make them tensors 3. predictions = discriminator(encoder_output, captions, styles, t...
2bb4cd47ddeea5c2edb6f627e39843ba18593833
3,657,662
def get_subs_dict(expression, mod): """ Builds a substitution dictionary of an expression based of the values of these symbols in a model. Parameters ---------- expression : sympy expression mod : PysMod Returns ------- dict of sympy.Symbol:float """ subs_dict = {} ...
075b406dfbdcb5a0049589880ad8b08fbd459159
3,657,663
def save_index_summary(name, rates, dates, grid_dim): """ Save index file Parameters ---------- See Also -------- DataStruct """ with open(name + INDEX_SUMMARY_EXT, "w+b") as file_index: nlist = 0 keywords_data, nums_data, nlist = get_keywords_section_data(rates) ...
ac807dac6a1c63eca7b20322dc2c4122dc0b7ec8
3,657,664
def fluxes_SIF_predict_noSIF(model_NEE, label, EV1, EV2, NEE_max_abs): """ Predict the flux partitioning from a trained NEE model. :param model_NEE: full model trained on NEE :type model_NEE: keras.Model :param label: input of the model part 1 (APAR) :type label: tf.Tensor :param EV1: input...
3f5ecf95c27a4deb04894c84de903a5eb34858d0
3,657,665
def xml_string(line, tag, namespace, default=None): """ Get string value from etree element """ try: val = (line.find(namespace + tag).text) except: val = default return val
77745d463cf6604ed787e220fdabf6ff998f770e
3,657,666
from datetime import datetime def generate_header(salutation, name, surname, postSalutation, address, zip, city, phone, email): """ This function generates the header pdf page """ # first we take the html file and parse it as a string #print('generating header page', surname, name) with open('...
c979c2985d730eee0ce5b442e55a050e7cc4a672
3,657,667
def cli_cosmosdb_collection_exists(client, database_id, collection_id): """Returns a boolean indicating whether the collection exists """ return len(list(client.QueryContainers( _get_database_link(database_id), {'query': 'SELECT * FROM root r WHERE r.id=@id', 'parameters': [{'name': '@i...
99ada0b4c4176b02d4bbe00c07b991a579a917d0
3,657,668
def probabilities (X) -> dict: """ This function maps the set of outcomes found in the sequence of events, 'X', to their respective probabilty of occuring in 'X'. The return value is a python dictionary where the keys are the set of outcomes and the values are their associated probabilities.""" # The set of outcomes...
c908a1186feea270be71bb1f03485c901bc82733
3,657,669
import time import requests def get_recommend_news(): """获取新闻推荐列表""" # 触电新闻主页推荐实际URL recommend_news_url = 'https://api.itouchtv.cn:8090/newsservice/v9/recommendNews?size=24&channelId=0' # 当前毫秒时间戳 current_ms = int(time.time() * 1000) headers = get_headers(target_url=recommend_news_url, ts_ms=cu...
3bee0bb7c1fb977d9380a9be07aab4b802149d6a
3,657,670
def put_profile_pic(url, profile): """ Takes a url from filepicker and uploads it to our aws s3 account. """ try: r = requests.get(url) size = r.headers.get('content-length') if int(size) > 10000000: #greater than a 1mb #patlsotw return False filename, h...
7bc201b754f33518a96a7e6a562e5a6ec601dfb5
3,657,671
from typing import Tuple from pathlib import Path from typing import Dict def get_raw_data() -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """Loads serialized data from file. Returns: Tuple[np.ndarray, np.ndarray, np.ndarray]: Tuple of features, labels and classes for the dataset. ""...
58e98b733c396fa8dca5f9dd442625283cae5f1e
3,657,672
import requests def cog_pixel_value( lon, lat, url, bidx=None, titiler_endpoint="https://titiler.xyz", verbose=True, **kwargs, ): """Get pixel value from COG. Args: lon (float): Longitude of the pixel. lat (float): Latitude of the pixel. url (str): HTTP URL...
40494f5ee491283b127409f52dd0e1d9029bce52
3,657,673
def select_daily(ds, day_init=15, day_end=21): """ Select lead time days. Args: ds: xarray dataset. day_init (int): first lead day selection. Defaults to 15. day_end (int): last lead day selection. Defaults to 21. Returns: xarray dataset subset based on time...
9948ecba5acc3c1ca2fe28526585d0bfa81fb862
3,657,674
def project_polarcoord_lines(lines, img_w, img_h): """ Project lines in polar coordinate space <lines> (e.g. from hough transform) onto a canvas of size <img_w> by <img_h>. """ if img_w <= 0: raise ValueError('img_w must be > 0') if img_h <= 0: raise ValueError('img_h must be > ...
7a6a75daedadc6ddfd6f8f55a7a57ae80865605e
3,657,675
def standardize_for_imshow(image): """ A luminance standardization for pyplot's imshow This just allows me to specify a simple, transparent standard for what white and black correspond to in pyplot's imshow method. Likely could be accomplished by the colors.Normalize method, but I want to make this as expl...
8b89235623746019b53d3c44dd8cecc2d313ffbd
3,657,676
def err_failure(error) : """ Check a error on failure """ return not err_success(error)
17e9edbbe7bb5451d991fb94108148d2d0b1c644
3,657,677
def rah_fixed_dt( u2m, roh_air, cp, dt, disp, z0m, z0h, tempk): """ It takes input of air density, air specific heat, difference of temperature between surface skin and a height of about 2m above, and the aerodynamic resistance to heat transport. This version runs an iteration loop to stabilize psychrometric data fo...
bd48c62817f25964fa394ace35ab24357d455797
3,657,678
def process_grid_subsets(output_file, start_subset_id=0, end_subset_id=-1): """"Execute analyses on the data of the complete grid and save the processed data to a netCDF file. By default all subsets are analyzed Args: output_file (str): Name of netCDF file to which the results are saved for the...
4103cffd3b519f16205fbf5dfb38ae198f315258
3,657,679
def bulk_lookup(license_dict, pkg_list): """Lookup package licenses""" pkg_licenses = {} for pkg in pkg_list: # Failsafe in case the bom file contains incorrect entries if not pkg.get("name") or not pkg.get("version"): continue pkg_key = pkg["name"] + "@" + pkg["version"]...
aa06b02fdfaa079dbfc4e1210ccccc995393dc52
3,657,680
def pack_bits(bools): """Pack sequence of bools into bits""" if len(bools) % 8 != 0: raise ValueError("list length must be multiple of 8") bytes_ = [] b = 0 for j, v in enumerate(reversed(bools)): b <<= 1 b |= v if j % 8 == 7: bytes_.append(b) ...
fadfb5e6abdb80691473262fac57f22384827c50
3,657,681
def init_ring_dihedral(species,instance,geom = []): """ Calculates the required modifications to a structures dihedral to create a cyclic TS """ if len(geom) == 0: geom = species.geom if len(instance) > 3: if len(instance) < 6: final_dihedral = 15. ...
7799ec63b4188d79104e4ab758fb42b497a64053
3,657,682
from typing import List from typing import Optional def get_largest_contour( contours: List[NDArray], min_area: int = 30 ) -> Optional[NDArray]: """ Finds the largest contour with size greater than min_area. Args: contours: A list of contours found in an image. min_area: The smallest ...
e505e9265540ae2f35e2de0f587aeaee067e5583
3,657,683
def particle( engine, particle_id="", color: Tuple4 = (1, 0.4, 0.1, 1), random_color: bool = False, color_temp: bool = False, vx=None, vy=None, vz=None, speed_limit=None, ) -> Material: """ Particle material. """ mat = bpy.data.materials.new(f"Particle{particle_id}") # F...
2bb120d4fd32c31bad7f9ee9765d1fc5808992a4
3,657,684
import os import scipy def _get_hardware_sharing_throughputs( outdirs, device, device_model, precs, filename, mode, ): """ The result is in the format of { 'amp': pd.DataFrame, # df contains max_B rows 'fp32': pd.DataFrame, # df contains max_B rows } df format: (`B` is the ind...
bd104c88144cc1635e4387c93aaf838f210b9703
3,657,685
def mask_to_segm(mask, bbox, segm_size, index=None): """Crop and resize mask. This function requires cv2. Args: mask (~numpy.ndarray): See below. bbox (~numpy.ndarray): See below. segm_size (int): The size of segm :math:`S`. index (~numpy.ndarray): See below. :math:`R = N` ...
5fd4003595ce7b13bcf59ce8669bfdb37a545d5b
3,657,686
def append_unique(func): """ This decorator will append each result - regardless of type - into a list. """ def inner(*args, **kwargs): return list( set( _results( args[0], func.__name__, *args, ...
ed656c500f95b03e8036605e9af5cc739830ff7b
3,657,687
def _get_unique_figs(tree): """ Extract duplicate figures from the tree """ return _find_unique_figures_wrap(list(map(_get_fig_values(tree), tree)), [])
ba8a40766981bca9ca23fd3ec681f1a8d52ad85b
3,657,688
def read_fssp(fssp_handle): """Process a FSSP file and creates the classes containing its parts. Returns: :header: Contains the file header and its properties. :sum_dict: Contains the summary section. :align_dict: Contains the alignments. """ header = FSSPHeader() sum_dict ...
4ac2c61ed40f14102d0ae1a8a3b6fa8e69252f27
3,657,689
import json def LoadJSON(json_string): """Loads json object from string, or None. Args: json_string: A string to get object from. Returns: JSON object if the string represents a JSON object, None otherwise. """ try: data = json.loads(json_string) except ValueError: data = None return ...
598c9b4d5e358a7a4672b25541c9db7743fcd587
3,657,690
import inspect import re def _dimensions_matrix(channels, n_cols=None, top_left_attribute=None): """ time,x0 y0,x0 x1,x0 y1,x0 x0,y0 time,y0 x1,y0 y1,y0 x0,x1 y0,x1 time,x1 y1,x1 x0,y1 y0,y1 x1,y1 time,y1 """ # Generate the dimensions matrix from the docstring. ds = i...
2c119c74e7e37827d6813437d9e0d8bbd97cbbc7
3,657,691
def is_monotonic_increasing(x): """ Helper function to determine if a list is monotonically increasing. """ dx = np.diff(x) return np.all(dx >= 0)
6d0afe3a6a70d57ec4ae09e20164c34c0739855f
3,657,692
import copy def cluster_size_threshold(data, thresh=None, min_size=20, save=False): """ Removes clusters smaller than a prespecified number in a stat-file. Parameters ---------- data : numpy-array or str 3D Numpy-array with statistic-value or a string to a path pointing to a nifti-fil...
3b946a639e2dae1c47fb78ad30dded32b0dd5f06
3,657,693
def convert_df(df): """Makes a Pandas DataFrame more memory-efficient through intelligent use of Pandas data types: specifically, by storing columns with repetitive Python strings not with the object dtype for unique values (entirely stored in memory) but as categoricals, which are represented by repeated...
7f6f2c20762963dceb0f52d36b7b724c5a89d8d4
3,657,694
def run_add(request): """Add a run.""" if request.method == "POST": form = forms.AddRunForm(request.POST, user=request.user) run = form.save_if_valid() if run is not None: messages.success( request, u"Run '{0}' added.".format( run.name) ...
c1eca5702e93e3a0751b2b22de18aa1aa4c88db7
3,657,695
def map_aemo_facility_status(facility_status: str) -> str: """ Maps an AEMO facility status to an Opennem facility status """ unit_status = facility_status.lower().strip() if unit_status.startswith("in service"): return "operating" if unit_status.startswith("in commissioning"): ...
43e1d5e5ea984d36260604cf25f4c7b90d5e56f1
3,657,696
def demand_monthly_ba(tfr_dfs): """A stub transform function.""" return tfr_dfs
74bbb3d732b64a30f0529f76deedd646cc7d4171
3,657,697
def render_page(page, title="My Page", context=None): """ A simple helper to render the md_page.html template with [context] vars, and the additional contents of `page/[page].md` in the `md_page` variable. It automagically adds the global template vars defined above, too. It returns a string, usuall...
fd2e427f096324b2e9a17587f498626a2ebfb47e
3,657,698
def _SortableApprovalStatusValues(art, fd_list): """Return a list of approval statuses relevant to one UI table column.""" sortable_value_list = [] for fd in fd_list: for av in art.approval_values: if av.approval_id == fd.field_id: # Order approval statuses by life cycle. # NOT_SET == 8 ...
15ce3c6191495957674ab38c2f990d34f10ecdf6
3,657,699