content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import torch def nn_capacity(dataframe, d_in, H, h_2, d_out, N): """ Takes a dataframe, the number of inputs, the number of nodes for the first hidden layer, the number of nodes for the second hidden layer, the number of outputs, and the total number of datapoints as the input parameters and retur...
0ac4090309177fc2f59f2234540a57f924e70227
45,009
def greedy_best_k_matching(smp, k=1, nodewise=True, edgewise=True, verbose=False): """Greedy search on the cost heuristic to find the best k matchings. Parameters ---------- smp: MatchingProblem A subgraph matching problem. k: int The maximum number of solu...
dbb6684f7aa16125b492da1f325a32a82e5d9247
45,010
from aea_cli_benchmark.case_multiagent_http_dialogues.case import run from typing import Any from typing import List from typing import Tuple def main( duration: int, runtime_mode: str, runner_mode: str, start_messages: int, num_of_agents: int, number_of_runs: int, output_format: str, ) ->...
9d3845d544d73ac4bef457852430ceffd001fb10
45,011
def moments_coords_central(coords, center=None, order=3): """Calculate all central image moments up to a certain order. The following properties can be calculated from raw image moments: * Area as: ``M[0, 0]``. * Centroid as: {``M[1, 0] / M[0, 0]``, ``M[0, 1] / M[0, 0]``}. Note that raw moments ...
e5db83e34fe38350e994e140ca0070876c5a924b
45,013
import google def google_logout(): """Revokes token and empties session.""" if google.authorized: try: google.get( 'https://accounts.google.com/o/oauth2/revoke', params={ 'token': google.token['access_token']}, ...
a8fd75a1d88b308cf6202663ed01d7149d07fb66
45,014
def region_overlap( label_no: int, label_img_outer: np.array, label_img_inner: np.array, overlap_thresh: int = 0.5, ) -> int: """Determine which two regions overlap in two label images. Args: label_no (int): Label number in the inner label image to look for overlap with. label_i...
78cdf69d7c314ff2e3335566e792afcc8a183f7e
45,015
def calc_lambda_r(r, r1, r2, r3, r4, En): """ Mino time as a function of r (which in turn is a function of psi) Parameters: r (float): radius r1 (float): radial root r2 (float): radial root r3 (float): radial root r4 (float): radial root En (float): energy ...
823e209831b90fb7b6bf58bbb12ed35e9244cf74
45,016
from s3db.pr import pr_address_anonymise as anonymous_address, \ def br_person_anonymize(): """ Rules to anonymize a case file """ ANONYMOUS = "-" # Standard anonymizers pr_person_obscure_dob as obscure_dob # Helper to produce an anonymous ID (pe_label) anonymous_id = la...
63eb538f7dce0a7ef58cc3e7125a90e77238ea2f
45,017
def pack_up_static_knapsack_2() -> Knapsack: """ [ Item(name='book', value=1, weight=1), Item(name='food', value=2, weight=1), Item(name='jacket', value=2, weight=2), Item(name='water', value=6, weight=4) ] """ items = ( Item('water', 6, 4), Item(...
cfa2cf72bc549024eea8b549f0f3b97c3d84b680
45,018
from .old import tag from artagger import Tagger import pip from artagger import Tagger def pos_tag(text,engine='old'): """ ระบบ postaggers pos_tag(text,engine='old') engine ที่รองรับ * old เป็น UnigramTagger * artagger เป็น RDR POS Tagger """ if engine=='old': elif engine=='artagger': if sys.version_inf...
62203bf97449a9fca6642add2beed9826f19a585
45,019
def gen_app_with_di_test() -> UserAppService: """依存解決を実行(テスト用)""" def bind_repository(binder): binder.bind(IUserRepository, to=UserInMemoryRepository(), scope=singleton) class DatabaseModule(Module): @provider @singleton def provide_repo(self, repo: IUserRepository) -> Use...
1a36d72a0fcea88c219d68ddf1188c8dda2b65c9
45,021
def to_millis(seconds): """ Converts the time parameter in seconds to milliseconds. If the given time is negative, returns the original value. :param seconds: (Number), the given time in seconds. :return: (int), result of the conversation in milliseconds. """ if seconds >= 0: return int...
818409afa643dbb8de73c35348a08508227b75a3
45,022
from typing import cast def var(input, axis=None, dtype=None, ddof=0, keepdims=False, name=None): """Variance across an axis. Parameters ---------- input : tensor_like Input tensor. axis : int or None, default=None Axis along which to reduce. If None, flatten the tensor. ...
cdf5a47c48e18bcb0426f8f87d45664afdf2f75c
45,023
def find_closest_pair_edges(edges_a, edges_b): """ Find the edges in edges_a and edges_b that are closest to each other """ def length_func(pair): e1, e2 = pair return (calc_edge_median(e1) - calc_edge_median(e2)).length pairs = [(e1, e2) for e1 in edges_a for e2 in edges_b] return...
b201626597f0a5ecdecd0ceabaacf110e4de84c3
45,024
from pathlib import Path import re def find_version(): """Retrieve the version.""" constpy = Path("dataplaybook/const.py").read_text() version_match = re.search(r"^VERSION = ['\"]([^'\"]+)['\"]", constpy, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to f...
a7766a2a3977e0ba2ace33a4c4e9aad64930ace2
45,025
import random def enforce_service_mode(services, FetcherClass, kwargs, modes): """ Fetches the value according to the mode of execution desired. `FetcherClass` must be a class that is subclassed from AutoFallbackFetcher. `services` must be a list of Service classes. `kwargs` is a list of arguments...
7f6164c53bcbb334987b2e81f3dd9c78e569a3c6
45,026
import json def get_all_items(): """ Get all items """ if DATASTORE == "DynamoDB": response = table.scan() if response['Count'] == 0: return [] else: return response['Items'] else: # We want info_hash, peers, and completed. items = ...
3da5bdc760fb497d606a0c16051f4660c965a25a
45,027
def escape_nl(msg): """ It's nice to know if we actually sent a complete line ending in \n, so escape it for display. """ if msg != '' and msg[-1] == "\n": return msg[:-1] + "\\n" return msg
dc30ee05b9985eb69a4e22f2603f739788b22dc8
45,028
def dmp_fateman_poly_F_2(n, K): """Fateman's GCD benchmark: linearly dense quartic inputs """ u = [K(1), K(0)] for i in xrange(0, n-1): u = [dmp_one(i, K), u] m = n-1 v = dmp_add_term(u, dmp_ground(K(2), m-1), 0, n, K) f = dmp_sqr([dmp_one(m, K), dmp_neg(v, m, K)], n, K) g = dmp_...
6c8fe970d1b712355d1f66ba80d768abbfecac1e
45,029
def noun(name: str, num: int) -> str: """ This function returns a noun in it's right for a specific quantity :param name: :param num: :return: """ if num == 0 or num > 1: return name + "s" return name
ccf9fd3f459e8d8946aded4435368231d54cac9f
45,030
def extract_measurements_for_phase(scalars_for_samples): """Convert scalars to simplified dictionary. Returns only uptake and production rates. :param scalars_for_samples: dictionary with lists of replicated scalars across samples :return: list of dictionaries of format {'id': <metabolite id (...
dc6d3ca73677ce1d9cd7ec5e23e52ee05531c08c
45,031
def scrape_all(): """Scrape data from four Mars websites and return dictionary of results.""" # Initiate headless webdriver for deployment # Set up Splinter (prepping the automated browser) executable_path = {"executable_path": ChromeDriverManager().install()} browser = Browser("chrome", **executabl...
258ec8af935e902614cd60721e68f707baa96434
45,032
def filters_from_params(params): """Returns a list of filters (filter context) built from parameters""" filters = [] if params.get('f_list'): filters.append(Q('terms', email_list=params['f_list'])) if params.get('f_from'): filters.append(Q('terms', frm_name=params['f_from'])) if para...
8f91a2695234c69b1c4488e863ac3eba18d8cdc7
45,033
def surface_weighted_three_modes(dp, n1, gm1, gsd1, n2, gm2, gsd2, n3, gm3, gsd3): """ Discrete PDF for a lognormal distribution of particle size for a 3-mode distribution weighted by surface. :param dp: The particle diameters at which to evaluate the PDF...
957cd2bc830bf2ccb633c89a9bde024581227e4f
45,034
def compareChecksum(msgBytes, checksumBytes): """Compute and compare Li-1 message checksum. Args: msgBytes: Raw message bytes. checksumBytes: Checksum to compare against. Returns: A boolean of whether checksum matched or not. """ checksum = calc8bitFletcherChecksum(msgBytes) ...
83a09b55e37e49c7d245d7e47142b5d598324e7e
45,035
def get_assessor_dict(assessor_label, assessor_path): """ Generate the dictionary for an assessor from the folder in the queue :param assessor_label: assessor label :param assessor_path: assessor path on the station :return: None """ assessor_dict = dict() keys = ['project_id', 'subject...
b3fd02f730ef6d966ddec562f0ed40a6ac12ef78
45,036
def token_literal(token_text: str): """ Generates an token lambda file which always returns the same value, this is used for testing, and also as an example of how to write token managers Parameters: token_text(string): the token which should always be returned by the lambda Return: ...
a424211cb527e7acd4eba90c6a4d79505974aac0
45,038
def loop_through_addresses(addresses, recipients, header): """ Loop through all addresses. :param addresses: user address input. :param recipients: list to store all addresses. :param header: message label (To, Bcc or Cc) :return: email addresses. """ try: for recipient in addres...
308689a821cc40d417cf7e81e490050890028f85
45,039
import torch def _rmse(y, y_hat): """RMSE""" y_hat = y_hat.unsqueeze(1) if y_hat.dim() == 1 else y_hat y = y.unsqueeze(1) if y.dim() == 1 else y assert y.shape == y_hat.shape assert y.dim() == 2 assert y.shape[-1] == 1 return torch.nn.functional.mse_loss(y, y_hat).pow(0.5)
b44402511f0e2acf48e9c9210ffa9f023c9a5ca0
45,040
def get_number_as_words(n): """ Gets the integer number returns corresponding string words :param n: integer :return: """ if n == 0: return zero return normalize(abs(n))
944157ec7311c5f52537bfd49b7896ff4e0adde7
45,041
from typing import Any from typing import Mapping def async_replace_list_data( data: list | set | tuple, to_replace: dict[str, str] ) -> list[Any]: """Redact sensitive data in a list.""" redacted = [] for item in data: new_value = None if isinstance(item, (list, set, tuple)): ...
ce2463f5807d053ee642b3acaf4b085aaead6086
45,042
def role_exists(handle, name, **kwargs): """ checks if a role exists Args: handle (UcsHandle) name (string): role name **kwargs: key-value pair of managed object(MO) property and value, Use 'print(ucscoreutils.get_meta_info(<classid>).config_props)' ...
614492a8f3ed2851e287a0fcdbb20781136f6fb2
45,043
def appliance_get_api( self, ne_pk: str, url: str, ) -> dict: """Pass along a GET API call to an appliance .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - appliance - GET - /appliance/rest/{nePk}/{url : (.*...
ef01d3db7cb213438f380e471404605fcd80d892
45,044
from datetime import datetime import csv import requests import time async def main(): """Main method.""" forceQuit = False while not forceQuit: async with ClientSession(headers={'Connection': 'keep-alive'}) as session: print('') print('#####################################...
414cd5bf049fdd053b79de8a01adb726bfab287a
45,045
import re def build_tx_cigar(exons, strand): """builds a single CIGAR string representing an alignment of the transcript sequence to a reference sequence, including introns. The input exons are expected to be in transcript order, and the resulting CIGAR is also in transcript order. >>> build_tx_...
a05211d4dbf04fa6cef8e1e595227985de8e7a36
45,046
def get_toeplitz_dictionary( n_samples=20, n_features=30, rho=0.3, seed=0): """This function returns a toeplitz dictionnary phi. Maths formula: S = toepltiz(\rho ** [|0, n_features-1|], \rho ** [|0, n_features-1|]) X[:, i] sim mathcal{N}(0, S). Parameters ---------- n_samples: int ...
18f6d3c0e13e967f518489e9047a8c34a7157977
45,048
def DictionaryofDate_valuetoArrays(Date_value): """Returns (array): date, value """ date = Date_value.keys() date.sort() value = [] for d in date: value.append(Date_value[d]) return date, value
d4ad630457fc03f9f193515ae51c52f438b0cd81
45,049
from pathlib import Path import re def song_html_file_path(song: Song) -> Path: """Return absolute artist song HTML file path. Parameters ---------- song Song. Returns ------- :cod:`Path` Absolute artist song HTML file path. """ song_file_name = re.sub(r"[\s/]", "...
5cbb8eb4df7d5cb5732b893c9ef9e94e968110d2
45,050
def area_separate(cnt): """ Calculates the total area of a list of contours. Args: * cnt - list of contours, as returned by cv2.findContours Returns: * total area """ return sum([cv2.contourArea(x) for x in cnt])
6cdb59b7a3ceef4dc79c8a8742284ce0d62aca21
45,052
def get_id_from_cache(username: str) -> str: """Check if username exists in cache, return their slack_id. Args: username: slack username Returns: slack_id """ dynamodb = boto3.resource("dynamodb") if not CACHE_USERS_TABLE: raise Exception( "env var CACHE_USERS...
6215839febce0f68b1702ab7dabb5b9699dcb09c
45,053
def animate_aux(i, bg_int, faces, face_lines): """perform animation step""" bg_int.sample() for k, f in enumerate(face_lines): f.set_data(face_position(bg_int, k, faces)) ## Fix for multi face animations. #line.set_data(face_position(bg_int, 0, faces)) #line2.set_data(face_position(bg_in...
a56151497d320e344aa7997c956c87cdc597b2be
45,054
import re def cassini_time(time): """Parse Cassini time. Parameters ---------- time: str, int or float Cassini time. Returns ------- float Parsed Cassini time as float. Raises ------ ValueError If the input time pattern is invalid. Examples -...
bc14c2803e04ed690fac75eb32d72b27a803f1ad
45,055
def _onset_by_mfcc(input, framesize=1024, hopsize=512, fs=44100): """ Onset detection by delta MFCC Parameters: inData: ndarray input signal framesize: int framesize of MFCC hopsize: int hopsize of MFCC fs: int samplingrate Returns: ...
6f021326f79905d3424cb3f45ede1419d9b7f129
45,056
def _ClientDataContainer_GetClientObject(self): """ Alias for :meth:`GetClientData` """ return self.GetClientData()
6e8369df36d9c649dca694fe2df240f1ed63cbfa
45,057
def kabsch(test, ref, wgt=None, refl=True): """Returns the Kabsch rotational matrix to map a test geometry onto a reference. If weights are provided, they are used to weight the test vectors before forming the covariance matrix. This minimizes the weighted RMSD between the two geometries. If refl=T...
c503b9e578c6ac6f12f3f69ec715232b8a42abd8
45,058
def _create_run_config(): """Creates a TPU RunConfig if FLAGS.use_tpu is True, else a RunConfig.""" session_config = tf.ConfigProto(allow_soft_placement=True) run_config_kwargs = { "save_summary_steps": FLAGS.save_summary_steps, "save_checkpoints_steps": FLAGS.save_checkpoints_steps, "save_check...
60c7143c44f54fe6056e455e6645c808b9a20680
45,059
def pods_by_uid(pods): """Construct a dict of pods, keyed by pod uid""" return {pod["metadata"]["uid"]: pod for pod in pods}
44b4167c561e494700e56a4967f731e0bef48aab
45,060
def _tags_conform_to_filter(tags, filter): """Mirrors Bazel tag filtering for test_suites. This makes sure that the target has all of the required tags and none of the excluded tags before we include them within a test_suite. For more information on filtering inside Bazel, see com.google.devtools....
1db9528e11d1b513690af14f1d8453f8b0682d34
45,061
def async(startDelaySeconds=None, name=None, maxAllowedRuntime=None, killSwitch=None, ensureOnlyOne=False): """Decorate a function with this to make it run in another thread asynchronously! If defined with a value, it will wait that many seconds before firing. If a name is provided the thread will be named. Handy fo...
a76da9b03d27287fc88c8521a7f58c3dcad7d035
45,062
from typing import Optional from typing import List from typing import Dict def convert_data(csv_data: pd.DataFrame, subset: str = 'all', exclude: Optional[List[str]] = None) -> Dict[str, Dict]: """ :param csv_data: dataframe with columns "mode", "split", "Structure", "seriesId" or "Patient", and "Dice" :...
139683b291f0e076cca4742a9fd932ca4c39e4ed
45,063
from typing import Optional def get_custom_line_item(arn: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetCustomLineItemResult: """ A custom line item is an one time charge that is applied to a specific billing group's bill. :param str arn: ARN ...
23dfa4c57aa5e529aac19818cd26fb735404d9f0
45,064
def boot(name=None, kwargs=None, call=None): """ Boot a Linode. name The name of the Linode to boot. Can be used instead of ``linode_id``. linode_id The ID of the Linode to boot. If provided, will be used as an alternative to ``name`` and reduces the number of API calls to ...
61a2475d5e54281c45b17fe615cf04746ebd01bd
45,065
def create_rating_definition(*, creator: str, bestrating: int, worstrating: int, name: str = None): """Return a mutation for making a Rating definition. A Rating (https://schema.org/Rating) is an evaluation on a numeric scale. A Rating definition describes the structure that a rating can take. It is used so...
19ba58c1a4fcca3a456bd5466eb2b5c1ee74479e
45,067
def generate_clothoid_paths(start_point, start_yaw_list, goal_point, goal_yaw_list, n_path_points): """ Generate clothoid path list. This function generate multiple clothoid paths from multiple orientations(yaw) at start points to multiple orientations...
5f636c085b9e4573d441425ac2a2547e17612145
45,068
def parse_classes(api_classes): """Parse the API classes data into the format required, a list of dict.""" parsed_classes = [] for entry in api_classes: class_ = {} class_[ATTR_ID] = entry["id"] class_[ATTR_CONFIDENCE] = round(entry["score"] * 100.0, 2) parsed_classes.append(...
d6269603e1542b8020300d399f2aba9e97edf9a2
45,070
def mesh_update_attributes(mesh): """Update the attributes of a mesh. Parameters ---------- mesh : compas.datastructures.Mesh A mesh object. Returns ------- bool ``True`` if the update was successful. ``False`` otherwise. See Also -------- * :func:`mesh...
a94d82dc681eb06ead1d657fec3d50268202605f
45,071
def get(objectid, worker=global_worker): """Get a remote object or a list of remote objects from the object store. This method blocks until the object corresponding to objectid is available in the local object store. If this object is not in the local object store, it will be shipped from an object store that ...
9728f67ee061c4e6af7d0b9128b3d12997f97e72
45,073
def plot_rboxes_on_image(img, boxes, color=[0, 255, 0], thickness=2): """ 旋转的boxes的结构为外接矩形四个点坐标,boxes=[n,8] or [n,4,2] """ if len(boxes.shape) == 2: h,l = boxes.shape boxes = tf.reshape(boxes,shape=[h,4,2]).numpy() boxes = boxes.astype(int) canvas = np.copy(img) for i in rang...
9294cd03a5f214857204691dfd5ab4b6bb425c77
45,074
import optparse def get_options(): """define options for this script and interpret the command line""" optParser = optparse.OptionParser() optParser.add_option("--nogui", action="store_true", default=False, help="run the commandline version of sumo") options, args = optParser....
ce09dfd6de38781b31b1f07f8f52fd5236c850e5
45,077
def getPixelsForInterp(img): """ Calculates a mask of pixels neighboring invalid values - to use for interpolation. """ # mask invalid pixels invalid_mask = np.isnan(img) + (img == 0) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) # dilate to mark borders around invali...
286464f45f79577aa0512efab97bfc53be4b8988
45,078
def set_max_results(uri, max): """Set max-results parameter if it is not set already.""" max_str = str(max) if uri.find('?') == -1: return uri + '?max-results=' + max_str else: if uri.find('max-results') == -1: return uri + '&max-results=' + max_str else: return uri
62793ad686c8abf0e2e750f65d9f709eee2c179e
45,079
def cosine_similarity(a,b): """ Measure of similarity between two vectors in an inner product space. Used for comparing n-gram frequency of e.g. english with the n-gram frequency of a given text, and thus getting a measure of how close the text is to english. """ return dot(a,b) / (norm(a) * nor...
db1fb72fbe519d4809f5c37f0d749435aeea32d8
45,080
def round_frequency(frequency: float) -> int: """Returns the nearest audiologically meaningful frequency. Parameters ---------- frequency : float The frequency to be snapped to the nearest clinically meaningful frequency. Returns ------- float A ``snapped`` frequency value. """ ...
7a66e5a78507a836e80c5a762137bf3fe376894d
45,081
def delete_registry_attr(request, rattr, **kwargs): """ arguments: request, rattr, **kwargs implements: DELETE /api/registry/(RATTR).(FMT) returns: an empty envelope """ m = Registry.get(key=rattr) m.delete() return Envelope(request, result=0)
c3e8ca772e52bdc82c8345638772dde86bc35db1
45,082
def candidates(plist,flist,x,y,dimz,stepsize): """Function to return a list xy-coordinates that indicate which pixels are likely microplastics based on reflectance differences. This function takes the list of pixels with a positive reflectance difference, the whole list of .csv files, the x and y coordi...
ff185c42e3781a5a41aa10fd6ed7c8ba2a497c0a
45,083
import torch def kronecker(mat1, mat2): """ kronecker product between 2 2D tensors :param mat1: 2d torch.Tensor :param mat2: 2d torch.Tensor :return: kronecker product of mat1 and mat2 """ s1 = mat1.size() s2 = mat2.size() return torch.ger(mat1.view(-1), mat2.view(-1)).reshape(*(s1 + s2)).permute([0, 2, 1, 3...
930ac9827b92848656b6579c173b2d7675b7e657
45,084
def from_smile_txt(line_tokens, scale=1): """ line_tokens: a tuple of tokens on a "create" line of a SMILE demo txt file """ kwargs = {"name": line_tokens[2]} def lookup(key): return line_tokens[line_tokens.index(key)+1] if "category" in line_tokens: kwargs["category"] = lookup("category") if "bboxx...
dec892bda2f29d0d71b461e5bd313a3cbdc115b3
45,085
def execute_rule_post(rule_name): """ Use this endpoint to execute the rule engine for a rule for a fact set. --- tags: - Execute Rule Engine parameters: - name: rule_name in: path type: string required: true description: Rule name - na...
fdd0b39baaf1cf7d80f17cd88e3449ffa69a47a0
45,086
def get_mid_geno(np_array, cargs_obj): """ return the genotype with highest probability in the central. """ a_count, b_count, miss_count = _count_genos(np_array) ab_count = a_count + b_count if ab_count > cargs_obj.win_size//2: a_ex_prob = binom.pmf(b_count, ab_count, cargs_obj.error_a) ...
1a6b8f7640602b5967add3a2f24fb5b654b0bb9c
45,087
def current_version(): """Provides version name(not code) : 1.0""" return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName # return "1.0"
fb17040b80cb603cdfccf44920b59a326561624b
45,088
def n2str(num): """ convert a number into a short string""" if abs(num) < 1 and abs(num) > 1e-50 or abs(num) > 1E4: numFormat = ".2e" elif abs(round(num) - num) < 0.001 or abs(num) > 1E4: numFormat = ".0f" elif abs(num) > 1E1: numFormat = ".1f" else: numFormat = ".2f...
42f9f714c49694fdc094ab1802a1c1782e58f942
45,089
def StringCompression(s: str) -> str: """Compresses the specified string using counts of repeated characters. >>> StringCompression("") '' >>> StringCompression("a") 'a' >>> StringCompression("ab") 'ab' >>> StringCompression("abc") 'abc' >>> StringCompression("aba") 'aba...
e23e7f10b4259fed27b57dd3932be53373166821
45,090
import json def _get_json_content(obj): """Event mixin to have methods that are common to different Event types like CloudEvent, EventGridEvent etc. """ msg = "Failed to load JSON content from the object." try: # storage queue return json.loads(obj.content) except ValueError as...
c0ed95cb2a267afa3e0185426a36e9b9225901d2
45,092
from typing import Optional def form_description(elastic_apartment: ElasticApartment) -> Optional[str]: """ Fetch link to apartment presentation and add it to the end of project description """ optional_text = "Tarkemman kohde-esittelyn sekä varaustilanteen löydät täältä:" main_text = getattr(elas...
8f1c50483a94f6ffb14d132908cec304ee699286
45,094
def extractlocalfeature(point_cloud, is_training, bn_decay=None): """ Classification PointNet, input is BxNx3, output Bx40 """ batch_size = point_cloud.get_shape()[0].value num_point = point_cloud.get_shape()[1].value input_image = tf.expand_dims(point_cloud, -1) # input_image BxNx3x1 with tf.vari...
798825ad8b97fd0bc195e5f1720ac6371e21b63b
45,095
def get_reaction_type(name, path = './data', output_format = 'array'): """to retrieve the type of reactions for reaction dataset Args: name (str): dataset name path (str, optional): dataset path output_format (str, optional): output format in dataframe or in raw array format Returns: pd.DataF...
6c39b74c8a5bab989e4819ccc78273cd6a65fd63
45,096
def beavrsMaterials(): """Dictionary of materials from the BEAVRS specification Currently provides: fuel32 -> 3.2 wt% enriched UO2 air -> air zirc4 -> zircaloy 4 cladding water -> unborated water helium -> helium bglass -> boroscillicate glass ss304 -> s...
6328427d7535501c134daa60f739f1f2d5bc9d05
45,097
import re def possibly_fix_width(text): """Heuristic to possibly mark-up text as monospaced if it looks like a URL, or an environment variable name, etc.""" if text in ['', '--']: return text # stringify the arguments if type(text) not in [type('string'), type(u'Unicode')]: te...
36e72e4578aea9d4be735ecec518bd232e7d40db
45,098
from typing import Dict def dfify_clusters(cols: Dict[str, np.ndarray], df: pd.DataFrame) -> pd.DataFrame: """Concatenate cluster ids with their input features. Args: cols (Dict[str, np.ndarray]): Columns to prepend to df. df (pd.DataFrame): inputrecord ids and their features. Returns: ...
9b0209861562a3f110512012f9a9908b17dee0f4
45,099
def weighted_score(raw_earned, raw_possible, weight): """ Returns a tuple that represents the weighted (earned, possible) score. If weight is None or raw_possible is 0, returns the original values. When weight is used, it defines the weighted_possible. This allows course authors to specify the exa...
98ec27ebe606586811945650c18772801edd80a0
45,100
def get_coderef_from(vw, va): """ return first code `tova` whose origin is the specified va return None if no code reference is found """ xrefs = vw.getXrefsFrom(va, REF_CODE) if len(xrefs) > 0: return xrefs[0][XR_TO] else: return None
c3042b1fee0f2aef7952f08e58c7610c96a9e9ae
45,101
def search(word: str) -> str: """查询es中朗文4的example """ if not USE_ES or not CONNECTED_ES: return "" dsl = { "query": { "match": { "han": word } } } res = esClt.search(index=INDEX, body=dsl) html = """<span>朗文4相关例句</span><link re...
a8c380879691a77a797554b835c6529337fef7d1
45,102
def tempDiffRestrict(primerInfo, maxTempDiff=MAX_TEMP_DIFF): """Checks the differnce in annealing temperatures between two primers. Difference should not be greater than 5 degrees.""" for key in primerInfo.copy(): if abs(primerInfo[key][0][1] - primerInfo[key][1][1]) > maxTempDiff: de...
6bb5453e02a60e8cee9039c27ae4240025a9ae0d
45,103
def get_compiler_dir(compiler_name): """ Try to figure out the compiler directory based on the input compiler name. This is fragile and really should be done at the distutils level inside the compiler. I think it is only useful on windows at the moment. """ compiler_type = choose_c...
2cbadc250658a60ea00b698c709ca28b7df99d26
45,104
def PairOHLCSchema(pair): """helper function to embed OHLC data frame parsing into a field with any name... returns a new instance of the class, creating the class if needed """ def build_model(self, data, **kwargs): assert len(data.get('error', [])) == 0 # Errors should have raised except...
b3ccbfb40fb50753f7a63c4b7d319a606e881c74
45,105
def sum_GaussLorentz(x, centers, amplitudes, widths, shapes, baselevels): """add mixed Gauss-Lorentzian curves together Parameters ---------- x : list-like centers, amplitudes, widths, shapes : list-like, 1-dimensional parameters for the individual curves. Lists have lenght n for n curves. ...
3f855f173566bf33375f400e82575ddc4480038e
45,106
def randn(*size, **kwarg): """Returns an array of standard normal random values. Each element of the array is normally distributed with zero mean and unit variance. All elements are identically and independently distributed (i.i.d.). Args: size (ints): The shape of the array. dtype...
5c05e64fd974709cdc4f29d010ef52943233a3fa
45,107
def is_registered(subject, license_uri, metadata): """ Checks for work registration assertions """ # shorthand accessor triples = metadata['triples'] # first check for a has_owner assertion if subject not in metadata['subjects'] or \ not triples[subject].has_key(SIOC('has_owner')): ...
6895a0454339f952e0b04a982519826ff6727cf9
45,108
import pandas import traceback def stddev_from_average(timeseries): """ A timeseries is anomalous if the absolute value of the average of the latest three datapoint minus the moving average is greater than three standard deviations of the average. This does not exponentially weight the MA and so i...
a755ffa60301435895ad8e1f509864e9e9e3ee65
45,110
def call_base_class_method_with_same_name(obj): """ Run base class method. :param obj: class object which methods will be decorated. :return: class object with decorated methods """ if hasattr(obj, "__dict__"): if obj.__dict__.items(): for attributeName in dir(obj): ...
c53d646f4a9aaeb7f8dd7db74eb43414fd2459ae
45,111
def find_matches(descriptors, filter_matches=True): """Match descriptors to themselves Parameters ---------- descriptors: array_like, shape=[n_keypoints, n_features] The array of descriptors Returns ------- matches: list of cv2.Match The found matches """ print(f"Nu...
c0026679c186d46fd977553a871e1c86985b25e4
45,112
def grade_generic(grader_data, numeric_features, textual_features): """ Grades a set of numeric and textual features using a generic model grader_data -- dictionary containing: { 'algorithm' - Type of algorithm to use to score } numeric_features - list of numeric features to predict on ...
a56b4937f73a220449f418677bc689d85f3fcb69
45,113
from core.rule import Rule from conf.rules import getTypeObject from utils.wiki import create_wikirule def add_rule(**kwargs): """ Create a Rule Object from information passed by user, and return a TypeObject who contain the new rule Object. Keyword Args: type (list of one str): rule's type (...
26a22bd6b4a9274b3ab0ec3c782edf41636f1869
45,114
def polygon_from_xywh(xywh): """Construct polygon coordinates in numeric list representation from numeric dict representing a bounding box.""" return polygon_from_bbox(*bbox_from_xywh(xywh))
59fe9fd9bbe3d59075ccfb840c3aa3ceaf570490
45,115
def cargar_datos(): """ Funcion para cargar los datos de la base de datos """ # Cargar datos de la base de datos path_archivos = "./Data/" data_CF = pd.read_csv(path_archivos + "mmm.csv") return data_CF
f4e466c0201256690d3da7c62b5eccc84de6f678
45,116
def bestIndividual(hof, X, y): """ Get the best individual """ _individual = None minAccurcy = 2.0 for individual in hof: # if (individual.fitness.values > maxAccurcy): if individual.fitness.values[0] < minAccurcy: minAccurcy = individual.fitness.values[0] ...
37ced7bf5404243ab5173acb7866eb4aeceaee9a
45,117
def clean_phone(phone_number, drop_invalid=False, area_code='406'): """Standardizes phone number formatting for American numbers""" # Removes non-digit characters clean_number = digit_only(phone_number) # Removes US country code if present if len(clean_number) == 11 and clean_number[0] == '1':...
da3a14d4708ee60e5ade09a42396684419e4943c
45,118
def show_user_status(): """Return True if the application is configured to use the user_status block""" return _django_status_enabled() or _ceda_status_enabled()
769b9903a31084e46b9fc3f40410ffebce6be6e1
45,120
def split_dataset(df, train_proportion, valid_proportion): """Split a dataframe into a train, validation, and test set. The size of the test set will be 1.0 minus the given train and valid proportion. Parameters df - pandas.core.frame.DataFrame The dataframe to split train_propo...
84562dceeaacfa23b1bd50e55b87b0b2f80ed911
45,121
def get_crawl_rate(): """Get the rate used to crawl Parameters ---------- None Returns ------- float The current web crawling rate """ return GLContainer.get_crawl_rate()
93dee16eb0aef93068e6fa618cc81eb56ca38052
45,122