content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def downscale(box, side, fill_color, background): """Downscales box by considering each box of length side as one pixel. If a downscaled pixel contains more than on color this returns None""" if side == 1: return None w, h = int(box.shape[0] / side), int(box.shape[1] / side) Y = np.full((w...
0a7340f7598941199c3913753867ba26fa9d63ab
43,100
import attr def switch_passive(tokenized): """Passive verbs are modifying the phrase before them rather than the phrase following. For consistency, we flip the order of such verbs""" if all(not t.match(tokens.Verb, active=False) for t in tokenized): return tokenized converted, remaining = [], ...
c6f7a22439f2b0953337c40f9a61380968c034b3
43,101
def unbox_unicode_str(typ, obj, c): """ Convert a unicode str object to a native unicode structure. """ ok, data, length, kind, is_ascii, hashv = \ c.pyapi.string_as_string_size_and_kind(obj) uni_str = cgutils.create_struct_proxy(typ)(c.context, c.builder) uni_str.data = data uni_str...
cf8a9aa9229ae7ceabd1e31424b45667a6602724
43,102
import torch def get_encoded_batch(sentence, lang_obj, use_cuda): """ accepts only bsz = 1. input: one sentence as a string output: named tuple with vector and length """ sentence = sentence + ' ' + global_variables.EOS_TOKEN; tensor = lang_obj.txt2vec(sentence).unsqueeze(0) device = torch.device('cuda') if...
a252c8d9af596afdcc0eeaa6e51a06a19996b1b1
43,103
from typing import List def ensure_topological_order(nodes: List[base_node.BaseNode]) -> bool: """Helper function to check if nodes are topologically sorted.""" visited = set() for node in nodes: for upstream_node in node.upstream_nodes: if upstream_node not in visited: return False visite...
56d71c306c809bae87c428607a17e91a82f5147f
43,104
import trace def eval_wavefront(opt_model, fld, wvl, foc, image_pt_2d=None, num_rays=21, value_if_none=np.NaN): """Trace a grid of rays and evaluate the OPD across the wavefront.""" fod = opt_model['analysis_results']['parax_data'].fod ref_sphere, cr_pkg = trace.setup_pupil_coords(opt_m...
8dc1c5d9aade54577e86e9f087fb0fd34eed6ec9
43,105
def _ArrayToVec3(vec3): """Convert an array of three doubles into a simple_aero.Vec3.""" if len(vec3) != 3: raise Vec3FormatException(vec3) c_vec3 = simple_aero.Vec3() c_vec3.x = vec3[0] c_vec3.y = vec3[1] c_vec3.z = vec3[2] return c_vec3
ae060783f923378cd555f94d25bfc98c8ea536a8
43,106
import importlib def get_storage(request): """ Gets a Credentials storage object provided by the Django OAuth2 Helper object. Args: request: Reference to the current request object. Returns: An :class:`oauth2.client.Storage` object. """ storage_model = oauth2_settings.storage_...
939f8e9f9db2e1f2a3624532fe7c70c00bd0a475
43,107
import copy def default_field(obj, **kwargs): """ returns field object that can handle default factory functions properly """ return field(default_factory=lambda: copy.copy(obj), **kwargs)
48b10596c443bd37f0391c4b28fa0e8a14e51b51
43,108
def is_visited(state, visited): """ Determines whether a State has already been visited. Args: state: visited: Returns: """ for visited_state in visited: if state.shore == visited_state.shore and state.boat == visited_state.boat: return True return False
567f85b63533188d58df4923e7e3a2a72da14943
43,109
def bf_get_snapshot_input_object_stream(key, snapshot=None): # type: (Text, Optional[Text]) -> Any """Returns a binary stream of the content of the snapshot input object with specified key.""" return restv2helper.get_snapshot_input_object(bf_session, key, snapshot)
2d19a845f639eeb4b90c5b3aa76078974fc7a008
43,110
def supplierProducts(supplierId): """ Lists out all of the supplier products with the ability to modify list and delist products into the master database. :param supplierId: The supplier id. """ page = escape(request.args.get("page")) limit = request.args.get("limit") if not limit o...
c902216fa83cfd0347ed9f2590d1ceba28584999
43,111
def bprop_scalar_to_array(x, out, dout): """Backpropagator for primitive `scalar_to_array`.""" return (F.array_to_scalar(dout),)
16bc8fdabdb9a682f0dd9605a7f4c3530983f3b2
43,112
def get_sequences(psms: np.recarray, db_seqs:np.ndarray)-> np.ndarray: """Get sequences to add them to a recarray Args: psms (np.recarray): Recordarray containing PSMs. db_seqs (np.ndarray): NumPy array containing sequences. Returns: np.ndarray: NumPy array containing a subset of s...
c066d524f4dd2cf583ac715dfd85a14343dc41de
43,113
def dual_basis_hamiltonian(n_dimensions, system_size, plane_wave=False, spinless=True): """Return the plane wave dual basis hamiltonian with the given parameters. Returns: the Hamiltonian as a normal-ordered FermionOperator. Args: n_dimensions (int): The number of dimens...
c3155855fb5fc49642c2cdf80d08e6151ba9fe45
43,114
def get_subject_for_cell(row_num, row, column_spec, table_about_url, shared_subject, column_info): """ Get the subject for the given cell.""" if column_spec["aboutUrl"]: return apply_all_subs(column_spec["aboutUrl"], row_num, row, column_info) elif table_about_url: return apply_all_subs(tabl...
dc2658d296529affabfb1ed4dd8cf2833655fd1c
43,115
from typing import Sequence from typing import Optional from functools import reduce def merge_confs( filenames: Sequence[PathLike], default: Optional[str] = "defaults.yml" ) -> Configuration: """ Merge configurations in given files. :param filenames: files to merge :param default: default config...
f528383fd620cb6177b2912ebb3abc32a09543a7
43,116
def add_product(body): """ Added a new Product :param body: Product object that needs to be added to the db. :type body: dict | bytes :rtype: AddProductResponse """ return Products.add_product(connexion)
cb5291670070f2d672979883bc8491dadfd5d272
43,117
def sineFit(wavelength,frequency,amplitude,phase,offset): """ A sine fit function of wavelength, frequency, amplitude, and phase. """ return amplitude * np.sin(frequency * (wavelength - phase)) + offset
6acf485936323a6fa6911a841180543b028b1ba2
43,118
from typing import Any from typing import Tuple import torch import contextlib def cast_floats_to_right_precision(to_fp16: bool, no_grad: bool, *args: Any, **kwargs: Any) -> Tuple[Any, Any]: """ Cast floating point Tensors in *args or **kwargs to FP16 or FP32 if they are not. We also retain the requires_g...
fe31c1751da0bff5e12801a19987e35700567bb0
43,119
def _BuildIsCompleted(build_dict, build_num): """Determine whether build was completed successfully. Get the build test status. Check whether the build given by |build_num] was terminated by an error, or is not finished building. If so, return None. Otherwise, return the build test status dictionary. Args: ...
4007a7948327b9f59b20677eb5505d3b170b3cb2
43,120
def extract_columns(myfile): """Returns the columns of a space separated file as a list let the file be: a b c d e f g h i the function will return: [(a,d,g), (b,e,h), (c,f,i)] """ lines = extract_lines(myfile) zipped = zip(*lines) return list(zipped)
4ccb474d437fc7bf3857813307f9d68b359a651b
43,121
import os def trim(filename, output_dir=None, duration=None): """Takes a single audio file, and standardizes it based on the parameters provided. Heads up! Modifies the file in place... Parameters ---------- filename : str Full path to the audio file to work with. output_dir : s...
6b10bc4e2033df07c43fd5b38d194e50b3ba8de9
43,122
def assign_label(cross_nn, ref_nn, ref_labels, how='mode'): """ Assign label to projected cells based on the labels among their nearest neighbors in the reference dataset. Parameters ---------- cross_nn dense numpy array or scipy sparse array (csr) with projected cells as rows and ...
4fd0db429ddab8ee084acafe9fb0cb5fbc7c2001
43,123
def parse_floatingips_to_add(floatingips): """ Parse "floatingips" values :param dict floatingips: Floating ips :rtype: dict (region, quantity) """ result = defaultdict(lambda: 0) for ip in floatingips: result[ip.get("region")] += ip.get("quantity") return result
0166f9ca469c49051c3c08e2941c3164d6aa736c
43,124
def edit_profile(): """ TODO """ token = request.cookies.get(TOKEN_COOKIE_NAME) token_decoded = jwt.decode(token, SECRET, algorithms=['HS256'], verify=True) subject = token_decoded['subject'] user = registry.get_user(subject=subject) return_url = request.args.get('return_url') form =...
e3bef6045abf8530b6b1ca5143d17cd51d6f47dd
43,125
def rgs_var(g, h, xoff, yoff): """Radiographs and variance with xoff and yoff offsets""" gx0, hx0 = xoff, 0 if xoff < 0: gx0, hx0 = 0, -xoff nx = min(g.rg.shape[0]-gx0, h.rg.shape[0]-hx0) gy0, hy0 = yoff, 0 if yoff < 0: gy0, hy0 = 0, -yoff ny = min(g.rg.shape[1]-gy0, h.rg.sha...
17ebaecb34be1c67cb9454117097b574ce14998e
43,126
from vrml import node def setExternalURL( cls, url ): """Set the externproto URL associated with a prototype""" return node.Node.externalURL.fset( cls, url )
1ef4549285b30dfd9ee853b395440b6a0f3be777
43,127
from typing import Union def load_fs(root: Union[FS, str]) -> FS: """If str is supplied, returns an instance of OSFS, backed by the filesystem.""" if isinstance(root, str): return pyfs.open_fs(root, create=True) if isinstance(root, FS): return root raise Exception("Not a filesystem or path!")
0b40f506b0a8624f3b7ab326e965d60d1030f726
43,128
def _getcontextrange(context, config): """Return the range of the input context, including the file path. Return format: [filepath, line_start, line_end] """ file_i = context['_range']['begin']['file'] filepath = config['_files'][file_i] line_start = context['_range']['begin']['line'][0] ...
8367049c450e8d7345478aa71efb2e97e07438f6
43,129
def prepare_email_content(runresult, subject_name): """ :param runresult: 生成的简要分析结果 :param subject_name: html名称 :return: email conetnt """ batch_result = {} batch_result['report_name'] = subject_name batch_result["tasks"] = runresult["tasks"] batch_result["pass_task"] = runresult["pa...
b8cff0dd6d40eb295015d6631e56448c21259141
43,130
def sample_recipe(user, **params): """create a dictionnary of a recipe object.""" defaults = { 'title': 'Pitimi ak Pwa Kongo', 'time_minutes': 10, 'price': 5.00, 'description': 'Manje Ayisyen' } defaults.update(params) return Recipe.objects.create(user=user, **default...
dc51f8679bd12ac3f0b892f6a2c87fe7c7a94156
43,131
def approx_match(stations, name): """ :param stations: dict เก็บข้อมูลพิกัดและอุณหภูมิของสถานีต่าง ๆ ในรูปแบบที่อธิบายมาก่อนนี้ :param name: เป็นสตริง :return: คืนลิสต์ที่เก็บชื่อสถานีที่มีตัวอักษรใน name เป็นส่วนหนึ่งของชื่อสถานี โดยไม่สนใจว่าเป็นตัวพิมพ์เล็กหรือใหญ่ และไม่สนใจเว้นวรรคภายในด้วย (ชื...
42338574242c7b866917e8480bc4accd4e569133
43,132
def update_widget(request): """ Update single Widget """ result = {} widgets = get_sidebar_widgets() widget_id = request.POST.get('widget_id', 0) try: widget_item = SidebarWidget.objects.get(pk=widget_id) except SidebarWidget.DoesNotExist: return result else: widget...
3c78d1d4cd3ea75559633811f4e8c9173928a1e9
43,133
import random def simulate(cycles, initSize, offspring, lifespan, crisprFems, popLimit): """ cycles: the number of cycles this simulation will run. initSize: the initial size of the population. offspring: max number of possible children per reproduction. lifespan: maximum lifespan of an in...
b52422afa689ac613c34514669b0438fe38ef692
43,134
def rpn_graph(feature_map, anchors_per_location, anchor_stride): """ Region Proposal Network hesaplama grafiğini oluşturur. feature_map: omurga özellikleri [toplu iş, yükseklik, genişlik, derinlik] anchors_per_location: özellik haritasındaki piksel başına çapa sayısı anchor_stride: Çapa yoğunluğunu ...
451507842b4af89bd8bfb9e0bf1b1dfa6d599868
43,135
def get_xml_schema_type(): """ Get xml schema type. """ return '{http://www.w3.org/2001/XMLSchema-instance}type'
1704b7d6227cd88836f4a55488445192bf63c9aa
43,136
def main_log_set(): """ メインの統計処理をあれこれする所 """ # 身内村判定 def get_local_villager(vill_name): for ng_word in ['ダンガンロンパ', 'ダンロン', 'RP', 'なんJ', '身内', 'クッキー', 'ク☆']: # 除外する村名リスト if ng_word in vill_name: return True return False # 設定変数 target = dict() ...
841158e74ff7d0a0f255af30a9758699d59aab23
43,137
def _get_state(ipaclient, idnsname): """Return set of currently defined SRV records.""" current = set() result = ipaclient.get_dns_record(idnsname)['result']['result'] for item in result: for record in item.get('srvrecord', []): _w, _p, port, host = record.split() current...
5c77c6c741e1a8260a00539432e857633ed44011
43,138
from typing import Tuple def locate_max_drawdown(returns: pd.Series) -> Tuple[pd.Timestamp, pd.Timestamp, float]: """ 寻找最大回撤周期 :param returns: 收益序列, 已时间为 ``index`` :return: (最大回撤开始时间, 最大回撤结束时间, 最大回撤比例) """ if len(returns) < 1: raise ValueError('returns is empty.') cumulative = empyri...
7eb88ee86aa2475df5d8e99b4bc905dc9fb76d2a
43,139
async def make_result_embed(vote, results): """ Create a discord.Embed object from a set of results for a vote :param vote: the vote the results are for :param results: the results from the vote :return: discord.Embed object to send """ embed = discord.Embed(title=f"{vote.title} Results:") ...
e22f7f82ea63db0ba9740c0dec8636f24a74e7c5
43,140
def count_bits_above(string: int, pos: int) -> int: """Return the number of set bits higher than the position Args: string (int) - bit string pos (int) - position in the bit string """ return count_bits(string & ~(2**(pos + 1) - 1))
2ec723cb756eaad386211a83e2467c3624dc6397
43,141
def GetEquivalentPatchsets(host, project, change, patchset): """Gets equivalent patchsets that are applicable for sharing coverage data. The reason why this is not just the current patchset number is because there may have been a succession of "trivial" changes before the current patchset. Args: host (str...
db8f193ed2b7f59820401f0b19431620d14cda33
43,142
def to_int(value): """Convert to integer""" return value & 0xFF
9045a7857dae407a196ccb29a142a8e243476b03
43,143
def remove_ephemeral_entry(self): """Return index of the new entry to be added. The view must be in edit mode, with 'adding_new=True'. We may or may not have included whatever the user entered as a new entry in 'body', depending on whether what the user entered satisfies the entry syntax. If yes, then...
40aa625606764d9e1649553035c69686abeacd8b
43,144
def get_P_fan_rtd_C(V_fan_rtd_C): """(12) Args: V_fan_rtd_C: 定格冷房能力運転時の送風機の風量(m3/h) Returns: 定格冷房能力運転時の送風機の消費電力(W) """ return 8.0 * (V_fan_rtd_C / 60) + 20.7
52c3d887e2c1a9daaedaacfea28207cc31a14d81
43,145
from datetime import datetime def generate_timestamp(now=None): """Generate an enhanced CDBS-style uniqname.""" if now is None: now = datetime.datetime.utcnow() if now.year < 2016: year = chr(now.year - 2015 + ord('z')) elif 2016 <= now.year <= 2025: year = chr(now.year ...
269ab4206d4a3643ad6d5d1f3d4f50e9f3de06ad
43,146
def crop_2d(pts2d, Prect, bounds): """ Expects 2D coordinate points and a dict of bounds of traffic signs """ min_x = bounds['x'] - bounds['w'] max_x = bounds['x'] + bounds['w'] min_y = bounds['y'] - bounds['h'] max_y = bounds['y'] + bounds['h'] # print(min_x) # print(max_x) # print(min_y) # print(max_y) ...
2c218c518cd7a56bcb2c6ca87f9548d8ecc32c78
43,147
def covid_mask_habit(A_1, A_2, D_inverse, a_1, t_2, t_3, b_1, b_2, p, alpha, beta, r, k, habit_p): """ Description ----------- This funciton simulate the spread of two contagions on two different networks, where contagions are correlated as described in the project report. ...
93f6836cc223c151a44682252e22334c403d1e0d
43,148
def _get_http() -> httplib2.Http: """ Provides an authorized HTTP object, one per thread """ if not hasattr(_tls, "_HTTP") or _tls._HTTP is None: http = httplib2.Http(timeout=_TIMEOUT) # Use application default credentials to make the Firebase calls # https://firebase.google.com/docs/ref...
815f01bf820f9584bb9e2e82e594b03c6615770a
43,149
async def read_rental_states(connection=Depends(get_db)): """ Fetches rental price average per state forecasted for next 2 years """ query = f""" SELECT state, price, date FROM forecasted_rentals_states; """ df = pd.read_sql(query, connection) if len(df) > 0...
3e34c16de1cec13411d50f70bd457d9d8e3e3099
43,150
from typing import Match def list_deleted_matches(): """Return paginated list of deleted matches. Params: page (int): Optional. Page number to return """ received = request.get_json() if received: page = received.get('page', 1) else: page = 1 # Query matches p...
82adb0aed70cdf44beb810d78ee64cc0529961bb
43,151
from datetime import datetime def api_post_by_id(id): """All user CRUD operations for one single post by ID""" cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) if "lost" in id: cursor.execute("SELECT * FROM lost_pets WHERE id=%s", [id]) else: cursor.execute("SELECT * FROM f...
432a985a7e9d26170576cc674d520d82cb861e83
43,152
from typing import List def preprocess_ical(text: str) -> List[str]: """ Removes VALARM ACTION:NONE from the iCal file (included in some events from Google Calendar) """ lines = text.splitlines() new_lines = [] i = 0 try: while i < len(lines): if lines[i] != "BEGIN:VALARM...
ad2d63cdb1f6883a56c48b2652ac19490c6c3f70
43,153
def yule_walker(X, order=1, method="unbiased", df=None, inv=False, demean=True): """ Estimate AR(p) parameters from a sequence X using Yule-Walker equation. Unbiased or maximum-likelihood estimator (mle) See, for example: http://en.wikipedia.org/wiki/Autoregressive_moving_average_model Param...
8c933c5e41778719244a1f477f941de844048a00
43,154
import logging import traceback def rtt_wrapper(args): """ wrapper for path() that enables trouble shooting in worker and multiple args""" try: return rtt(*args) except Exception: logging.critical("Exception in worker.") traceback.print_exc() raise
b9aa24cadaea47bc1d3b75be9c39b119dd6ec526
43,155
from typing import Dict from typing import Tuple def generate_financial_amount_replacement( token: Token, financial_amounts_encountered: Dict, percentage_financial_amount_variation: int, ) -> Tuple[str, Dict]: """ Generate replacements for an amount and currency based on previous amounts generated...
8ced5028369d6aba79d42053e8838460fd3d5819
43,156
from datetime import datetime def command_seen(bot, user, channel, args): """Displays the last action by the given user""" if not args: return bot.say(channel, "Please provide a nick to search...") table = get_table(bot, channel) # Return the first match, there shouldn't be multiples anyway ...
18476c83072aaa435dfa42f022a57f8e140a7580
43,157
def decode_parameters(data): """ :code-block 'parameters': [{ 'required': False, 'name': 'skip', 'allowEmptyValue': True, 'in': 'query', 'enum': [0, 1], 'type': 'integer', 'description': 'offset' }] """ q...
3bbdebd00ad1ceee8f3ec2d87e2b2d78b12defef
43,158
def rotate_180_bm8(bits: int) -> int: """ bit matrixの180度回転 Parameters ---------- bits : int 対象となるbit matrix """ return flip_horizontal_bm8(flip_vertical_bm8(bits))
5e3f6cf618f39cc9eef5f3f6cc4c8532d7bd66aa
43,159
import requests def delete(url: str, data: dict, header: dict): """ Issue request Param 1 - url Param 2 - data Param 3 - header Return - response object """ res = requests.delete(url, json=data, headers=header) ret = {'status_code': res.status_code} try: ret['response'...
900076b53b439655d304daf10a015b560ad2a8c6
43,160
def abspath_from_egg(egg, path): """Given a path relative to the egg root, find the absolute filesystem path for that resource. For instance this file's absolute path can be found invoking `abspath_from_egg("dallinger", "dallinger/utils.py")`. Returns a `pathlib.Path` object or None if the path was ...
887ca007cd0692ba334e78109b9aaaca6bcff8d4
43,161
import pathlib def get_tldname(): """look in /etc/hosts or /etc/hostname to determine the top level domain to use """ basename = tldname = '' with open('/etc/hosts') as hostsfile: for line in hostsfile: if not line.strip().startswith('127.0.0.1'): continue ...
5f1c4f7f63d0ffbd39a05d9529bffabaa2c5d216
43,162
def get_converter(content_type): """Returns converter object. All converter objects should have convert method. Parameters: content_type the type of content to check for a converter """ return CONVERTERS[content_type]
26d20366e7f16ec52403adc116a21fe38359a7fc
43,163
import os def gcp_cli(parser): """ Extend a parser with the GCP options """ parser.add_argument("--bucket", help="Storage account to write image to", default=os.environ.get("GCP_BUCKET")) parser.add_argument("--gce", help="Use...
7a31a3363863d8f4a4a6da1c33c335a1c6d69273
43,164
def proper_case(package_name): """Properly case project name from pypi.org.""" # Hit the simple API. r = _get_requests_session().get( "https://pypi.org/pypi/{0}/json".format(package_name), timeout=0.3, stream=True ) if not r.ok: raise IOError( "Unable to find package {0} ...
8c79751f3574850c5503d3a37c66476e5215f977
43,165
def select_from(*args, **kwds): """ Returns :py:class:`~.Select` instance and passed arguments are used for list of tables. Columns are set to `*`. """ return Select().from_(*args, **kwds)
ea7afd8d55846393af4dce046eb576a5704d3c97
43,166
import functools def configurable(setting): """Return a function that only gets called if a setting is enabled.""" def decorator(func): @functools.wraps(func) def _configurable(*args, **kwargs): if settings[setting]: return func(*args, **kwargs) return _con...
451aeebb280b1d8d54b1eec0f521c6f959e31311
43,167
def rate_bucket(dataset, rate_low, rate_high): """Extract the movies within the specified ratings. This function extracts all the movies that has rating between rate_low and high_rate. Once you ahve extracted the movies, call the explore_data() to print first few rows. Keyword arguments: d...
540f72ead479041e29fba8467a5b8f41597b0cf2
43,168
def get_attributes(sitk_image): """Get physical space attributes (meta-data) of the image.""" attributes = {} attributes['orig_pixelid'] = sitk_image.GetPixelIDValue() attributes['orig_origin'] = sitk_image.GetOrigin() attributes['orig_direction'] = sitk_image.GetDirection() attributes['orig_spa...
0baf1153bf53529026ef205961903fa6695be389
43,169
import itertools def build_vocab(tokenized_src_trgs_pairs, opt): """Construct a vocabulary from tokenized lines.""" vocab = {} for src_tokens, trgs_tokens in tokenized_src_trgs_pairs: tokens = src_tokens + list(itertools.chain(*trgs_tokens)) for token in tokens: if token not in...
f2f7601f3e2dabd96376291866897e480e3b957f
43,170
def payback(cashflows): """The payback period refers to the length of time required for an investment to have its initial cost recovered. (This version accepts a list of cashflows) >>> payback([-200.0, 60.0, 60.0, 70.0, 90.0]) 3.1111111111111112 """ investment, ca...
0cbd06294b724ca4f356ca2fcb017026a6d660c8
43,171
import random import csv def generate_postal_code(chance=None, variation=False, row=None): """ Function to generate the postal code of the profile. Args: chance: Integer between 1-100 used for realistic variation. (not required) variation: Boolean value indicating whether variation is requested. (optional) ...
725732269489be408a1ce9bb465fe6b7a9528727
43,172
def vector_by_axis(axis, origin): """ Create a vector along the specified axis. :param str axis: Axis ('x', 'y', or 'z'). :param array_like origin: Origin of vector. :return: Vector along specified axis. :rtype: :class:`.Vector` """ if not isinstance(origin, Point): origin = Po...
fe8b3daf8511002818486c609ee02b99e69413df
43,173
def daily_statistics(cube, operator='mean'): """ Compute daily statistics. Chunks time in daily periods and computes statistics over them; Parameters ---------- cube: iris.cube.Cube input cube. operator: str, optional Select operator to apply. Available operators: ...
7bada8c8091358eba5eec1aa0f268bfbd8883037
43,174
import sys def checkChangeLog(message): """ Check debian changelog for given message to be present. """ for line in open("debian/changelog"): if line.startswith(" --"): return False if message in line: return True sys.exit("Error, didn't find in debian/chang...
7801a5207549a2ba48551c760f9d2781a79ed81e
43,175
def is_symmetric(t): """ Returns True if the root of t is a symmetric node, and False otherwise. If t is a leaf, it returns True: ex falso quodlibet. :return: `bool` instance. """ return t.is_leaf() or \ all(isomorphic(t.children[0], ch) for ch in t.children[1:])
6f0a116aaaa80c5ff19460a23cbdab98c66e5447
43,176
def fwdkin(robot, theta): """ Computes the pose of the robot tool flange based on a Robot object and the joint angles. :type robot: Robot :param robot: The robot object containing kinematic information :type theta: numpy.array :param theta: N x 1 array of joint angles. Must ha...
35116326097f51676db2579fac0ce208a516202a
43,177
import socket import sys def _locateNS(host=None, port=None, broadcast=True, hmac_key=None): """Get a proxy for a name server somewhere in the network.""" if host is None: # first try localhost if we have a good chance of finding it there if config.NS_HOST in ("localhost", "::1") or config.NS_...
1136affa6d68d34d65ed55ac61a409cc35288aa7
43,178
def lstm_attention_decoder(inputs, hparams, train, name, initial_state, encoder_outputs): """Run LSTM cell with attention on inputs of shape [batch x time x size].""" def dropout_lstm_cell(): return tf.contrib.rnn.DropoutWrapper( tf.nn.rnn_cell.BasicLSTMCell(hparams.hidden_si...
d84958cd0b8e4294422e0185912bee1f8a60e1c5
43,179
from typing import Any def check_non_linearity(item: Any) -> bool: """Evaluates whether "item" is a torch module :param item: variable to check :return: boolean """ return isinstance(item(), nn.Module) if item is not None else True
639796e25c7d73d895bd1ece159fbe8d7c591720
43,180
import numpy def mean_average_error(ground_truth, regression, verbose=False): """ Computes the mean average error (MAE). Args: ground_truth (list or 1-dim ndarray): ground truth labels. regression (list or 1-dim ndarray): label estimations. Must have the same length as the ground tru...
0bcc7fe67aa97dcf44595a6f2ef63ed242b29837
43,181
def calcFlashThresholds(loSampleData, hiSampleData): """\ Analyses light sensor sample data and returns suggestions for the thresholds needed to detect the flashes. :param loSampleData: list of sample values, where each value is the lowest seen during that sampling period :param loSampleData: list ...
a302a0291975434c506f8406293895e75ded24a4
43,182
def pmd_load_variance(pmd_map): """ Get load variance on a set of pmds. Parameters ---------- pmd_map : dict mapping of pmd id and its Dataif_Pmd object. """ pmd_load_list = list(map(lambda o: o.pmd_load, pmd_map.values())) return util.variance(pmd_load_list)
a7e7eddb622adabbc6bb29ee3b776457c96d5cea
43,183
import numpy def RDdispSurf(X, Y, P1, P2, P3, P4, opening, nu): """ RDdispSurf calculates surface displacements associated with a rectangular dislocation in an elastic half-space. """ bx = opening Vnorm = numpy.cross(P2-P1, P4-P1) Vnorm = Vnorm/norm(Vnorm) bX = bx*Vnorm[0] bY = b...
da7fa7f49bee83d5ecc3f83a1b208fcb90bba105
43,184
def coerce_human_date(d, datemode = None): """Attempt to coerce d into a Python datetime.date Generally d will have been retrieved from an excel spreadsheet, so I expect it to be a string or an excel date. Args: d - object to be coerced d...
0bebe31e8febd32958b12c2b5ee1378e1fc455a0
43,185
def check_vcf(variants): """Check if there are any problems with the vcf file Args: variants(iterable(cyvcf2.Variant)) Returns: nr_variants(int) """ logger.info("Check if vcf is on correct format...") nr_variants = 0 previous_pos = None previ...
3e73ea3fb3d7b39a7fcf5d1fb0ce93532e71314c
43,186
def merge_partial_elements(element_list): """ merges model elements which collectively all define the model component, mostly for multidimensional subscripts Parameters ---------- element_list Returns ------- """ outs = dict() # output data structure # needed to preserve ...
a971ffcd2fec407a1defc494928badbcb889c4a8
43,187
import requests def get_job_results(engagement_id: str, job_id: str): """Retrieve job results from S3 via authentication. :param engagement_id: str -- the engagement id :param job_id: str -- the job id to retrieve :returns: dict -- the query results """ job_results = query_job(engagement_id, ...
f2bccd4cf1fa358e3616ac54d3014a948628cf64
43,188
def has_external_refs(*args): """has_external_refs(func_t pfn, ea_t ea) -> bool""" return _idaapi.has_external_refs(*args)
a003614ac19177885e52ae3d8ba29371da3c3947
43,189
def bw_scott(x): """ Scott's Rule of Thumb Parameter --------- x : array-like Array for which to get the bandwidth Returns ------- bw : float The estimate of the bandwidth Notes ----- Returns 1.059 * A * n ** (-1/5.) A = min(std(x, ddof=1), IQR/1.349) ...
04a028617653f1a900c6f3c4077a7c208ec946ff
43,190
def get_bibliography(soup, file_path): """Read in a soup object and a path to that object on disk and return an object describing bibliographic data for that record""" bibliography_data = {} labels = ["printings", "citations"] bibliography = soup.find('div', {'id': 'Bibliographic'}) for o in bibliography...
e0b2f448845308a0743bb77b839aff0eeab31cc4
43,191
from typing import Union from pathlib import Path import base64 def read_as_base64(path: Union[str, Path]) -> str: """ Convert file contents into a base64 string Args: path: File path Returns: Base64 string """ content = Path(path).read_text() return base64.b64encode(cont...
bf4071662fd335882f50e10b72e7623d5e84d855
43,192
def estimate_affine_matrix(x1, x2): """ See https://github.com/YadiraF/face3d. """ x1 = x1.T; x2 = x2.T assert(x2.shape[1] == x1.shape[1]) n = x2.shape[1] assert(n >= 4) mean = np.mean(x2, 1) x2 = x2 - np.tile(mean[:, np.newaxis], [1, n]) average_norm = np.mean(np.sqrt(np...
46937834ab853b42b21142e4e09a76c8e06a3abc
43,193
def get_verifiers(stage, test_block_config, sessions, expected): """Get one or more response validators for this stage Args: stage (dict): spec for this stage test_block_config (dict): variables for this test run sessions (dict): all available sessions expected (dict): expected ...
4553de0e5a940610ea9a3f53afc0f3d9f1427a4d
43,194
def cms_scan(self): """ CMS component task """ blacklist = list(range(42, 55)) + [58, 106] blacklist = [IPv4Network(f"147.251.{x}.0/24") for x in blacklist] client = CMSClient(bolt=self.neo4j_addr, password=self.neo4j_passwd) res = client.get_ips_and_domain_names().value() stats = 0 ...
6d85c9da0693712cc1aa29ec914448426e76ad1c
43,195
def immerge(images, row, col): """Merge images. merge images into an image with (row * h) * (col * w) `images` is in shape of N * H * W(* C=1 or 3) """ if images.ndim == 4: c = images.shape[3] elif images.ndim == 3: c = 1 h, w = images.shape[1], images.shape[2] if c > ...
4cd93a891ba0ab4ae717dcba3f72177a8d65ef4b
43,196
def type_equals(e, t): """ Will always return true, assuming the types of both are equal (which is checked in compare_object) """ return True
7d394ab23369854476c91d85c4160cd177fa125f
43,197
def create_tenant() -> str: """Create Tenant.""" tenant, _ = Tenant.objects.get_or_create(name=TENANT_NAME) tenant.validated_save() return TENANT_NAME
3e31d23e70e1c6465663a367b187a7665047494f
43,198
def result_to_maybe( result_container: Result[_ValueType, _ErrorType], ) -> Maybe[_ValueType]: """ Converts ``Result`` container to ``Maybe`` container. .. code:: python >>> from returns.maybe import Some, Nothing >>> from returns.result import Failure, Success >>> assert result_to_...
8b21d6800a70d5ef755bf8a8a1975060b8c83d52
43,199