content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from datetime import datetime def parse_last_timestamp(df): """ Parse last timestamp from dataframe. Add one minute forward to prevent the script from fetching the same value. The last timestamp already in database, so we need to fetch the weather data one minute forward. """ if df.empty:...
2fe7430344229e89aab33ef47af944735b79c169
31,225
def NextLexem_OperatorPredicate(op_value): """ construct a predicate: lexem_list -> boolean which checks if the next lexem is an operator whose value macthes @p op_value (do not consume it) """ def predicate(lexem_list): if len(lexem_list) == 0: return False head_lexe...
caf2866e85a42bee2e7eab0355cad4568bde46de
31,227
import torch def optim_inits(objective, x_opt, inference_samples, partition_samples, edge_mat_samples, n_vertices, acquisition_func=expected_improvement, reference=None): """ :param x_opt: 1D Tensor :param inference_samples: :param partition_samples: :param edge_mat_samples: :p...
f048fc3290d890bc687f3176f66e5ad86dfa5141
31,228
def _pushb2phases(pushop, bundler): """handle phase push through bundle2""" if 'phases' in pushop.stepsdone: return b2caps = bundle2.bundle2caps(pushop.remote) if not 'pushkey' in b2caps: return pushop.stepsdone.add('phases') part2node = [] enc = pushkey.encode for newrem...
ff8f5c839919c6593e2d7d5cb98c477f8b2bc735
31,231
def predict_all(model, all_data): """ Predict odor probabilities for all trials. :param model: (keras) decoding model :param all_data: (4d numpy array) data of format [trial, window, neuron, time] :return: (3d numpy array) prediction of format [trial, time, odor] """ test = stack_data(all_d...
5bc748f6eddc4e6791601b87ff73a000a72efa4c
31,232
def normalize(X): """Normalize the given dataset X Args: X: ndarray, dataset Returns: (Xbar, mean, std): tuple of ndarray, Xbar is the normalized dataset with mean 0 and standard deviation 1; mean and std are the mean and standard deviation respectively. Note: ...
5db71253b148387663b8575cf4df086cd182fbff
31,233
def get_lat_lon(exif_data): """Returns the latitude and longitude, if available, from the provided exif_data (obtained through get_exif_data above)""" lat = None lon = None if "GPSInfo" in exif_data: gps_info = exif_data["GPSInfo"] gps_latitude = _get_if_exist(gps_info, "GP...
d653dd84cd47efb2063db724cf7a88fa3f2a7490
31,234
def reduce_dimensions(df, reduce_cols=None, n_components=2): """ given a dataframe, columns to reduce and number of components for dimensionality reduction algorithm returns a dictionary of reduction algorithm to it's name and reduced df. dimensionality reduction or dimension reduction is the process o...
39c5bf6257da93f449dc4081fde98ecd18465a0f
31,237
import numpy import math def _dct_or_dst_type3( x, n=None, axis=-1, norm=None, forward=True, dst=False, overwrite_x=False ): """Forward DCT/DST-III (or inverse DCT/DST-II) along a single axis. Parameters ---------- x : cupy.ndarray The data to transform. n : int The size of th...
7e617e478c38ea47767a259df74581c960bfcaff
31,238
def indi_events(person, tags=None): """Returns all events for a given individual. Parameters ---------- person : `ged4py.model.Individual` GEDCOM INDI record. tags : `list` [ `str` ], optional Set of tags to return, default is all event tags. Returns ------- events : `l...
632a532ddcf6d187d1a9f8a5cf7b4451b3d73f37
31,239
def encrypt(key, plaintext): """Encrypt the string and return the ciphertext""" return ''.join(key[l] for l in plaintext)
0dc693fe1357756fdfee21cbc847fc6929dab2d1
31,240
from re import T def rename_keys( mapping: T.Dict[str, T.Any], *, prefix: T.Optional[str] = None, suffix: T.Optional[str] = None ) -> T.Dict[str, T.Any]: """Renames every key in `mapping` with a `prefix` and/or `suffix`. Args: mapping (T.Dict): Mapping. prefix (str, optional):...
fdfc335354e0ccf36c5416159927b7ffe8e5aec9
31,241
def any_root_path(path): """Rendering the React template.""" return render_template('index.html')
ba1069e4e52f2388b7a68129fa6ee7a4701ce31b
31,242
def getChartdata(): """ 获取图表数据 params: request return: response """ data = {'staff': {}} data['staff']['is_worker'] = Staff.query.filter(Staff.is_leave==True).count() data['staff']['not_worker'] = Staff.query.filter(Staff.is_leave==False).count() data['staff']['total_worker'] = data[...
70dcee23ca8e55ab8500e6ca56d44216aea69f95
31,243
def md_to_html(content): """ Converts markdown content to HTML """ html = markdown.markdown(content) return html
16c67405d35b1119e2f52708aed26ad2f3f23244
31,244
import logging def userdata_loader(s3_training_bucket='', trainer_script_name='trainer-script.sh'): """ Given the filepath for the trainer-script, load and return its contents as a str. :param s3_training_bucket: :param trainer_script_name: :return: """ try: # If the user didn't p...
9ed6bf1c4cb252c855acf4ed943f3c8ce2a07952
31,245
def timer(string,i,f): """ Takes in: i = starting time; f = finishing time. Returns: Time taken in full minutes and seconds. """ sec = f - i # Total time to run. mins, sec= divmod(sec, 60.0) time = string+' time: '+str(int(mins))+'min '+str(int(sec))+'s' print(time) ...
cbb3c857160a4cbade7a02311455737b1e6e89ef
31,246
def format_server_wrs(world_records, server_id): """Format the world records on the server browser to a table world_records format: {server_id: [list of records]} where every record is a tuple like {map_name, mode, date, time, player_name, steam_id, rank} accessible like sqlalchemy result""" if ...
eef6be19b13694e8e7c7bf33d833c2f74960ad95
31,247
from pathlib import Path def clean_file(path=Path('data') / 'Fangraphs Leaderboard.csv', level='MLB', league='', season='', position=''): """Update names for querying and provide additional context. Args: level (str): the minor/major leave level selected. Default MLB. league (s...
4b01de07630f694c4b5a8010036b6394bed414ec
31,248
def TextRangeCommandStart(builder): """This method is deprecated. Please switch to Start.""" return Start(builder)
dacf2fdb830f0fdfc5951288730963e3deb77741
31,249
import random def ai_derp(gstate: TicTacToe, *args): """AI that randomly picks the next move""" return random.choice(list(gstate.next_moves.keys()))
bfa1521c4bc2d4dad79a9f91b6bfed14b872f918
31,250
def get_logits_img(features, n_classes, mode, params): """Computes logits for provided features. Args: features: A dictionary of tensors that are the features and whose first dimension is batch (as returned by input_fn). n_classes: Number of classes from which to predict (i.e. the number ...
e4170d31949c531c54021b6a17c9cbd6306175eb
31,251
def ccnv(pad=0): """Current canvas""" global _cnvs if pad == 0: return _cnvs[-1] _cnvs[-1].cd(pad) return _cnvs[0].GetPad(pad)
121f61661ea2a7d9ae941503c3bc2caa29f86dbd
31,252
import functools import unittest def NetworkTest(reason='Skipping network test'): """Decorator for unit tests. Skip the test if --network is not specified.""" def Decorator(test_item): @functools.wraps(test_item) def NetworkWrapper(*args, **kwargs): if GlobalTestConfig.NETWORK_TESTS_DISABLED: ...
f694902249d38be4d897ac20d47a23eb9ce10223
31,253
from typing import Dict from typing import Any def azure_firewall_network_rule_collection_update_command(client: AzureFirewallClient, args: Dict[str, Any]) -> CommandResults: """ Update network rule collection in firewall or policy. Args: c...
4d3d5ac09d345d661b2ef258ba2d6311c0f5b764
31,254
from typing import Optional def get_stream(id: Optional[str] = None, ledger_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetStreamResult: """ Resource schema for AWS::QLDB::Stream. """ __args__ = dict() __args__['id'] = id _...
244721f3424c8de4c923b8eb57c96429c028280d
31,255
def _is_course_or_run_deleted(title): """ Returns True if '[delete]', 'delete ' (note the ending space character) exists in a course's title or if the course title equals 'delete' for the purpose of skipping the course Args: title (str): The course.title of the course Returns: ...
c32c69e15fafbc899048b89ab8199f653d59e7a8
31,256
def copy_installer_dict(installer_dict, default_installer): """Copy installer dict. The installer rules themselves are not deep-copied. 'default_installer' installer names are replaced according to ``default_installer``. :param str default_installer: name of the default installer """ resu...
1bae37f603b0ac36b80e433b44722245f5df0090
31,257
import numpy def pbg_dispersion_1d_imre( results, wave="p", size=(6,4), xlim=(-1, 1), ylim=(0, 1) ): """ Plots the photonic dispersion (Bloch wavevector) of a photonic crystal structure, computed for a range of frequencies (wavelengths) and one angle of incidence. ...
d1c8605e1255669b31f9caf530f3c8669a2e03a6
31,258
from typing import OrderedDict def map_constructor(loader, node): """ Constructs a map using OrderedDict. :param loader: YAML loader :param node: YAML node :return: OrderedDictionary data """ loader.flatten_mapping(node) return OrderedDict(loader.construct_pairs(node))
21bf92d0c3975758ae434026fae3f54736b7f21d
31,259
def index(): """首页""" return redirect(url_for('site.hot'))
816585c515c254929fdbd0f8e2c0af99c73f9f9d
31,260
def tpr(df, label_column): """Measure the true positive rate.""" fp = sum((df['predictions'] >= 0.0) & (df[label_column] > 0.5)) ln = sum(df[label_column] > 0.5) return float(fp) / float(ln)
62cd3908f5e8490c507b2b320a8a453aa861f77d
31,261
from typing import Optional def get_pathway_names( database: str, pathway_df: pd.DataFrame, kegg_manager: Optional[bio2bel_kegg.Manager] = None, reactome_manager: Optional[bio2bel_reactome.Manager] = None, wikipathways_manager: Optional[bio2bel_wikipathways.Manager] = None ): ...
40397aa26fc90b06f21fe30605ef654b14a98662
31,262
from pathlib import Path def gather_rgi_results(rgi_sample_list: [RGIResult], outdir: Path) -> tuple: """ Symlinks RGI result files to a single destination folder -- required for rgi heatmap command :param rgi_sample_list: List containing RGIResult object instances :param outdir: Destination directory...
664172d0d6de5619c7f92ba74a5f3673726aedf9
31,263
from connio.rest.api.v3.account.propertyy import PropertyInstance def retention(retention): """ Serialize a retention object to retention JSON :param retention: PropertyInstance.Retention :return: jsonified string represenation of obj """ if retention is values.unset or retention is None...
38762297e80c434ce3e561731850b40137a16fdb
31,264
def get_tool_path(loader, node): """ yaml tag handler to access tools dict at load time """ py_str = loader.construct_python_str(node) return py_str.format(**tools)
22e2d82e428e376b31082b213a50d7ed33a5045f
31,265
def _get_oath2_access_token(client_key, client_secret): """ Query the vistara API and get an access_token """ if not client_key and not client_secret: log.error( "client_key and client_secret have not been specified " "and are required parameters." ) retu...
2be67e8305aac64f3cf39517e64efa7659100bf5
31,266
def sanity_check_dp(A_org, XW, U, L, delta_l, delta_g, check_symmetry=True, \ activation='linear'): """ Sanity approach for solving min_{A_G^{1+2+3}} F_c(A) + np.sum(A.*L) param: A_org: original adjacency matrix XW: X...
21f51523b21c2ca94feddf4724d7848317054279
31,267
def quadratic_bezier(t, p0, p1, p2): """ :return: Quadratic bezier formular according to https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Quadratic_B%C3%A9zier_curves """ return (1 - t) * ((1 - t) * p0 + t * p1) + t * ((1 - t) * p1 + t * p2)
ac9319683afb5b156ac40ba24865d9bc04531917
31,268
def add_musician_genres(musician, genre_list): """Add genres to a musician's profile""" musician_genres = [] found_genres = Genre.query.filter(Genre.genre_name.in_(genre_list)).all() for genre in found_genres: musician_genre = MusicianGenre(genre_id=genre.genre_id, ...
2557498853b8ecb634c282db5c27d0772ae066a1
31,269
def test_eat_exceptions_normal_case(): """ If no exceptions, this wrapper should do nothing. """ @utils.eat_exceptions def test_function(x): return x assert test_function(1) == 1
ce16fff9511ac52b1e2ffb08305c839a1bb36b57
31,270
def delete_system_interface(api_client, interface_id, **kwargs): # noqa: E501 """delete_system_interface # noqa: E501 Delete System Interface # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> response = awa...
a6c4db5d1c5ea1674146a7d723b8cea5725dcd51
31,271
def IsPlacementGroupCompatible(machine_type): """Returns True if VMs of 'machine_type' can be put in a placement group.""" prefix = machine_type.split('.')[0] return prefix not in NON_PLACEMENT_GROUP_PREFIXES
4c5cd10e2f2024d93b676df87a6e531fb866c228
31,272
import binascii def create_public_key_from_b64(b64Key: bytes) -> X25519PublicKey: """Derive X25519 Private key from b64 ascii string""" public_bytes = binascii.a2b_base64(b64Key) loaded_private_key = X25519PublicKey.from_public_bytes(public_bytes) return loaded_private_key
8cdac21431ed278fb82cfc4c76379baec401e518
31,274
from re import T def im_detect_bbox(model, images, target_scale, target_max_size, device, captions=None, positive_map_label_to_token=None ): """ Performs bbox detection on the original image. """ if cfg.INPUT.FORMAT is not '': input_form...
a20c4eb8fb8b5cf37bc5ee59901504e3a03a1307
31,275
import warnings def jmap(g, H, ae0, be0, af0, bf0, max_iter=1000, tol=1e-4, rcond=None, observer=None): """Maximum a posteriori estimator for g = H @ f + e p(g | f) = normal(H f, ve I) p(ve) = inverse_gauss(ae0, be0) p(f | vf) = normal(0, vf I) p(vf) = inverse_gauss(af0, bf0) JMAP: maximizes...
82b1199dfbaf1ecc9811b0d3127d976304df576f
31,276
def get_chats(im): """This function gets the chatting messages. Arguments: im (PIL.Image.Image): Image object Return: Image object list (PIL.Image.Image). [0]: The most latest chatting message. e.g, The most below messages. """ return get_chat_msg(im)
b3d30ee36025866020e8b8ce4c1b1477c2950fa3
31,277
def state_field(value): """Fetch the pagination state field from flask.request.args. :returns: list of the state(s) """ states = istate.States.all() value = value.split(',') invalid_states = [state for state in value if state not in states] assert not invalid_states, \ _('State(s) "...
c7e3d31780994c46fc1e43fc3f4398a4e93e77f6
31,278
import torch def cal_smoothness_orig(var1_orig, var2_orig, var3_orig, io, args): """ Input: var1_orig, var2_orig, var3_orig: scalar tensors, original variances on the 3 principal orientations Return: smoothness_orig: scalar, original smoothness of this region (linearity/planarity/scattering, ...
4713aede2109c17deb917fb2f86f73142185a258
31,279
def format_size(size): """Format provided size in bytes in a human-friendly format :param int size: size to format in bytes :return: formatted size with an SI prefix ('k', 'M', 'G', 'T') and unit ('B') :rtype: str """ if abs(size) < 1000: return str(size) + 'B' for unit in ...
04d9099a99e7c4863ada898096829aed9f6d7fc1
31,280
def get_acl_permission(acl, complete_acl_list): """ This uses numpy's vectorized operations to quickly match the acl returned from the API, to the complete list of acls to get the description. """ index = -1 where_arrays = np.where(acl == complete_acl_list[:,0]) try: index = wher...
55dc256c75be9dfcf897fffc6a5842cc19dbf1d8
31,281
import torch def interface_script(mod_interface, nn_module): """ Makes a ScriptModule from an nn.Module, using the interface methods rule for determining which methods to compile. Args: mod_interface: the interface type that the module have nn_module: The original Python nn.Module th...
dcfe3b7710a353da53c3e3b3ee2d360a943b77dd
31,282
def create_call_error(message: str) -> str: """Create CallError serialized representation based on serialize Call. Raises ValueError if message is not type Call. CallResult and CallError don't require response. """ call: Call = unpack(message) if isinstance(call, Call): call_error: Call...
c30a5c50c8d43805b554e4b2002bdc73be568918
31,283
def filter_boxes(min_score, boxes, scores, classes): """Return boxes with a confidence >= `min_score`""" n = len(classes) idxs = [] for i in range(n): if scores[i] >= min_score: idxs.append(i) filtered_boxes = boxes[idxs, ...] filtered_scores = scores[idxs, ...] filtered_...
596c9ecab145df0d6a3a7f1da44898da27566b72
31,284
def recenter_image(im): """ """ n_height, n_width = im.shape com = nd.center_of_mass(im) if any(np.isnan(com)): return im im_center = im[(com[0]-n_height/2):(com[0]+n_height/2)] offset = [(n_height-im_center.shape[0]),(n_width-im_center.shape[1])] if offset[0]%2 > 0: h_odd = 1 else: h_odd = 0 if offse...
64a180c8ea67a8105a08e7c326cc92c6cf281803
31,285
from typing import Counter def cal_participate_num(course: Course) -> Counter: """ 计算该课程对应组织所有成员的参与次数 return {Naturalperson.id:参与次数} 前端使用的时候直接读取字典的值就好了 """ org = course.organization activities = Activity.objects.activated().filter( organization_id=org, status=Activity.Statu...
c2dff0f9b956c819170070116f4fda858f616546
31,286
def plot( self, fig=None, ax=None, is_lam_only=False, sym=1, alpha=0, delta=0, is_edge_only=False, edgecolor=None, is_add_arrow=False, is_display=True, is_show_fig=True, ): """Plot the Lamination with empty Slots in a matplotlib fig Parameters ---------- ...
b317fe6518b20cd266f035bbb6a6ff3e4de94e10
31,287
def usage_percentage(usage, limit): """Usage percentage.""" if limit == 0: return "" return "({:.0%})".format(usage / limit)
7caf98ddb37036c79c0e323fc854cbc550eaaa60
31,288
def all(numbered=False): """ Get all included stanzas. Takes optional argument numbered. Returns a dict if numbered=True, else returns a list. """ return dict(zip(range(1, 165 + 1), stanzas)) if numbered else stanzas
af61087223411f3d57ec2e35f048da9da41bf469
31,289
from tensorflow.python.ops import math_ops from tensorflow.python.framework import ops def cosine_decay(learning_rate, global_step, maximum_steps, name=None): """ """ if global_step is None: raise ValueError("global_step is required for cosine_decay.") with ops.name_scope(name, "CosineDe...
6f4395bf5ca38beb483f142acec91455e2a77ced
31,290
def parse_file_header_64(bytes): """Parse the ELF file header.""" e_ident = {} e_ident['EI_CLASS'] = get_bytes(bytes, 4) e_ident['EI_DATA'] = get_bytes(bytes, 5) endian = get_byte_order(e_ident['EI_DATA']) e_ident['EI_VERSION'] = get_bytes(bytes, 6) e_ident['EI_OSABI'] = get_bytes(bytes, 7) ...
1b4a5cbd8f9dad58dc8d8ad6bd6a87f65d7bad07
31,291
def _or (*args): """Helper function to return its parameters or-ed together and bracketed, ready for a SQL statement. eg, _or ("x=1", _and ("a=2", "b=3")) => "(x=1 OR (a=2 AND b=3))" """ return " OR ".join (args)
1162600b49acb57e3348e6281767ce2fb0118984
31,292
from typing import Dict def strip_empty_values(values: Dict) -> Dict: """Remove any dict items with empty or ``None`` values.""" return {k: v for k, v in values.items() if v or v in [False, 0, 0.0]}
982814edbd73961d9afa2e2389cbd970b2bc231e
31,293
import torch def dispnet(path=None, batch_norm=True): """dispNet model architecture. Args: path : where to load pretrained network. will create a new one if not set """ model = DispNet(batch_norm=batch_norm) if path is not None: data = torch.load(path) if 'state_dict' in d...
8229c4616148c771686edbb7d99217404c48e3f9
31,294
def apigw_required(view_func): """apigw装饰器 """ @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): request.jwt = JWTClient(request) if not request.jwt.is_valid: return jwt_invalid_view(request) return view_func(request,...
c0bd9105df47297ae0f7db418ac3260c93272488
31,296
def text_analysis(string: str, *, nlp) -> str: """Return a text analysed string. post-analysis sentences are separated by <sent> tags e.g., 'a sentence<sent>a second sentence<sent>a third. see https://spacy.io/usage/rule-based-matching#adding-patterns-attributes """ sents = [] doc = nlp(s...
6bd16be281237bd2f2001755ce06d056a2cd8fda
31,297
def wtr_tens(P, T): """Function to Calculate Gas-Water Interfacial Tension in dynes/cm""" #P pressure, psia #T temperature, °F s74 = 75 - 1.108 * P ** 0.349 s280 = 53 - 0.1048 * P ** 0.637 if (T <= 74): sw = s74 elif(T >= 280): sw = s280 else: sw...
acbf649a8dfe1302350b35f141afc09198470d8d
31,298
from typing import List def _decompose_move(event: MoveElements) -> List[MoveElements]: """ Decompose an event moving elements into a list of MoveElements events representing the same action. :param event: event to decompose :return: list of events representing the same action """ return ...
c3572a2b183219280b4f352a8ddc98cbdfb7aa43
31,299
import math def get_line_equation(segment_point0, segment_point1): """ Ax + By + C = 0 :param segment_point0: Point :param segment_point1: :return: A, B, C """ x0, y0 = segment_point0.px, segment_point0.py x1, y1 = segment_point1.px, segment_point1.py a, b, c = y1 - y0, x0 - x1, x...
9e0b35f2cac4c7a5835755878fd8aa5d32735699
31,301
def keep_lesser_x0_y0_zbt0_pair_in_dict(p, p1, p2): """Defines x0, y0, and zbt0 based on the group associated with the lowest x0. Thus the new constants represent the point at the left-most end of the combined plot. :param p: plot to combine p1 and p2 into :param p1: 1st plot to combine :param p...
4dc7c008e86606b4257980f59b12fc6a183e060f
31,302
from typing import List from typing import Dict from typing import Optional def build_csv_from_cellset_dict( row_dimensions: List[str], column_dimensions: List[str], raw_cellset_as_dict: Dict, top: Optional[int] = None, line_separator: str = "\r\n", value_separator: str...
b6f40a97f14da3c37d63b6bfd545dc95fa61240e
31,303
def get_stages_from_api(**kwargs): """ This is the API method, called by the appConfig.instantiate method """ resp = utils.request(utils.RETRIEVE, 'stages', kwargs) return utils.parse(resp)
03e6ae52b0e3e18bd107b5bf0069ccaa6c01b322
31,304
import numpy import numba def fill_str_array(data, size, push_back=True): """ Fill StringArrayType array with given values to reach the size """ string_array_size = len(data) nan_array_size = size - string_array_size num_chars = sdc.str_arr_ext.num_total_chars(data) result_data = sdc.str...
5dc586a7334bdae73145574fa9afb2f939f1808e
31,305
def _visible_fields(user_profile, user, configuration=None): """ Return what fields should be visible based on user's preferences :param user_profile: User profile object :param user: User object :param configuration: A visibility configuration dictionary. :return: whitelist List of fields to b...
43e9b0f03ebee891681a6c3cf7892c5dab36e5f0
31,306
def open_dataframe(): """ Function to open the dataframe if it exists, or create a new one if it does not :return: Dataframe """ print("Checking for presence of data file......") try: datafile = './data/data.csv' dataframe = pd.read_csv(datafile) print("File found.... loa...
8f6bbed1e57df7a1567863c4ecd3bc4656901727
31,307
import fnmatch def zipglob(sfiles, namelist, path): """Returns a subset of filtered namelist""" files = [] # cycle the sfiles for sfile in sfiles: # we will create a list of existing files in the zip filtering them # by the sfile filename sfile.zfiles = fnmatch.filter(namelist,...
818e9a7598ba0827616061bbfed80e345d1e22a5
31,309
def to_string(result: ValidationResult, name_col_width: int) -> str: """Format a validation result for printing.""" name = state_name(result.state) if result.failed: msg = ", ".join(result.error_details.strip().split("\n")) return f"❌ {name} {msg}" elif result.state.reward is None: ...
263e327e053e6aee06a936b24eaabc2dd9ef028a
31,310
def two_sum_v1(array, target): """ For each element, find the complementary value and check if this second value is in the list. Complexity: O(n²) """ for indice, value in enumerate(array): second_value = target - value # Complexity of in is O(n). https://stackoverflow.com/questions/...
0dcc3b4a10ac4c04cabd4ab09a9e71f739455f55
31,311
def worker_numric_avg(fleet, value, env="mpi"): """R """ return worker_numric_sum(fleet, value, env) / fleet.worker_num()
9906fb0c35b718a9da6c8d6d0e0a5a85da5cf28d
31,312
from typing import List from typing import Tuple from typing import Dict def build_graph( nodes: List[Tuple[str, Dict]], edges: List[Tuple[str, str, Dict]] ) -> nx.DiGraph: """Builds the graph using networkx Arguments --------- nodes : list A list of node tuples edges : list A...
0d0bbbfa96ddd5c170a2ec7e9fb06b964b997dd3
31,313
def table_exists_sql(any_schema=False): """SQL to check for existence of a table. Note that for temp tables, any_schema should be set to True.""" if not any_schema: schema_filter_sql = sql.SQL('AND schemaname = current_schema()') else: schema_filter_sql = sql.SQL('') return sql.SQL("""S...
2ea073d26705f218d2929c7a419ef61a05c4cced
31,314
def _process_json(data): """ return a list of GradPetition objects. """ requests = [] for item in data: petition = GradPetition() petition.description = item.get('description') petition.submit_date = datetime_from_string(item.get('submitDate')) if 'decisionDate' in it...
5d381b896cd237b7780f1c048ef3e8fc6dd8bb9a
31,315
def PaddingMask(pad=0): """Returns a layer that maps integer sequences to padding masks. The layer expects as input a batch of integer sequences. The layer output is an N-D array that marks for each sequence position whether the integer (e.g., a token ID) in that position represents padding -- value ``pad`` --...
146f4bb6b518b38c007a42ed78c7e0d344070dee
31,316
import yaml def python_packages(): """ Reads input.yml and returns a list of python related packages """ with open(r"tests/input.yml") as file: inputs = yaml.load(file, Loader=yaml.FullLoader) return inputs["python_packages"]
91889c21b1553f9b09c451913e658b458c4502d0
31,317
import asyncio def create_tcp_visonic_connection(address, port, protocol=VisonicProtocol, command_queue = None, event_callback=None, disconnect_callback=None, loop=None, excludes=None): """Create Visonic manager class, returns tcp transport coroutine.""" # use default protocol if not specified protocol =...
0db9e05db4035caf828d61c91799d3658c61b6e0
31,318
def metric_wind_dict_to_beaufort(d): """ Converts all the wind values in a dict from meters/sec to the corresponding Beaufort scale level (which is not an exact number but rather represents a range of wind speeds - see: https://en.wikipedia.org/wiki/Beaufort_scale). Conversion table: https://www.win...
b26ddb5e9c0423612a9c7086030fd77bbfa371ad
31,319
def add_favorite_clubs(): """ POST endpoint that adds favorite club(s) for student user. Ordering is preserved based on *when* they favorited. """ user = get_current_user() json = g.clean_json new_fav_clubs_query = NewOfficerUser.objects \ .filter(confirmed=True) \ .filter(...
1288e3d579dca54d25883fed4241b6fa1206f7f0
31,320
def death_rate_60(): """ Real Name: b'death rate 60' Original Eqn: b'Critical Cases 60*fraction of death 60/duration of treatment 60' Units: b'person/Day' Limits: (None, None) Type: component b'' """ return critical_cases_60() * fraction_of_death_60() / duration_of_treatment_60()
223990d67fcde9731080e58c7f5ca6ee208c17ff
31,321
from datetime import datetime def cast_vote(uid, target_type, pcid, value): """ Casts a vote in a post. `uid` is the id of the user casting the vote `target_type` is either `post` or `comment` `pcid` is either the pid or cid of the post/comment `value` is either `up` or `down` """ ...
702622b91612c1b9636c16786c76c1c711cf7520
31,322
def convert_file(ifn: str, ofn: str, opts: Namespace) -> bool: """ Convert ifn to ofn :param ifn: Name of file to convert :param ofn: Target file to convert to :param opts: Parameters :return: True if conversion is successful """ if ifn not in opts.converted_files: out_json = to...
963a3bdc4b5fa48295230e183ee99fd4b3f79b22
31,323
def target_validation(target_name, action): """ Given a Target name and an action, determine if the target_name is a valid target in target.json and if the target supports the action. Parameters ---------- target_name : str Name of the Target. action : str Type of action the...
c2f8015856f154c16fbcae29f3ed931c3a4d8f73
31,324
def bartletts_formula(acf_array, n): """ Computes the Standard Error of an acf with Bartlet's formula Read more at: https://en.wikipedia.org/wiki/Correlogram :param acf_array: (array) Containing autocorrelation factors :param n: (int) Length of original time series sequence. """ # The first ...
d207695a59d1b1c968f2e3877edbee3ce97f1604
31,326
def AddEnum(idx, name, flag): """ Add a new enum type @param idx: serial number of the new enum. If another enum with the same serial number exists, then all enums with serial numbers >= the specified idx get their serial numbers incremented (in other words, ...
1b5a713380c1b79e1bc26e1300e36adbcc7ceb8e
31,327
from typing import Optional from typing import Tuple from typing import Union def get_turbine_shadow_polygons(blade_length: float, blade_angle: Optional[float], azi_ang: float, elv_ang: float, ...
c3d568d60325a8309a3305b871943b55f8959f41
31,328
def str_igrep(S, strs): """Returns a list of the indices of the strings wherein the substring S is found.""" return [i for (i,s) in enumerate(strs) if s.find(S) >= 0] #return [i for (s,i) in zip(strs,xrange(len(strs))) if s.find(S) >= 0]
bae8afdb7d0da4eb8384c06e9f0c9bc3f6a31242
31,329
def random_laplace(shape, loc=0.0, scale=1.0, dtype=tf.float32, seed=None): """ Helper function to sample from the Laplace distribution, which is not included in core TensorFlow. """ z1 = random_exponential(shape, loc, dtype=dtype, seed=seed) z2 = random_exponential(shape, scale, dtype=dtype, seed=seed) r...
77c2df0bacfcf2ec07f137def93e2a9429d968ca
31,330
import math def resample_image(img_in, width_in, height_in, width_out, interpolation_method="bilinear"): """ Resample (i.e., interpolate) an image to new dimensions :return resampled image, new height """ img_out = [] scale = float(width_out) / float(width_in) scale_inv = 1.0 / scale # print "Resampling sca...
4d9759c02749cab30244326d3da7cf7c6c48fe46
31,331
def identify_missing(df=None, na_values=['n/a', 'na', '--', '?']): """Detect missing values. Identify the common missing characters such as 'n/a', 'na', '--' and '?' as missing. User can also customize the characters to be identified as missing. Parameters ---------- df : DataFrame R...
b7b7fe20309463cd6f9044cb85459084910d23a4
31,332
def _TryJobSvnRepo(builder_type): """Returns an SVN repo to use for try jobs based on the builder type.""" if builder_type == fetch_build.PERF_BUILDER: return PERF_SVN_REPO_URL if builder_type == fetch_build.FULL_BUILDER: return FULL_SVN_REPO_URL if builder_type == fetch_build.ANDROID_CHROME_PERF_BUILDE...
9d3a71ee10735499a0f677c88f5b2dc2c8e24e5c
31,334
def find_wr5bis_common2(i, n, norm, solution_init, common2b_init): """ Find the point when for the scalar product of the solution equals the scalar product of a guess with 2 consecutive bits in common. Fct_common2b(w) = fct_solution(w), for which w in [w0_3 , w0_4] with 0 =< w0_3 < w0_4 < 1 ? fct_solution(w) =...
2678f1ad355f1bc96aaf1be96945af2b21727d97
31,335