content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def evaluate_posterior_predictive(samples: xr.Dataset, test: xr.Dataset) -> np.ndarray: """ Computes the predictive likelihood of all the test items w.r.t. each sample. See the class documentation for the `samples` and `test` parameters. :returns: a numpy array of the same size as the sample dimension. ...
23062158b92fb7358c65ae4d36094d9c7c3ecd7f
47,240
from typing import Any def get_logger() -> Any: """ An entry point of the plug-in and return the usage logger. """ return KoalasUsageLogger()
4299dcb722cc06bab360579f379a0a1f487a2100
47,241
def circle_image(shape, center, radii, intensities): """ Creates an image with circle or thickness 2 """ im = np.zeros(shape=shape, dtype=np.float) xx, yy = np.ogrid[0 : shape[0], 0 : shape[1]] xx, yy = xx - center[0], yy - center[1] for radius, intensity in zip(radii, intensities): rr = np....
0441b6f1b06481889f8d8333bc47a68463e969ad
47,242
import time def upsample(prob_maps_multiple_images, output_shape): """ Function for performing upsamping of probability maps :param prob_maps: Probability maps for each class for each resized image :param output_shape: Desired shape to upsample to (should be dimensions of original image) :return: ...
fcea1a68304d74542afc937472d531ddb2a73aa3
47,243
def closest_dataframe_from_origins_destinations(origins, origin_id_fld, destinations, dest_id_fld, gis=None, network_dataset=None, destination_count=4): """ Create a closest destination dataframe using origin and destination Spatially Enabled Dataframes. :para...
98f43f8a2354afdba9d716cb484a7fef403c7728
47,244
def naive(string: str): """ Recognize POS in a string using Regex. Parameters ---------- string: str Returns ------- string : tokenized string with POS related """ string = string.lower() results = [] for i in string.split(): results.append(_naive_POS_word(i)) ...
ec436805a5d9803599ea6f1152c3e9a5cb3d095b
47,245
def main(): """ Runs the main program. """ prob1a() return GOOD_RET
142127860a55edc204dd98c02d467d8df56259d1
47,246
def init_tenses(): """initialises the tenses dict.""" tenses = {} for t in VerbTense: tenses[t] = {} for d in VerbDependency: tenses[t][d] = {} for p in VerbPerson: tenses[t][d][p] = [] return tenses
97cec934b2d971aebd52b6c9337eb2dcff0dde62
47,247
def prim(w_graph_d): """Prim's algorithm for minimum spanning tree in "undirected weighted" graph, G(V, E). Time complexity for : O((|V|+|E|)log(|V|)). Space complexity: O(|V|). """ min_pq = MinBinaryHeapAttribute() key_d = {v: float('inf') for v in w_graph_d.keys()} previous_d = {v: ...
752e3cd5768a176ab1322231e3fd4537402dccdc
47,248
def get_row_headers(data): """ Take a dictionary and walk the dictionary identifying allthe unique row headers. """ headers = set() try: for key, value in data.iteritems(): try: iter(value) if not isinstance(value, basestring): ...
d21eecd1306a052faeb07d305e62f87086881509
47,249
import traceback def Compile(expr): """ Given an XPath expression as a string, returns an object that allows an evaluation engine to operate on the expression efficiently. This "compiled" expression object can be passed to the Evaluate function instead of a string, in order to shorten the amount o...
61e8695e21ce4f3a016a4bb8512a44f6f22a0ef5
47,250
import math def f1(myList): """Solves x = Sqrt((120-y)/8)""" return math.sqrt((120-myList[1])/8) #return 120-8*myList[0]**2
5d84417d52ec3b667862a3750f6d46f74964a586
47,251
def mfccf(num, s, Fs): """ 计算并返回信号s的mfcc参数及其一阶和二阶差分参数 :param num: :param s: :param Fs: :return: """ N = 512 # FFT数 Tf = 0.02 # 窗口的时长 n = int(Fs * Tf) # 每个窗口的长度 M = 24 # M为滤波器组数 l = len(s) Ts = 0.01 # 帧移时长 FrameStep = int(Fs * Ts) # 帧移 lifter = np.array([...
4c36d6cb4b248bd081410964f3c72105f06c3444
47,253
def mesh_reader(path): """Read a mesh in using pymeshlab. Parameters ---------- path : str or list of str Path to file, or list of paths. Returns ------- layer_data : list of tuples List of surfaces, one per file path. """ # handle both a string and a list of string...
296332e459837e6c77e0f28ff8a6c0d99bec172c
47,255
def get_git_string(): """ Return a string with information on the git version """ sha = get_git_hash() return "Git branch hash: " + sha
6bd78cb250f6a26b6ed1e79d4d42633efcad961d
47,256
from typing import List from pathlib import Path def estimate_dmg_size(app_bundles: List[Path]) -> int: """ Estimate size of DMG to hold requested app bundles The size is based on actual size of all files in all bundles plus some space to compensate for different size-on-disk plus some space to hold ...
59261685ecece9128ace2430398e95e9c2ddc985
47,258
import torch from typing import Tuple def _initialize_full_precision( model: torch.nn.Module, optimizer: torch.optim.Optimizer ) -> Tuple[torch.nn.Module, torch.optim.Optimizer]: """ Initialize full precision training - leaves model and optimizer untouched. Flattens fp-32 parameters and gradients. ...
e989edbeccf9bf68acfd68bd8e645fc536091f47
47,259
def serialize(obj: Serializable) -> JSON: """Serialize object to JSON. Args: obj: An object to serialize. Returns: Its JSON representation. """ return _serializers[type(obj)](obj)
c8231dccbfe7bf4ea29636c1c4b0a143a7de9b9d
47,260
def resize_image(image, size=140): """Get squared-resized image """ BLACK = [0, 0, 0] h = image.shape[0] w = image.shape[1] if w < h: border = h-w image = cv2.copyMakeBorder(image, 0, 0, border, 0, cv2.BORDER_CONSTANT, value=BLACK) else: border = w-h image = c...
e9dfcddcfa644bc2dc39651071db1bb6c48d75a8
47,262
from typing import OrderedDict def get_families(cxn): """Extract the families from the taxonomy table.""" sql = """SELECT DISTINCT family FROM taxonomy;""" families = pd.read_sql(sql, cxn).set_index('family') return families.to_dict(orient='index', into=OrderedDict)
3e53d95fd9b9667dd975b1ac2d875aea1c3551ab
47,263
def _filter_by_variance(frame, threshold=0.005): """Removes from frame any columns with a relative variance beneath the given threshold. """ # first, for each column X, compute relative variance as # var((X-min(X))/(max(X)-min(X))) numerators = frame.subtract(frame.min(axis='index'), axis='colum...
f4225fe41adab6f5f1a0189f9eaeae071109a5ee
47,264
def test(p, parameters): """ Runs the quality control check on profile p and returns a numpy array of quality control decisions with False where the data value has passed the check and True where it failed. """ # Get temperature values from the profile. t = p.t() # Make the quality...
9854ddaf5979be6923d09c7293e757c348647fe5
47,265
def getDate(signature): """Function that returns the date present on the signature.""" return getToken(signature, "Date: ", '\x00')
07a738bce3d546f5950b8adda5f30ee6a2662d6a
47,266
import functools def monadic(f): """Decorate a unary function to return a Maybe monad.""" @functools.wraps(f) def wrapped(a): try: b = f(a) except Exception: b = None if b is None: return Nothing() else: return Just(b) ret...
461565ad0edfb5482aacdcaea13543592281f021
47,267
def jacobian(variables, functions): """Returns the Jacobian matrix containing the first derivative of each input function with respect to each input variable""" derivatives = [] try: # Case where functions is a list of AD objects if type(functions) is list: if l...
21cba3592be16c9883ef1a1eb6fd9a7307ac566f
47,268
from functools import reduce def kron_diag(diags): """Returns diagonal of kronecker product from list of diagonals. """ return reduce(flattened_outer, diags)
e8a5f6ad0c9d02369d31493284cb3a7763e466e4
47,270
def get_nodes_with_services(G): """ Based on the render of app_operator.py for visual inspection :param sim: :return: """ HwReqs = nx.get_node_attributes(G, name="HwReqs") currentOccupation = {} for n in G.nodes: currentOccupation[n] = np.zeros(int(HwReqs[n])).astype(int) ...
a67d04470da4f643e057caed1ad51635828e73f6
47,271
def GetXML(archiveUID=None,table=None): """ :param archiveUID: Archive UID :param table: Table :return: XML String """ sqlXML = "select XMLType.GetClobVal(xml) from ALMA.XXXXYYY where archive_uid='ZZZZCCCC' " sqlXML = sqlXML.replace('XXXXYYY',tables[table]).replace('ZZZZCCCC',archiveUID) ...
4038bab11069a6c15b2a2605c6b1d9158aa6dc75
47,272
def f_to_R(f_df, R_dict): """Calculates robustness from performance values. Uses a set of performance values, `f`, determined from simulations across multiple decision alternatives, `l`, different scenarios, `s`, and calculates robustness, `R`, using a variety of given robustness metrics. Para...
3d11f49f5beec7efa8cb2d1a652bdb6efc99ec3e
47,273
def is_not_csv_file(filename): """Retun an indication if the file entered is the clusterserviceversion (csv) file """ return not filename.endswith('clusterserviceversion.yaml')
3afcecfee95f300b9a5e6128f33a58dcdfc2c443
47,274
from typing import Optional def get_key(app_id: Optional[str] = None, developer_id: Optional[str] = None, key_id: Optional[str] = None, organization_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetKeyResult: """ Gets details...
6183059ebca2fd1584bd39f027dc1d747db5d462
47,275
def _shellBucklingOneSection(h, r1, r2, t, gamma_b, sigma_z, sigma_t, tau_zt, E, sigma_y): """ Estimate shell buckling for one tapered cylindrical shell section. Arguments: h - height of conical section r1 - radius at bottom r2 - radius at top t - shell thickness E - modulus of elastici...
b13d1f5d9127cf31712429124e359a8adf78dbf1
47,276
def cc_score_fct(i): """ CC (Chamberlin-Courant) marginal score function. This is the additional (marginal) score from a voter for the `i`-th approved candidate in the committee. Parameters ---------- i : int We are calculating the score for the `i`-th approved candidate in...
2a0cfab120bae500d023d548d06be68c4699fc22
47,277
def create_plan(response): """Create plan""" # if user is logged in if response.user.is_authenticated: if response.method == 'POST': form = CreateNewPlan(response.POST) # chcek form validation if form.is_valid(): # clean data t = f...
572d3fb4e638c624007abc2f82d56ddfb0161182
47,278
from typing import cast from datetime import datetime def sun( hass: HomeAssistant, before: str | None = None, after: str | None = None, before_offset: timedelta | None = None, after_offset: timedelta | None = None, ) -> bool: """Test if current time matches sun requirements.""" utcnow = d...
2e295e233fbe71c5383b912d1527ebf9d98c3fba
47,279
import torch def load_snapshot(model_path): """ Load snapshot :param model_path: path to snapshot :type model_path: str :return: built state :rtype: dict """ state = torch.load(model_path) return state
bdeba078302b8c8c6ac39f156877ef58e91341ec
47,280
def import_secondary_context_membership(): """Add docstring.""" log.info('Read in secondary context membership') SecondaryContextMembership = pd.read_csv(inputpath + 'SecondaryContextMembership.csv') return SecondaryContextMembership
6e755af43c9022f2137c0e934dc02f688735ea51
47,282
def _get_compiler_args( compiler_lang, flags, options, **_kwargs): """ Return compiler args when compiling for ocaml. """ _ignore = compiler_lang args = [] # The OCaml compiler relies on the HS2 compiler to parse .thrift sources to JSON args.append("-c") ...
3818896ca3dd099d1ba806cd1b80a53eb183b262
47,284
def view_vote_entities_map_proposal(self, request): """ A static link to the map of the proposal. """ ballot = getattr(self, 'proposal', None) if ballot: return redirect(request.link(ballot, name='entities-map')) raise HTTPNotFound()
42acf262defad98aee6ebd6177fcf644669e753a
47,287
def _format_artifact(tuple, flink_version, scala_version, classifier = None, neverlink = False): """Formats the given artifact tuple. """ group = tuple[0] artifact_id = _replace_scala_artifact_version(tuple[1], scala_version) version = None if group == _FLINK_GROUP: version = flink_versi...
ab935e79edc217eaefb4a48e4ae236e098adf380
47,288
def create_input_list(pdb_list_fname): """ create a list of tuples (pdb_id, chain) from a text file """ pdb_list = [] with open(pdb_list_fname, 'r') as f: for record in f.read().splitlines(): pdb_id, chain = record[:-1], record[-1] # check PDB ID and chain are valid ...
d02588ec1d2ff55454782b337ac15cf9e6f67a80
47,289
def PreDataViewCtrl(*args, **kwargs): """PreDataViewCtrl() -> DataViewCtrl""" val = _dataview.new_PreDataViewCtrl(*args, **kwargs) return val
d522fee41438c7514b2c36b90f8b6c3498b770f2
47,290
def guess_industries(companies, return_prob=False, cutoff=ind_cutoff): """ The function guesses industries and probabilities based on company names. """ try: global _model _model = IndustryModel.load() if companies: return cur_model.predict(_model, companies, return_prob, cut...
ed1e883e26bce9013f08fcf552f6e831e1344fe4
47,291
def get_drawing(doc_id, drawing_num): """Summary Args: doc_id (str): Document identifier (e.g. patent number) drawing_num (str): Drawing number, e.g. "1" Returns: bytes: Image data """ key_prefix = _drawing_prefix(doc_id) key = f'{key_prefix}{drawing_num}.tif' tif_d...
83961a63569aecaa77e0ae3cb587a280e249ec1e
47,292
def _query_worrying_level(time_elapsed, state): """ Gives a "worriness" level to a query For instance, long times waiting for something to happen is bad Very long times sending is bad too Return a value between 0 and 1 rating the "worrying level" See http://dev.mysql.com/doc/refman/5.7/en/genera...
383e36c75d68a9e975d48efc6c68deeee446c987
47,293
def do_color(msg, style): """ print the message in color if it can be handled""" return msg if can_handle_color() else colorit(msg, style)
42ca6f1c883a678e6c9c34bad898a071f94b47a5
47,294
def sce2t_vector(k1, in11): """sce2t_vector(SpiceInt k1, ConstSpiceDouble * in11)""" return _cspyce0.sce2t_vector(k1, in11)
5696292aa1614427d6498216988e100f9416e13e
47,295
def cross_entropy_loss(pred,labels): """ Does an internal softmax before loss calculation. args: pred- batch,seq,input_size labels-batch,seq(has to be transformed before comparision with preds(line-133).) """ checkdatadim(pred,3) checkdatadim(labels,2) batch,seq,size=pred.sha...
13fc0bb5288940db30d4f83b1a92fd4eb6c43d54
47,296
import cartopy.crs as ccrs def latitude_from_cross_section(cross): """Calculate the latitude of points in a cross-section. Parameters ---------- cross : `xarray.DataArray` The input DataArray of a cross-section from which to obtain latitudes. Returns ------- latitude : `xarray.Da...
9c023cb21ae433884db7633601e75d977ed9e202
47,297
def dict_to_casl_rules(rules: dict): """ Given a dict where the keys are the subject and the values are the actions, return a list of dicts ready to be serialized as JSON :return: """ perms = [] for key, actions in rules.items(): perms.append({ 'subject': key, ...
5d0f3dfd610a1cd7deb7f09a668e291997419b2a
47,298
def svn_fs_paths_changed2(*args): """svn_fs_paths_changed2(svn_fs_root_t * root, apr_pool_t pool) -> svn_error_t""" return _fs.svn_fs_paths_changed2(*args)
202f24e3e7a8fdb4c0fafff9efa95cf58b5ecb6d
47,299
def clamp(x, lower, upper): """ Naive Clamping in [2] A [[ x ]]_b = min(max(u,b_lower),b_upper) :param x: :param lower: :param upper: :return: """ # Not None assert x.shape == lower.shape assert x.shape == upper.shape assert (lower.array <= upper.array).all(), " lower is larg...
a50bb4ce270422cad194ed66a0c77f2c498af68f
47,301
import math import time def main(lr=None, log_path_end='', bs=None, train_epoch=None, lambda_list=None, random_mirror=False, random_scale=False, model_weight=None): """Create the model and start the training.""" tf.reset_default_graph() args = get_arguments() """ Get configurations here....
3dd4e9f97a850fe871a64500b8eb407bf36c0cec
47,302
from typing import Dict from typing import List import collections def make_category_to_builders_dict() -> Dict[ str, List[tfds.core.DatasetBuilder] ]: """Loads all builders with their associated category.""" datasets = _all_tfds_datasets() print(f'Creating the vanilla builders for {len(datasets)} datasets....
50a1aa7c4584f151daa5be2ef58f5c288b84c733
47,303
def trajnet_sample_eval(pred, gt): """Calculate ADE, FDE, Pred_Col, GT_Col for one sample. pred = Num_ped x Num_timesteps x 2 gt = Num_ped x Num_timesteps x 2 """ return ade(pred, gt), fde(pred, gt), pred_col(pred, gt), gt_col(pred, gt)
9e4c02d7d39955ee127e400118cb367d900dae36
47,304
def bbox_hflip(bboxes, img_width): """horizontal flip the bboxes ^ ............. . . . . . . . . . . . . ............. ^ Args: bbox (ndarray): bbox ndarray [box_nums, 4] flip_code (int, optional): [description]. Defaults...
00e45f69a517ccb15623afb813fc05ad1c7c7eee
47,305
def _pathjoin(a, b): """ POSIX-like path join for Globus Transfer paths As with _normpath above, this is meant to behave correctly even on Windows systems """ if not b: # given "" as a file path return a elif b.startswith("/"): # a path starting with / is absolute return b ...
20079d97be4e07499a9b0dfa80458a7e151826c3
47,307
def is_current_user_admin(request): """Checks whether the current user is an admin.""" user = get_current_user(request) if user: return user.is_superuser else: return False
3b25bf2d5640b6d52d58aad8e3a57efe3bae9f17
47,309
def _load_fidel_to_opt_parameters(param): """ Loads fidel_to_opt parameters. """ if isinstance(param, (list, tuple)): ret = [] for elem in param: ret.append(_load_fidel_to_opt_parameters(elem)) else: ret = param # just return the param if isinstance(param, unicode): ret = unicode_to_st...
22d8358ba599e5f7161a29bf60bd6ece07314b3f
47,310
def get_sans(names): """ :param SubjectAltNames names: :rtype: dict[str, bool] """ sans = dict() if names.dns_allowed is not None: sans[RPA.TPP_DNS_ALLOWED] = names.dns_allowed if names.ip_allowed is not None: sans[RPA.TPP_IP_ALLOWED] = names.ip_allowed if names.email_all...
625b10531b9ca03005242ffd3d6c74198084eff3
47,311
def get_observed_I_and_R(country: str, is_country: bool = True): """ Gets the data for the number of confirmed cases and the number of recovered. :param country: The country or province for which to get the cases :param is_country: Whether the country variable is for a country or for a province :re...
bb2b632b77cfc8646754920573f25cb144d0265b
47,312
def ClearChannelRequestHeader(sid, cid): """ Construct a ``MessageHeader`` for a ClearChannelRequest command. Clears a channel. This command will cause server to release the associated channel resources and no longer accept any requests for this SID/CID. Parameters ---------- sid : ...
fbd80892006211dd82e0e3313f9e0cb9ee0fe889
47,313
def refine_pic_group_msg(ctx: GroupMsg) -> _PicGroupMsg: """群图片/表情包消息""" if not isinstance(ctx, GroupMsg): raise ContextTypeError('Expected `GroupMsg`, but got `%s`' % ctx.__class__) if ctx.MsgType == MsgTypes.PicMsg: return _PicGroupMsg(ctx) return None
d8529e461bc9af7292bc899db183a8bb1812c44d
47,314
def crunch_samples(standards, standards_exclude, timestamps_standard, signal_standard, peaks_idx_standard, peaks_area_standards, samples_filename=None, samples_directory='samples', ...
987c968d97855d66b41e1172968f094179a8e075
47,315
def str_static_gen(size): """Returns an encoded static string of length 'size'.""" msg = '\n' msg += '__________Hello_World__________' while (len(msg)) < (size): msg += num_to_char(len(msg) % 16) msg = (msg[:size]) if len(msg) > size else msg return msg.encode('ascii', 'replace')
cf5d3fb8211802e0e05dff299861b0d9e328d763
47,316
def rank(M,pref=None): """ Rank solutions: - By Pareto front subpopulation - Distance to ideal vector """ distance = dist(M,pref=np.abs(pref)) fr, fix = fronts(M) strata = np.zeros(shape=len(distance),dtype=int) for i in np.arange(0,len(fix)): for j in fix[i]: ...
b171fa8bbd7db0cb08d0116d93af6785f999ec85
47,317
from typing import Tuple def calculate_temperature_factor( temperature_active: float, power_ratio: float, ) -> Tuple[float, float]: """Calculate the temperature factor (piT). :param temperature_active: the ambient operating temperature of the resistor in C. :param power_ratio: the ratio o...
3eefcf31978d0f20ecfab8c485e05b6a318cb574
47,318
def probability(vector, x, t): """ Finds the probability of vector[x] in t occurnences If x is not in vector then the probability is .001/t @param {Vector} vector {int} x {float} t @return {float} """ t = t*1.0 return vector[x] / t or 0.001 / t
bb6c731a157104a653669730be0569f555402167
47,319
def create_testing_eeg_data(): """Create testing data with HFO and a spike.""" freqs = [2.5, 6.0, 10.0, 16.0, 32.5, 67.5, 165.0, 250.0, 425.0, 500.0, 800.0, 1500.0] random_state = 0 fs = 5000 n = fs * 10 data = np.zeros(n) hfo_samps = [] # basic_amp = 10 x = np.arange(n...
bfa9cc9c5ba510c637c3215d02c05e035c54a0e7
47,320
def getNodeDictVlans(nodesInfo, hostname, switchName): """Get Node dictionary.""" if not nodesInfo: return None, {} for _, nodeDict in list(nodesInfo['nodes'].items()): if nodeDict['hostname'] == hostname: for intf, intfDict in list(nodeDict['NetInfo'].items()): p...
1113f0eb1829c9e84791ed151ce05c7165168b10
47,321
from rasterio._io import windows_intersect def intersect(*windows): """Test if windows intersect. Parameters ---------- windows: list-like of window objects ((row_start, row_stop), (col_start, col_stop)) Returns ------- boolean: True if all windows intersect. """ ...
a4113022e6ffc1bb38d2427c9ede0496271205d3
47,322
import numbers def check_state(seed): """Turn seed into a np.random.RandomState instance Parameters ---------- seed : None | int | instance of RandomState If seed is None, return the RandomState singleton used by np.random. If seed is an int, return a new RandomState instance seeded wi...
d7083e6ddfb094272b12f920d85bf8617bb1719d
47,323
def gen_edo(x, DBplot=False): """Generate EDO Γ[x(n)] from simple formula in the time domain: Γ[x(n)] = y(n)² + H[y(n)]² where y(n) is the derivative of x(n) using the central-finite method and H[.] is the Hilbert transform. Parameters ---------- x: ndarray input signal DBplot...
b190618ba48f8f63fe6c1c97768fb3d427bef407
47,324
def fetch_mps_government_roles_raw(): """Fetch government roles for all MPs.""" return members.fetch_government_roles_raw( house=constants.PDP_ID_HOUSE_OF_COMMONS)
25be217fdb2d957be4f1fa12c74781a0bbe37bcf
47,325
import time def delayed_plus1(x): """Sleeps for 100ms then returns x+1.""" time.sleep(0.1) return x + 1
aa63eb61e112342be3bcd0f7a5e0118006b76c07
47,326
def view_link(url, args, appended='', text='View'): """ Helper function for generating view links """ return '<a href="' + reverse(url, args=args) + appended + '">' + text + '</a>'
73e0a24c1a064fb5d9928ed342c5ac0b798ddb74
47,327
def rob(nums): """ You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent...
9bfb631b2781bbf95fa299a6474e0b1fe36ac19b
47,328
def dashboard(): """Displays the dashboard template. Returns: str: HTML Template """ data = {} try: data = { 'experiments': Experiment.get_status(current_app.config.get('container')), 'migrations': get_migration_status(), } except InvalidRequestE...
79ddb0acbe87df63afb8af0f60dd8c41548a5830
47,329
def tamiz1(m): """Algoritmo clásico para el tamiz de Eratóstenes""" l, n = [i for i in range(2, m+1)], 2 while n: for i in l[l.index(n)+1:]: if i % n == 0: l.remove(i) if l.index(n) +1 < len(l): n = l[l.index(n) + 1] else: return l
3063e5007360cfbbda53e10b84e7ca141473a552
47,330
def _sincfunc(x, dx, dampfac=3.25): """sinc helper function for sincshift()""" if dx != 0.0: xx = (x+dx)*np.pi #- cache shifted array for 30% faster evals return np.exp( -(xx/(dampfac*np.pi))**2 ) * np.sin(xx) / xx else: xx = np.zeros(len(x)) xx[len(x)//2] = 1.0 retu...
d642f4e9ed4e97d4ea3ffa837ddd2dbb9efe13d4
47,331
def data_preprocess(data): """ Perform data procession """ field_list = [] ### On `param_1`(76% is null), `param_2`(86% is null), `param_3` (89% is null) # This three params are text-type, and most of them are empty. # Concat `description`+`title`+`param_1`+'param_2'+`param_3`+`city` ...
71c5f554677320ee99a51116dbed3b4073b81e51
47,333
import string import random def get_random_string(length=5): """ Generates a random string of fixed lenght """ letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(length))
bf3d8734f414065cea93940c8ad1d46d4158813f
47,334
import networkx as nx def FragGraph(G, bondOrderThreshold=1.2): """ Fragment all bonds with Wiberg Bond Order less than threshold Parameters ---------- G: NetworkX graph bondOrderThreshold: int thershold for fragmenting graph. Default 1.2 Returns ------- subgraphs: list o...
e19d211fb1173a72f3c19017654565014cbd421d
47,335
def plot_referendum_map(referendum_result_by_regions): """Plot a map with the results from the referendum. * Load the geographic data with geopandas from `regions.geojson`. * Merge these info into `referendum_result_by_regions`. * Use the method `GeoDataFrame.plot` to display the result map. The result...
97db169d88e5fffa2c5a68986ef37d45ab80bbaf
47,337
def keep(attrs, tweets): """Strip each tweet so as to keep only the given attributes. Attributes are given as a list of the form: ['text', 'user.screen_name', 'user.name'] where the dot notation represent embedded dicts: tweet = { 'text': "This is a tweet." 'user':...
36c914246ea97b51993efd78f9059a2cd5f7d9d9
47,338
import struct def get_payload() -> bytes: """This function returns the data to send over the socket to the server. This includes everything - the 4 bytes for size, the nop slide, the shellcode, the return address (and the zero at the end). WARNINGS: 0. Don't delete this function or change it's n...
f5e697e2d7f344b13ce19ea0cf465931b6c4bdac
47,339
def _get_last_playthrough_information(last_playthrough_model): """Returns an ExpUserLastPlaythrough domain object given an ExpUserLastPlaythroughModel loaded from the datastore. Args: last_playthrough_model: ExpUserLastPlaythroughModel. The last last playthrough information loaded from ...
48ce04d882e35392a99f66b33fbcd8fd23da0135
47,341
import re from bs4 import BeautifulSoup def process_html(html): """Processes HTML for embedded code using SyntaxHighlighter Determines languages used by checking class attribute of pre tags with name="code". Args: html: HTML to be processed for embedded code Returns: The modifie...
a35c0fa79ad387d6df564d7c556cd408423b2c55
47,342
from typing import Tuple def get_movie_info(cap: cv2.VideoCapture) -> Tuple[int, int, int, float]: """get movie information Args: cap (cv2.VideoCapture): cv2 video object Returns: Tuple[int, int, int, float]: W, H, total frame, fps of movie """ W = int(cap.get(cv2.CAP_PROP_FRAME_WIDT...
3cf95dec3730bad0f46af494556b8272fffbea05
47,343
import numpy import warnings def getMetrics(sector, symbols): """Returns a 2xN numpy.Array of metrics for the given symbols from the given sector. """ metrics = [ # hard-coded for now, could easily be parameterized "Price Performance (52 Weeks)", "Standard Deviation (1 Yr Annualized...
df00d21031056bb2faf3ad9d420c308cdf075b5a
47,345
def get_prediction_datas(date=None): """ retourne les donnees predictes """ if not date: # on prend partant de la date actuelle #date = datetime.datetime.now() pass date = config.TEST_DATE # datas datas_df = model_request.get_prediction_datas(date) # data...
0949acb1b7a9ec5bcd83cc595e20bd95689da441
47,346
def testConnection(base_url=server_address): """ :param base_url: String; server address with port number. :return: Boolean; True if connection is done, false otherwise. """ try: get(base_url, timeout=5) return True except ConnectionError or Timeout: return False
eafe1d4fe5f54e868912f264f21a55f491b99ddc
47,347
def getUser(username: str): """Get user login and url.""" return getGithubApiRequestJson("users/" + username)
e68b977e4083776f5e8299113e8bf049790701de
47,348
def initStandard(cls, init=None): """ Standard initialization for population distributions, inserted by :class:`PopulationDistributionMeta`. Will call the provided initialization method as well. :param cls: The class being initialized :type cls: A class of type :cl...
2d81363fa86ecc5a2456de037307df1fdab40169
47,349
def get_best_downloader(downloader=None): """Choose among a set of 4 popular downloaders, in the following order: - wget - curl - powershell - insecure (Python) Args: downloader (str, optional): Use a given downloader. One of wget|curl|powershell|insecure. Defaults to None. ...
00a5f07485fbcc3944533a2798a864fe20fd18da
47,350
def np_parse_pcap_worker(filename): """Parse a pcap file into a numpy matrix. Inputs: - filename : a pcap file that contains packets to parse Returns: - a numpy matrix where each row is a packet and each column is a different field - a numpy column array containing the correspondi...
73d651e4d0e0524f7fe2c4e8415f213d64566edc
47,351
def get_btis(gtis, start_time=None, stop_time=None): """ From GTIs, obtain bad time intervals, i.e. the intervals *not* covered by the GTIs. GTIs have to be well-behaved, in the sense that they have to pass ``check_gtis``. Parameters ---------- gtis : iterable A list of GTIs ...
5197776b1351f1c657c4d2b526cd12086b9aa489
47,352
def greedy_find_clique(graph, progress=False, nodes=None, ordering_func=None, node_deletion=True): """Finds the graph's clique (largest complete subgraph) """ graph_order = graph.order() if graph_order == 0: return [] if nodes is None: nodes = list(graph.nodes...
bb9389019a5a7d3d3c7c442bc36e32a4a8c154d1
47,353
import json def patch_truck(client, truck_id, **kwargs): """ attempts to change the specified row in truck :param client: the client to make the request with :param truck_id: the id of the truck to change :param kwargs: the data that needs to be changed :return: """ return client.patch...
b416a9a2662ae0b44adde8d1d361bad54706e90a
47,354
def get_lists(tab=None, cfg="tlut"): """ Returns: loss_list, acc_list """ if cfg == 'tlut': # loss = get_cell_vals(tab, 'B6:B20') loss = [0.0296, 0.044, 0.0612, 0.0997, 0.1713, 0.2981, 1.6251, 1.9081, 2.0437, 1.8245, 2.1162, 2.2531, 2.2789, 2.3028, 2.3035] # acc = get_ce...
48048c32f612086796545392f35d5145bdf0fc5c
47,356