content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _act_drop(grid_world, agent, env_obj, drop_loc): """ Private MATRX method. Drops the carried object. Parameters ---------- grid_world : GridWorld The :class:`matrx.grid_world.GridWorld` instance in which the object is dropped. agent : AgentBody ...
93511395fda0060d479284a4b97ccd181346292f
28,321
def get_emoticon_radar_chart(scores_list, colors, names): """ AAA """ data_radars = [] emotions = ['anger', 'anticipation', 'disgust', 'fear', 'joy', 'sadness', 'surprise', 'trust'] for score, color, name in zip(scores_list, colors, names): data = go.Scatterpolar(r=score, theta=emotions, fil...
9f147a9bdd5713a915b96a309bcd1086c9e17ba6
28,322
def get_polling_method(meth_name=None): """ Grab a polling-method by string-key Eventually these could be auto-registered somehow; for now we just keep a look-up dict of them. """ methods = dict( poll_game_unknowns=poll_game_unknowns, poll_dan=poll_dan, ) default_method = poll_...
2faf19b3b6cf6decd230c5678591478eaf7839d6
28,323
import pkg_resources import scipy def generate_wav(pattern, tempo=120, loops=1, saveName='audiofile.wav', fs=44100, dynamics=False, customSound=None): """ Generate a .wav file from a pattern. Specify a tempo (in BPM), loops, name of the file, sampling rate, and decide if you want "dynamics". Dynamics adds o...
aa11722a40aca967d168f38ea1ae239eccfa3361
28,326
def svn_fs_upgrade(*args): """svn_fs_upgrade(char path, apr_pool_t pool) -> svn_error_t""" return _fs.svn_fs_upgrade(*args)
4f466df2d6f41cbe277370e3ec158e7737d271f0
28,327
def api_url(service: str = "IPublishedFileService", function: str = "QueryFiles", version: str = "v1") -> str: """ Builds a steam web API url. :param service: The steam service to attach to. :param function: The function to call. :param version: The API version. :return: ...
2538ab8c8035c491611585089ddd3a1625e423cc
28,328
import re def reg_all_keywords(data): """ 从meta file中提取所有关键词,格式为: ***[:###]*** 提取出### :param data: :return: """ patt = re.compile(r"\[:([^\[\]]+)\]") ret = patt.findall(data) return ret if ret else None
d81f8dd5f04d9e65f61247a8c9857969cf7e514d
28,329
def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ _focus = windowing.FocusManager() FigureClass = kwargs.pop('FigureClass', Figure) figure = FigureClass(*args, **kwargs) window = Tk.Tk() canvas = FigureCanvasTkAgg(figure, master=window) figMan...
c5c589c214a70f07ace913b5b8fb13cd52c30240
28,330
def get_platform(): """Gets the platform (example: azure).""" return get_config_value("platform")
693540442f23b21b9d983c9e7728d5397415544b
28,331
def ascii_from_object(space, w_obj): """Implements builtins.ascii()""" # repr is guaranteed to be unicode w_repr = space.repr(w_obj) w_encoded = encode_object(space, w_repr, 'ascii', 'backslashreplace') return decode_object(space, w_encoded, 'ascii', 'strict')
14ff3217b42743c5e202db107914e5ee0df4a10d
28,333
def capture(p): """Return a peg that acts like p, except it adds to the values tuple the text that p matched.""" return _Peg(('capture(%r)', p), lambda s, far, (i, vals): [(i2, vals2 + (s[i:i2],)) for i2, vals2 in p.run(s, far, (i, vals))])
710e1cf4015b057e6898affa70ef380be0648ea3
28,335
def html_chart(df, height=1200): """ make interactive chart. param df: inpute dataframe param height: optional plot height returns: plotly chart """ fig = make_subplots(rows=(len(df.columns)), cols=1, subplot_titles=df.columns, ...
821f6ae8c10a80c32a932cd77beb2b0a3969d0af
28,336
def build_0565_color_lookup(): """Build the lookup table for the ARGB_0565 color format""" bdG = 6 bdB = 5 redColorOffset = bdG + bdB greenColorOffset = bdB val_lookup_5 = BITDEPTH_VALUE_LOOKUPS[5] val_lookup_6 = BITDEPTH_VALUE_LOOKUPS[6] conversion_table = [None] * 65536 for r_sho...
c3a33e0355fb795e93ee722012faab6b83195bb4
28,337
def build_que_input_from_segments(context, answer, question, tokenizer, max_input_length=1000, with_eos=True, with_labels=True): """ Build a sequence of input from 3 segments: context, answer, question """ bos, eos, ctx, ans, que, pad, ...
400abaac1744bab2f665c8ffad50ba2b7030569b
28,338
def transition(field, source='*', target=None, conditions=[], custom={}): """ Method decorator for mark allowed transitions Set target to None if current state needs to be validated and has not changed after the function call """ def inner_transition(func): fsm_meta = getattr(func, '_d...
cf4066c8a21c89a793e526cf4a4171ac17cf7c42
28,341
def get_inspexp_frames(slice, inspexp_data, images_path): """ Loads inspiration and expiration frames for the specified cine-MRI slice Parameters ---------- slice: CineMRISlice A cine-MRI slice for which to extract inspiration and expiration frames inspexp_data : dict A dictionary...
d0dda284af281ebca08ee494a1e5fdc8f97789e4
28,342
def cleaned_reviews_dataframe(reviews_df): """ Remove newline "\n" from titles and descriptions, as well as the "Unnamed: 0" column generated when loading DataFrame from CSV. This is the only cleaning required prior to NLP preprocessing. INPUT: Pandas DataFrame with 'title' and 'desc' colum...
8f805f556667f5d734d4d272a2194784d37ce99c
28,343
def not_list(l): """Return the element wise negation of a list of booleans""" assert all([isinstance(it, bool) for it in l]) return [not it for it in l]
6d30f5dd587cdc69dc3db94abae92a7a8a7c610d
28,344
def first_order_forward(n, zero = True): """ """ m1 = -np.eye(n) + np.eye(n, k = 1) return np.vstack([np.ones(n), m1])
d79149614e15c8cce9f13a402f6321b43498862b
28,345
def boil(config, recipe_config): """ Boil wort. """ up = config['unit_parser'] if 'Hops' in recipe_config: hops = recipe_config['Hops'] for hop in hops: if 'addition type' in hop and hop['addition type'] == 'fwh': if 'mass' in hop and 'name' in hop and 'type' in...
035de7c388e2c82962987c63c13679e6bd16222f
28,346
def _ecdf( data=None, p=None, x_axis_label=None, y_axis_label="ECDF", title=None, plot_height=300, plot_width=450, staircase=False, complementary=False, x_axis_type="linear", y_axis_type="linear", **kwargs, ): """ Create a plot of an ECDF. Parameters ----...
e3ae7e76eaa285506692ef48031cdb309fa732f1
28,347
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes def _get_cipher(key: bytes) -> Cipher: """获取 DES3 Cipher 对象""" algorithm = algorithms.TripleDES(key) cipher = Cipher(algorithm, modes.CBC(key[:8]), backend=default_backend...
13c046884ccd51ff19ed9eb80a1747f6888863a0
28,348
def get_real_dist2rim(x_dist, radius_cut, radius_sphere): """ Get the real distance to rim :param x_dist: :param radius_cut: :param radius_sphere: :return: """ x_transf = x_dist * ((radius_sphere) - np.sqrt((radius_sphere) ** 2 - (radius_cut) ** 2)) / radius_cut return x_transf
89f1a6ef3e020636537a8f229e082f7765410129
28,349
def get_workers_stats(worker_class=None): """Get the RQ workers stats. Args: worker_class (type): RQ Worker class Returns: list: List of worker stats as a dict {name, queues, state} Raises: redis.exceptions.RedisError: On Redis connection errors """ worker_class = worker_...
33e86511051b15de07eceaa1ab0d8d609eecbafc
28,351
def _get_trafo(cmatrix: cairo.Matrix) -> qc3const.TrafoType: """Converts cairo matrix to trafo list :param cmatrix: (cairo.Matrix) cairo transformation matrix :return: (qc3const.TrafoType) transformation matrix """ return [i for i in cmatrix]
ea9c3c3b8466a7025fce5f48ceb02baa5ae9d319
28,352
import bokeh from bokeh.plotting import output_file, ColumnDataSource, show, figure from bokeh.models import HoverTool, CategoricalColorMapper, LinearColorMapper, Legend, LegendItem, ColorBar from bokeh.palettes import Category20 def mousover_plot(datadict, attr_x, attr_y, attr_color=None, attr_size=None, save_file=N...
0cee54239d13e7c3ebd36972e7c0f259ff7de69a
28,353
import numpy def globalInequalityChanges(Y, fieldNames, outFile, permutations=9999): """Global inequality change test This function tests whether global inequality has significantly changed for the Theil statistic over the period t to t+k. For more information on this function see [Rey_Sastre2010] (...
6a9d0579c52083419d5f4cbedbe4b568d6b7e0a0
28,354
import re def generate_gisaid_fasta_df(fname, rtype="nuc", ambiguous_tol=0.01, len_tol=0.9): """ Generate pandas dataframe for sequences downloaded from GISAID """ fdat_df = [] standardise_gene_name = {"PB2":1, "PB1":2, "PA":3, "HA":4, "NP":5, "NA":6, "MP":7, "NS":8} subtype_to_influenza_gene...
bf7c09f1f2cfa935d93bbe46c25d55539f2c8bf8
28,355
def radial_trajectory(base_resolution, views=1, phases=None, ordering='linear', angle_range='full', tiny_number=7, readout_os=2.0): """Calculate a radial trajectory. This function sup...
3554fc0b833be552af31153c80c07863ab8f683d
28,356
def highlight_threshold(image, img_data, threshold, color=(255, 0, 0)): """ Given an array of values for an image, highlights pixels whose value is greater than the given threshold. :param image: The image to highlight :param img_data: The values to use :param threshold: The threshold above which pi...
bc4b0c9f44f7d45b947c9913f6b6f43b73ea542b
28,357
import numpy def error_norm(q_numerical, q_exact, dx, p=2): """ Compute the discrete error in q in the p norm Parameters ---------- q_numerical : numpy vector The numerical solution, an array size (N,) or (N,1) q_exact : numpy vector The exact solution, whose size matches q_nu...
e4d33583ee2c5308a2eda9755c44961acba2603d
28,358
def flip(xyz_img): """ Take an xyz_img and flip its world from LPS / RAS to RAS / LPS. >>> data = np.random.standard_normal((30,40,50,5)) >>> metadata = {'name':'John Doe'} >>> lps_im = XYZImage(data, np.diag([3,4,5,1]), 'ijkt', metadata) >>> lps_im.xyz_transform XYZTransform( fu...
e3f345c8c61043e8a46e8c9b603ed5de93125d63
28,360
def pivoting_remove(z, rule): """Choose which active constraint will be replaced """ if rule is None: k = np.argmin(z) elif rule.lower() == 'bland': k = np.min(np.nonzero(z < 0)[0]) else: raise('Undefined pivoting rule') return k
54186ddc15db3abca6853b928c6d51f145cbe248
28,361
import tqdm def train_network(model, optimizer, train_loader, lss_fc) -> None: """Train Network for one Epoch.""" train_losses = [] for batch in tqdm(train_loader, total=len(train_loader)): optimizer.zero_grad() input_tensor, original = batch input_tensor = input_tensor.to('cuda')...
1b90706348ceefe7840b16d29bfb0cc37229ec46
28,362
def get_class(cls): """Return TestModuleVisitor report from a class instance.""" ast = get_ast(cls.__module__) nv = TestmoduleVisitor() nv.visit(ast) return nv._classes[cls.__name__]
4d3bb56f9582edb1576db67a3094f6b3efa3e106
28,363
def show_system_timezone( enode, _shell='vtysh', _shell_args={ 'matches': None, 'newline': True, 'timeout': None, 'connection': None } ): """ Display system timezone information This function runs the following vtysh command: :: # show system ti...
67f08762a31c54fdaeb7c93c48c8c5d97ecf2f3e
28,364
import numpy def summarize_list(values): """ Takes a list of integers such as [1,2,3,4,6,7,8] and summarises it as a string "1-4,6-8" :param values: :return: string """ sorted_values = numpy.array(sorted(values)) summaries = [ (f'{chunk[0]}-{chunk[-1]}' if len(chunk) > 1 els...
ea6e3501fb3340e0a78a71096129df5b3400fac9
28,365
import torch def enforce_size(img, depth, instances, new_w, new_h): """ Ensures that the image is the given size without distorting aspect ratio. """ with torch.no_grad(): _, h, w = img.size() if h == new_h and w == new_w: return img, depth, instances # Resize the...
5252b9c62af4ce909fb85856a78b7e4a697aaf74
28,366
import stat def update_V_softmax(V,B,T,O,R,gamma,eps=None,PBVI_temps=None, max_iter=100,verbose=False,n_samps=100,seed=False): """ inputs: V (list): V[0]: n_B x n_S array of alpha-vector values for each belief V[1]: n_B array, denoting which action generate...
62910d068a59902d6a9f5f0c2b873cad551f9c17
28,367
def scaled_location_plot(yname, yopt, scaled_res): """ Plot the scaled location, given the dependant values and scaled residuals. :param str yname: Name of the Y axis :param ndarray yopt: Estimated values :param ndarray scaled_res: Scaled residuals :returns: the handles for the ...
24e126f3bb60e5f46713d3a0c7da383684081afd
28,368
def importNoiseTerms(filename): """ Imports noise data from an FWH file; the returned data is a list of length nProbes filled with (nTime,3) arrays """ f = open(filename,'r') deltaT = [] while True: line = f.readline(); # read line by line if line == '': # check for ...
b2066f37f7a030d1e330f9bcc0b13b7527caa1e1
28,369
def line_edit_style_factory(txt_color='white', tgt_layer_color='white', bg_color='#232323'): """Generates a string of a qss style sheet for a line edit. Colors can be supplied as strings of color name or hex value. If a color arg receives a tuple we assume it is either an rgb or ...
10670afc32ec1c19d09dd72fc0e23bb1583ba3af
28,370
import struct import random def create_key(key_len): """ Generates key using random device if present - key_len -- length of key """ try: #generates truly random numbers frand = open("/dev/random", "r") data = frand.read(key_len/2) frand.close() return data.e...
84a9952a896855f04ddf6fedf8a81c1be6bdaa08
28,371
import re def ipv6_from_string(string: str) -> netaddr.IPSet: """ Takes a string and extracts all valid IPv6 Addresses as a SET of Strings Uses the validate_ip helper function to achieve. """ ipv6_regex = re.compile( '(?<![a-zA-Z\d\.])((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-...
2aa529b8561498384dea2ae6c18f44164710848a
28,373
from typing import Tuple from typing import List def get_feature_location( feature_text: str) -> Tuple[int, int, str, List, bool, bool]: """ Args: feature_text: endswith '\n' For example: ' CDS complement(join(<360626..360849,360919..360948, ...
665649a7ea7c618a8830b0bf11c5d26a6e6d21fd
28,374
import json import logging def _update_port_rate_limits_v1(port_name, broadcast_limit=None, broadcast_units=None, multicast_limit=None, multicast_units=None, unknown_unicast_limit=None, unknown_unicast_units=None, **kwargs): """ Perform GET and P...
28f21634af949b2e023db64ac6a4b850e2bf96cc
28,376
def random_geom_sum(pmf, p, low_mem=False): """Calculates the distribution of Z = X_1 + X_2 + ... + X_N. Parameters ---------- pmf : array Probability distribution of X such that pmf[x] = Pr(X = x). p : float Probability such that N ~ geom(p), i.e. Pr(N = n) = p(1-p)^{n-1}. low_...
3b7f75a248975dd78e3cf986bff02a6160c1a026
28,377
def noto_tools(default=""): """Local path to nototools git repo. If this is called, we require config to be set up.""" result = _values.get("noto_tools", default) if result: return result raise Exception(_ERR_MSG)
42738c374bcd6d89baf4eabbe7c0f0a75fb1fd1d
28,378
def fdc_windtur_west(timestamp, sonicU, sonicV, sonicW, heading, rateX, rateY, rateZ, accX, accY, accZ, lat): """ Description: Calculates the L1 windspeed data product WINDTUR-VLW_L1 from the FDCHP instrument, which collects 20 minutes of data every hour. The L1 data ...
e0136ff7ddaf676b99f28700e3613523bb57b12e
28,379
def reports(): """View reports""" return render_template("reports.html")
b69119a97998595757d52e5641246bbeea007d18
28,380
def otr_statusbar_cb(data, item, window): """Update the statusbar.""" if window: buf = weechat.window_get_pointer(window, 'buffer') else: # If the bar item is in a root bar that is not in a window, window # will be empty. buf = weechat.current_buffer() result = '' i...
9fb58921b901e542ad6f8bed7207337db56de872
28,381
def rotate_ellipse_NS(time_deg, datastruc, const): """Rotate ellipse major/minor axis to north/south orientation.""" # Construct major and minor major, minor, pha, inc = get_constituent(const, datastruc) # construct current at this time try: major_current = major*np.cos(np.deg2rad(time_deg -...
48c4d4270e8a521969608369974c59cff6700a03
28,382
import requests def img_lookup(pid): """Query for object type and return correct JPG location""" r = requests.get("https://fsu.digital.flvc.org/islandora/object/{0}/datastream/JPG/view".format(pid)) if r.status_code == 200: return r.url elif r.status_code == 404: r2 = requests.get("htt...
ac9ccfc64e4bf38b0f22e90649368cae1ad89b18
28,383
from datetime import datetime def _get_midnight_date(date): """Return midnight date for the specified date. Effectively, this function returns the start of the day for the specified date. Arguments: date -- An arbitrary date (type: datetime.datetime) Return: Midnight date (type: datetime.da...
165a884fd12e79f167c9818126e1e31a3b2dc8b3
28,384
def get_workflow_entrypoint(definition_class, workflow_name, workflow_version): """Get the entry point information from *workflow_class*. This function provides a convenient way to extract the parameters that need to be returned the *get_workflow* argument to :py:class:`~.GenericWorkflowWorker` :p...
87a7cbc1ad810e08033f19d1d3c7551ff8b4eb46
28,385
def expect_types(*_pos, **named): """ Preprocessing decorator that verifies inputs have expected types. Usage ----- >>> @expect_types(x=int, y=str) ... def foo(x, y): ... return x, y ... >>> foo(2, '3') (2, '3') >>> foo(2.0, '3') Traceback (most recent call last): ...
92b7682bda54f02c095d10534b71fb02fea1a763
28,386
def squash_by(child_parent_ids, *attributes): """Squash a child-parent relationship Arguments --------- child_parent_ids - array of ids (unique values that identify the parent) *attributes - other arrays that need to follow the sorting of ids Returns ------- child_parents_idx - an arra...
1c68bb38ee10044803021f4d74b37ea4b161eef5
28,387
import random import math def _generate_quantsets(num_vars, num_qsets, ratio): """ _generate_quantsets(num_vars : int, num_qsets : int, ratio : float) return (quantsets : list) Generates a list of random quantifier sets according to given argument...
e01e053e64384f0304fd21200bd31485f0e6eb06
28,388
def encoder(src_embedding, src_sequence_length): """Encoder: Bidirectional GRU""" encoder_fwd_cell = layers.GRUCell(hidden_size=hidden_dim) encoder_fwd_output, fwd_state = layers.rnn( cell=encoder_fwd_cell, inputs=src_embedding, sequence_length=src_sequence_length, time_major...
f23fb197838952017d3706db221ab55c9807bbb0
28,390
def _class_search_post_url_from(absolute_url, form): """Determines absolute URL to submit HTTP POST query request to""" method = form.get(HTTP_METHOD) if method != POST: raise ValueError("Expected POST form submission method; Got "+repr(method)) action = form.get(ACTION) dest_url = urljoin(a...
9547643b49cec1a4ea272c31b6a5399c076fa487
28,391
def pcmh_2_2d__3_5_6_7_8(): """Huddles, Meetings & Trainings""" huddle_sheet_url = URL('init', 'word', 'huddle_sheet.doc', vars=dict(**request.get_vars), hmac_key=MY_KEY, salt=session.MY_SALT, hash_vars=["app_id"]) # referral tracking chart huddle_sheet = MultiQNA( 5...
73946627100342c07083e656d92d2364d166cc16
28,392
def CallCountsToMockFunctions(mock_function): """A decorator that passes a call count to the function it decorates. Examples: @CallCountsToMockFunctions def foo(call_count): return call_count ... ... [foo(), foo(), foo()] [0, 1, 2] """ counter = [0] def Result(*args, **kwargs)...
cc621cabdf87ff554bb02c25282e99fadcaaa833
28,393
from typing import Callable from typing import Tuple import scipy def multi_start_maximise(objective_function: Callable, initial_points: ndarray, **kwargs) -> Tuple[ndarray, float]: """Run multi-start maximisation of the given objective function. Warnings -------- This is a h...
6eabacc0d84389c45ddbd75fd84a27cf312e65be
28,394
async def ping(): """ .ping: respond with pong """ return "pong"
988165efb5087fd838a2930dbe4ed540b2d70037
28,395
from statsmodels.tsa.stattools import adfuller def stationarity_check(TS,plot=True,col=None): """From: https://learn.co/tracks/data-science-career-v2/module-4-a-complete-data-science-project-using-multiple-regression/working-with-time-series-data/time-series-decomposition """ # Import adfuller i...
4b2120b4da74a08e13f61220bd212ae6016f3a73
28,396
def file_exists(session, ds_browser, ds_path, file_name): """Check if the file exists on the datastore.""" client_factory = session._get_vim().client.factory search_spec = vm_util.search_datastore_spec(client_factory, file_name) search_task = session._call_method(session._get_vim(), ...
00b856d529f16ea05123f2b4447d94698d986902
28,398
def convert_binary_to_unicode(binary_input): """ converts binary string of length 18 input to unicode :param binary_input: String :return: String """ unicode_output = '' for starting_position in range(0, len(binary_input), 18): unicode_output += chr(int(binary_input[starting_positio...
ae00c8b31779420662dca09e1ca6c23590b45e38
28,399
def get_rating(comment): """ """ return comment.xpath( ".//div[@itemprop=\"reviewRating\"]/meta[@itemprop=\"ratingValue\"]" )[0].attrib.get("content")
c80d7f3443a20facdf5a99c3db42d8aa49e95010
28,400
def creat_netmiko_connection(username, password, host, port) -> object: """Logs into device and returns a connection object to the caller. """ credentials = { 'device_type': 'cisco_ios', 'host': host, 'username': username, 'password': password, 'port': port, 'ses...
94c7463235051f87ad106b0c960ad155101fce56
28,401
def get_requirements(): """Read the requirements file.""" requirements = read("requirements.txt") return [r for r in requirements.strip().splitlines()]
a178d5148b137b4a6f46112cd73bbf6d2e9fb211
28,403
def handler(fmt, station, issued): """Handle the request, return dict""" pgconn = get_dbconn("asos") if issued is None: issued = utc() if issued.tzinfo is None: issued = issued.replace(tzinfo=timezone.utc) df = read_sql( f""" WITH forecast as ( select id ...
d75940ab5accc36258473d9794fd0449f707b593
28,404
def index_count(index_file=config.vdb_bin_index): """ Method to return the number of indexed items :param index_file: Index DB file :return: Count of the index """ return len(storage.stream_read(index_file))
2abe3a9a3b1e04f67175cabc9099f490556caabd
28,405
def asc_to_dict(filename: str) -> dict: """ Load an asc file into a dict object. :param filename: The file to load. :return dict: A dict object containing data. """ return list_to_dict(asc_to_list(filename))
3509321bc38e53ae1e86fa8b9cea113bec55700a
28,407
def merge_sort(array): """ Merge Sort Complexity: O(NlogN) """ if len(array) > 1: mid = len(array) // 2 left = array[:mid] right = array[mid:] left = merge_sort(left) right = merge_sort(right) array = [] # This is a queue implementation. We c...
73b3ac5b950f5788cbc3e7c98d2a4d5aac427929
28,408
def semi_major_axis(P, Mtotal): """Semi-major axis Kepler's third law Args: P (float): Orbital period [days] Mtotal (float): Mass [Msun] Returns: float or array: semi-major axis in AU """ # convert inputs to array so they work with units P = np.array(P) Mtotal...
338ce7857544d59dca1d78026f2559ce698faae8
28,409
def _check_df_load(df): """Check if `df` is already loaded in, if not, load from file.""" if isinstance(df, str): if df.lower().endswith('json'): return _check_gdf_load(df) else: return pd.read_csv(df) elif isinstance(df, pd.DataFrame): return df else: ...
7245341c8fa58e2aea20761d6832be09e948b0e3
28,411
def ping(host, timeout=False, return_boolean=False): """ Performs an ICMP ping to a host .. versionchanged:: 2015.8.0 Added support for SunOS CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2015.5.0 Return a True or False instead ...
f5707427eaef1e436618065bea78faa15a5cce7e
28,413
def comp_wind_sym(wind_mat): """Computes the winding pattern periodicity and symmetries Parameters ---------- wind_mat : numpy.ndarray Matrix of the Winding Returns ------- Nperw: int Number of electrical period of the winding """ assert len(wind_mat.shape) == 4, "...
7984eb6f3b1d7d11694ecac1237ce27b11bbd9fe
28,414
def row(data, widths="auto", spacing=3, aligns=None): """Format data as a table row. data (iterable): The individual columns to format. widths (iterable or 'auto'): Column widths in order. If "auto", widths will be calculated automatically based on the largest value. spacing (int): Spacing betw...
3adef2268ba1720e7480a3b4d0f873927d14f0b6
28,416
from datetime import datetime import calendar def _increment_date(date, grain): """ Creates a range of dates where the starting date is the given date and the ending date is the given date incremented for 1 unit of the given grain (year, month or day). :param date: the starting date in string for...
53626ad40cdf5a2352a6129fb15ed91ede60838e
28,417
def ErrorCorrect(val,fEC): """ Calculates the error correction parameter \lambda_{EC}. Typical val is 1.16. Defined in Sec. IV of [1]. Parameters ---------- val : float Error correction factor. fEC : float Error correction efficiency. Returns ------- float ...
83c4483c56c7c3b79060dd070ec68f6dfd5ee749
28,418
def BytesGt(left: Expr, right: Expr) -> BinaryExpr: """Greater than expression with bytes as arguments. Checks if left > right, where left and right are interpreted as big-endian unsigned integers. Arguments must not exceed 64 bytes. Requires TEAL version 4 or higher. Args: left: Must eva...
9c509eab36ef0b174248741b656add275d8654b3
28,419
def balanceOf(account): """ can be invoked at every shard. If invoked at non-root shard, the shard must receive a xshard transfer before. Otherwise the function will throw an exception. :param account: user address :return: the token balance of account """ if len(account) != 20: raise Ex...
36d56a2536f33053dc5ed2020d0124380e9ceb28
28,420
def archive_entry(title): """ """ if not session.get('logged_in'): abort(401) db = get_db() # Archive it stmt = ''' insert into archived_entries select * from entries where pretty_title like ? ''' db.execute(stmt, ('%' + title + '%',)) db.execute('delet...
69384fbfda4090352640890105c02304782e541c
28,421
def build_census_df(projection_admits: pd.DataFrame, parameters) -> pd.DataFrame: """ALOS for each category of COVID-19 case (total guesses)""" n_days = np.shape(projection_admits)[0] hosp_los, icu_los, vent_los = parameters.lengths_of_stay los_dict = { "Hospitalized": hosp_los, "ICU": i...
0b1471f6e522a15027e2797484e573c65971e0d4
28,422
def indented_kv(key: str, value: str, indent=1, separator="=", suffix=""): """Print something as a key-value pair whilst properly indenting. This is useful for implementations of`str` and `repr`. Args: key (str): Key. value (str): Value. indent (int, optional): Number of spaces to i...
b27a7ed7a0db4219332fda1e1131c888216141b2
28,423
def are_in_file(file_path, strs_to_find): """Returns true if every string in the given strs_to_find array is found in at least one line in the given file. In particular, returns true if strs_to_find is empty. Note that the strs_to_find parameter is mutated.""" infile = open(file_path) for line in i...
474234a35bf885c5f659f32a25c23580f2014cc2
28,424
def load_data(filename: str): """ Load house prices dataset and preprocess data. Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector (prices) - either as a single DataFrame or a Tuple[DataFrame, Series] """ ...
a8aed077d63c9e2df0f150b2ef7e3c06c30fcb29
28,425
import unicodedata import re def slugify(value): """ Unicode version of standart slugify. Converts spaces to hyphens. Removes characters that aren't unicode letters, underscores, or hyphens. Converts to lowercase. Also replaces whitespace with hyphens and strips leading and trailing hyphens. ...
e81020b76f4e29f89e44c420e8e95b89f7eb1363
28,427
from math import factorial as f def binomial_coefficient(n: int, m: int) -> int: """ Binomial Coefficient Returns n!/(m!(n-m)!). This is used in combinatronics and binomial theorem.""" return f(n)/(f(m)*f(n-m))
e0ad7a4cd3cb85bb4c0a48890209a8f71086a853
28,429
def joint(waypoints): """ Calculate a trajectory by a joint operation. """ # total number of segments numSegments = len(waypoints) - 1 # every segment has its own polynomial of 4th degree for X,Y and Z and a polynomial of 2nd degree for Yaw numCoefficients = numSegments * (3*5+3) # list ...
06b3b2f183c749405ecacd4ce639c3c2d5826e55
28,430
import math def logistic(x: float): """Logistic function.""" return 1 / (1 + math.exp(-x))
98b4f7aebd562609789ed5f53f6a79d63eaf6ea0
28,431
def highlight_deleted(obj): """ Display in red lines when object is deleted. """ obj_str = conditional_escape(text_type(obj)) if not getattr(obj, 'deleted', False): return obj_str else: return '<span class="deleted">{0}</span>'.format(obj_str)
daad6a35bab989a2ca9df63292fecf36b05ff715
28,432
def range_(stop): """:yaql:range Returns an iterator over values from 0 up to stop, not including stop, i.e. [0, stop). :signature: range(stop) :arg stop: right bound for generated list numbers :argType stop: integer :returnType: iterator .. code:: yaql> range(3) [0, ...
28717348bcdcd432388b8a4809c897c70a2fce3f
28,433
def post(filename: str, files: dict, output_type: str): """Constructs the http call to the deliver service endpoint and posts the request""" url = f"http://{CONFIG.DELIVER_SERVICE_URL}/deliver/{output_type}" logger.info(f"Calling {url}") try: response = session.post(url, params={"filename": fil...
358b408ace8750d1c48ca6bef0855aac4db625ca
28,435
def is_off(*args): """ is_off(F, n) -> bool is offset? @param F (C++: flags_t) @param n (C++: int) """ return _ida_bytes.is_off(*args)
43dc5298bad5daf95f76e8426e819e1feb89f8d4
28,437
def get_libdcgm_path(): """ Returns relative path to libdcgm.so.2 """ return "../../lib/libdcgm.so.2"
a1067449bdc9012e07c5707ece68c3aae2799694
28,438
def method(modelclass, **kwargs): """Decorate a ProtoRPC method for use by the endpoints model passed in. Requires exactly one positional argument and passes the rest of the keyword arguments to the classmethod "method" on the given class. Args: modelclass: An Endpoints model class that can create a metho...
801fad462414b94f6ee72e507c17813afc043f81
28,439
def detect_on(window, index=3, threshold=5): # threshold value is important: power(watts) """input: np array listens for a change in active power that exceeds threshold (can use Active/real(P), Apparent(S), and Reactive (Q)(worst..high SNR)) index = index of feature to detect. Used P_real @ index 3 ...
dfea9b4ea95c22b199a63c47cb5f7f16f10df742
28,440
def calculate_target_as_one_column(df:pd.DataFrame, feature_cols:list, target_cols:list): """create a row for every new porduct and give the product name as target column, this is done for the train set""" x = df[target_cols] x = x[x==1].stack().reset_index().drop(0,1) df = pd.merge(df, x, left_on=df.in...
eee8e27a60999c95e2354877526ae27d9679a3ca
28,441