content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def setup_prim(results, classify, threshold, incl_unc=[], **kwargs): """Helper function for setting up the prim algorithm Parameters ---------- results : tuple tuple of DataFrame and dict with numpy arrays the return from :meth:`perform_experiments`. classify : str or cal...
e3747b28c675734866e50208872ceb6ac2b93d8b
56,028
def indexd_client(indexd_server, create_indexd_tables, indexd_admin_user): """Create the tables and add an auth user""" return IndexClient(indexd_server.baseurl, auth=(indexd_admin_user[0], indexd_admin_user[1]))
7cc45ad1140b0893915ba3bf89251693e88cb4d0
56,029
def load_class(module_name, class_name): """Return class object specified by module name and class name. Return None if module failed to be imported. :param module_name: string module name :param class_name: string class name """ try: plugmod = import_module(module_name) except Exc...
d90ed0f39b41fb19db8418c324a75ded96b2d295
56,030
def send_user_email_copy_admins(title, from_address, to_addresses, request, template="email/default.txt", context={}): """ Send a message on behalf of a user to another user, cc'ing the sender and the Perma admins. Use reply-to for the user address so we can use email services that require a...
ee05d2b290cc0bfde0e7ae510e9051e7b9850d12
56,031
def render_row(row): """ Renders a row as an HTML table element. """ return "".join(_render_row(row))
e9f01c246c3d22b9c67cb7236c6561843ba67660
56,032
def dropout(inputs, is_training, scope, keep_prob=0.5, noise_shape=None): """ Dropout layer. Args: inputs: tensor is_training: boolean tf.Variable scope: string keep_prob: float in [0,1] noise_shape: list of ints Returns: tensor variable """ with tf.variable_scope(scope) as sc: outputs ...
4651f66dd7bc7d31f841f5460039724f4578ad38
56,033
import re def checkOS(): """ This finction need from checked OS type and use specific key package manager""" fin = open("/etc/os-release", "rt") data = fin.read() findkey = re.search( r'^NAME=\"Arch Linux\"|NAME=\"Debian GNU/Linux\"|NAME=\"Ubuntu GNU/Linux\"|NAME=\"CentOS Linux\"' r'|N...
ddf1764535afaad15494e7605d46ae011d4c949f
56,034
import gzip def rows_from_gz_flowlog_stream(gz, key): """Return the rows of a compressed stream (.i.e COS object)""" with gzip.open(gz) as bstream: return rows_from_flowlog_stream(bstream, key)
bebdf431944c9121d1a547f1b7b5545e0577e1e5
56,035
def mk_falls(data_id, data): # measurement group 12 """ transforms a g-falls.json form into the triples used by insertMeasurementGroup to store each measurement that is in the form :param data_id: unique id from the json form :param data: data array from the json...
597591e22d1bd5fb4a4f5920a3de6dd4545ac1dd
56,036
def ctrees2arg(trees, names, times, verbose=False, delete_arg=True): """ Convert a C data structure for the ARG into a python ARG """ if verbose: util.tic("convert arg") # get local trees info nnodes = get_local_trees_nnodes(trees) ntrees = get_local_trees_ntrees(trees) # allo...
792819b6e3d5b7ee42f80d44139fadefc7e560c3
56,037
import click def install_package(package_name: str, verbose=True): """ Installs a system package with the given "package_name" """ operating_system = CONFIG['install']['os'] package_install_command = CONFIG['install'][operating_system]['package_install'] click.secho('Installing package "{}".....
a83f5397e3f27fe0bda8f9ad47cf187a14e4c18c
56,038
def query_wolfram_alpha_api(url: str) -> dict: """ Query the Wolfram|Alpha API and return the result :param url: Wolfram|Alpha API URL to query :return: dict status_code, content, encoding """ result = SESSION.get(url) return {"status_code": result.status_code, "content": result...
b4d8ce81304021015d6b4fb239089806afe1d735
56,039
def l2_norm(params): """Computes l2 norm of params by flattening them into a vector.""" flattened, _ = weights_flatten(params) return np.dot(flattened, flattened)
94a74801b450515ead098f008dd6ae320853b84d
56,040
def test_clustercron_returns_1_when_not_master(monkeypatch): """ Test if `main.clustercron` returns 1 when not `lb.master` """ class ElbMock(object): def __init__(self, name): pass def master(self): return False monkeypatch.setattr(elb, "Elb", ElbMock) ...
504a41262a9abeae7d1672041b4e04f3818b112b
56,041
def delete_repo( request, repo_id ): """ Delete a data repository. Checks if the user is the original owner of the repository and removes the repository and the accompaning repo data. """ repo = get_object_or_404( Repository, mongo_id=repo_id ) # Check that this user has permi...
d9b5995c4f1216457386f4ed372733b0407b793b
56,042
import time import requests import socket import errno import random def azure_request(req, timeout=None, *args, **kwargs): """Wrapper method to issue/retry requests to Azure, works with both the Azure Python SDK and Requests Parameters: req - request to issue timeout - timeout in seconds ...
c94072ee98a3a930ee6ad33c205115c12867456e
56,043
def build_params_test(): """Cheap parameter set for test runs.""" params = sitk.GetDefaultParameterMap('translation') return params
9a5dfa25ff34cf0a8418fc753370fcb5b1b41582
56,044
import re def to_kebab_case(input): """Convert a string into its kebab case representation.""" str1 = re.sub("(.)([A-Z][a-z]+)", r"\1-\2", input).replace("_", "-") return re.sub("([a-z0-9])([A-Z])", r"\1-\2", str1).lower()
f2203888f556626271a66dca150e13817fedc1f2
56,045
def locate_hodogram(st: Stream, event: Event, inventory: Inventory, window_length: float = 20e-3, linearity_threshold=0.7): """ measure the incidence angle from hodogram :param st: a stream object containing the waveforms :type st: uquake.core.stream.Stream :param picks: a list o...
01b7198d4d3d314f0df2810b9cec27443178c1d5
56,046
import scipy import collections def location_significant_place_features(df, **kwargs): """Calculates features related to Significant Places""" assert 'speed_threshold' in kwargs speed_threshold = kwargs['speed_threshold'] def compute_features(df): """Compute features for a single user"""...
39d88a26f984762f0484cf190501ade19011a1d0
56,047
def concatenation_based_attention( hidden_states, dt, e_num_units, d_num_units, attention_size, initializer=layers.xavier_initializer(), activation_fn=tf.tanh): """ Concatenation-based Attention args: `hidden_states`: the hidden states of encoder w...
98ac5de6836aee94f572810a24b2597929199242
56,048
from typing import Dict from typing import Any from typing import List def get_human_readable_for_my_asi_insights_command(results: Dict[str, Any], priority: str, active_insights: int, total_insights: int, total_observations: int) -> str: """ Parse and convert...
6f1b1f4770476d7fd9bdcd2981c91886dbc07ec8
56,050
def encode_datetime_to_ml(series, col_name) -> pd.DataFrame: """ This method converts datetime pandas series to machine learning acceptable format. It extracts year, month, day, hour, and minute from the datetime object. The method returns a dataframe, as shown in below example. Example: pd...
c9e61521d3692afea4bc29526e49b9bea3c27e3f
56,051
def get_port(duthost, ptfhost, interface_ranges, port_type): """ Get port configurations from DUT and PTF Args: duthost: DUT host object ptfhost: PTF host object interface_ranges: numbers of ports port_type: Type of port Returns: Tuple with port configurations o...
e13702b7116a61a43dc6298c3b7341a599a2c3f7
56,052
def rank_perturbation_genes(adata, pkey="j_delta_x_perturbation", prefix_store="rank", **kwargs): """Rank genes based on their raw and absolute perturbation effects for each cell group. Parameters ---------- adata: :class:`~anndata.AnnData` AnnData object that contains the gene-wise per...
1134754051458c378a1077ba4b82147bc288ec4f
56,054
def extract_details(df): """Extract step details for last 3 steps (deBoc, BHA and SNAr).""" df_RSinfo = df[['pentamer', 'Step details', 'RouteScore details', 'Isolated', 'RouteScore', 'log(RouteScore)']] last3_rxns = ['Buchwald_deprotection', 'Buchwald', 'SNAr'] for rxn in last3_rxn...
c361f91b36a5270c93739d546779bcbb89944fbb
56,056
from typing import Any def test_for_fraction_exception(item: Any, next_item: Any) -> bool: """ Returns True if a combination 'item' and 'next_item' appear to indicate a fraction in the symbolic deque. False otherwise. e.g. item=deque([...]), next_item="/" -> True item="/", next_item=dequ...
d304eae78319c27f3aa0c185e81c7e6dba0db22f
56,057
def user_num_documents(user): """Count the number of documents a user has contributed to. """ return Document.objects.filter( revisions__creator=user).exclude( html__startswith='<p>REDIRECT <a').distinct().count()
0f7b19cd87d8dfb5f262b8ed799559bf07c49987
56,058
from typing import Optional import torch from typing import Tuple from typing import Iterator from typing import Callable from typing import OrderedDict def cppn( size: int, num_output_channels: Optional[int] = 3, num_hidden_channels: Optional[int] = 24, num_layers: Optional[int] = 8, activatio...
af10dcf402c0455647841aa824ba053a5e231b51
56,060
def validate_velocity(a): """ Checks that the array 'a' is a valid velocity vector, meaning: It must be a scalar, or 1-D array of numbers It must only contain finite and defined values If successful, returns 'a' with the given changes """ a = np.array(a) a = che...
d797f6b18f54e5b41fc5e50ae8bd669136795d27
56,061
def multi_backend_test(globals_dict, relative_module_name, backends=('jax', 'tf'), test_case=None): """See backend.multi_backend_test.""" if test_case is None: return lambda test_case: multi_backend_test( # pylint: disable=g-long-lambda ...
7e3ec1e7cb5b85490b9e54e2ad951ad2786e3fed
56,062
def iam_auth(endpoint_url): """ Helper function to return auth for IAM """ url = urlparse(endpoint_url) region = boto3.session.Session().region_name return BotoAWSRequestsAuth(aws_host=url.netloc, aws_region=region, aws_service='exe...
dab1267360ba80a2bcdb0dd9e00525435d02e0fe
56,064
def create_slider_severity(x: str): """ X = symptom """ return st.slider(f'Please rate the severity of {x}', 1, 3, 1)
f4914c242cbe5a5fb1b9ca5e4562d26eef3c4aef
56,066
def waveform_2_magnitude(waveform, frame_length=512, frame_step=128, log_magnitude=True, n_mel_bins=None, mel_lower_hertz_edge=0.0, mel_upper_hertz_edge=8000.0): """Transform a Waveform to a Magnitude Spectrum. This function is a wrapper for waveform_2_spectogr...
64f1aa8aaaee01875c758c9b40afc33fa3d43af9
56,067
def phaseinfo(xs, ys, sphase): """Compute the mutual information between firing phase and position.""" xbins = ybins = INFO_PHASE_POS_BINS xmin, xmax = INFO_PHASE_POS_XRANGE ymin, ymax = INFO_PHASE_POS_YRANGE pmin, pmax = PHASE_MIN, PHASE_MAX pbins = INFO_PHASE_BINS sample = np.c_[xs, ys, s...
6e00edd738d436f1f29eac9490ee403a050b564e
56,070
from typing import Callable from typing import Any from typing import Union from typing import List from typing import Type def _return_types(func: Callable[..., Any]) -> Union[TypesDict, List[TypesDict]]: """Get the callables return types""" func = _unwrap_function(func) # type: ignore args_spec = getfu...
59a40f1e4fe6d5c5727676fe2134764a8853a8b6
56,072
def create_mixed_plot(dataframe, groupby, primary_measure, secondary_measure, title): """ Description: This function can be used to create a plot with 2 measures Arguments: df: the dataframe group: columns to be grouped of the dataframe (can be multiple ones) primary_measure: the pr...
43de28978877a1d54819d0d75ed30f95b6114add
56,075
from typing import Callable from typing import Tuple def loss( vector_field: Callable, zo: Tuple[np.ndarray], step_size: float, omega: float, mu: np.ndarray ) -> np.ndarray: """A loss function representing violation of the constraint function with respect to the inputs....
65c8f9b53c9d8fd929f22f0797c78f8b44b03223
56,076
def format_singular_csc_error(system, matrix): """ Format a coherent error message when the CSC matrix is singular. Parameters ---------- system : <System> System containing the Directsolver. matrix : ndarray Matrix of interest. Returns ------- str New error...
b833ebdc647cc74a33ed66173d4426b64dbd6d56
56,077
def _is_vcf_version_at_least_0_6_8(): """ The behaviour of vcfReader.fetch changed significantly from version 0.6.8 onwards. :return: boolean """ major, minor, patch = vcf.VERSION.split(".") if int(major) == 0 and int(minor) == 6 and int(patch) >= 8: return True elif int(major) =...
1b9ca7796dc4938cc0265c4886289c7a4c52f585
56,078
import random def random_names(count=10): """Returns a random selection of ``count`` names. No repetitions. """ return random.sample(NAMES_2K, count)
a406919008b874d879eba80f92e9ca21abcfee3d
56,079
def thresholdcoloring(coloring, names): """ Threshold a coloring dictionary for a given list of column names. Threshold `coloring` based on `names`, a list of strings in:: coloring.values() **Parameters** **coloring** : dictionary Hierarchical structure on the columns g...
affe639d0863468390d02f7dac2840239520419c
56,080
def ComputeMultiLevelLogsig1dBM(BM_paths, number_of_segment, depth_of_tensors, T): """ Compute the log-signature of all samples """ no_of_samples = np.shape(BM_paths)[0] if depth_of_tensors == 1: MultiLevelLogSigs = np.zeros([no_of_samples , 2 * number_of_segment], dtype=float) else...
ed82f7c40be63681bfa135a5b837ee64dcd6eff1
56,081
def add_spray_angle(raw_df: pd.DataFrame, adjusted: bool = False) -> pd.DataFrame: """Adds spray angle and adjusted spray angle to StatCast DataFrames - Spray angle is the raw left-right angle of the hit - Adjusted spray angle flips the sign for left handed batters, making it a push/pull angle Args: ...
092a8134980d32c13d793137945575a49414f4ec
56,082
async def verify_token(x_key: str = Header(None)): """ Note: this isn't meant to be secure could also use a cache ... You have to pass a valid key curl -H "X-Key: your_key" http://127.0.0.1:8000/ """ if x_key is None: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED) ...
504077ae8a81c5ece58de3af63762a7fa11cbffa
56,083
def _VarintDecoder(mask): """Return an encoder for a basic varint value (does not include tag). Decoded values will be bitwise-anded with the given mask before being returned, e.g. to limit them to 32 bits. The returned decoder does not take the usual "end" parameter -- the caller is expected to do bo...
19738e8a1a09464525af18a0689a04b601e9869b
56,085
def getDownSampleImage(image, imageSize=320): """ Function take image and down sample to imageSize, while keeping the original ratio Args: image (numpy.array): image use for cropping (h,w,c) imageSize (int): target size Returns: * **resized_image** (numpy.array) - cropped image (h,w,c) """ image_ratio = ...
0ec64b549656a67bab113681a59c6905eccc2f04
56,086
def thiran_delay1(source, delta, fillvalue=0.0): """First order Thiran allpass delay.""" k = int(floor(delta - 0.5)) d = delta - k a0 = 1.0 a1 = -d / (1.0 + d) return delay(polezero(source, a0, a1, a1, a0), k, fillvalue)
8b3801b20b45c2e3b278c878fdac94a5420ea250
56,088
def kontejnery_verejne(kontejnery_json): """Funkce vybere jen kontejnery s veřejným přístupem""" verejne_kont = [] for kontejnery in kontejnery_json["features"]: pristup = kontejnery["properties"]["PRISTUP"] if pristup == "volně": souradnice = kontejnery["geometry"]["coordinates...
d9179acd6ad8c94330c1c0499815cda77e84fbf4
56,089
def generate_token(clientKey, clientSecret): """Generate the token. Please respect these credentials :)""" credentials = oauth2.SpotifyClientCredentials( client_id=clientKey, client_secret=clientSecret) token = credentials.get_access_token() return token
58badd42f550b9d523ddf7ca770e6b2b68a640c4
56,091
def rcv_winner(L, tie_breaker, printing_wanted=False): """ Return RCV (aka IRV) winner for ballot list L. Args: L (list): list of ballots (this should be a "cleaned" list) tie_breaker: list of all choices, most-favored first printing_wanted (bool): True if printing desired Retu...
e657447fa1de89dfe6baf0bede068512a2d358b1
56,094
def structuredToVTK( path: str, x: np.ndarray, y: np.ndarray, z: np.ndarray, cellData: DataType = None, pointData: DataType = None, fieldData: DataType = None, **kwargs ) -> str: """Write data to a RectilinearGrid :param path: path to file without...
ef0ff3a5575d49d8068abeddc535833bec77f11e
56,095
def _zf_pad(data, pad=0, mid=False, **kwargs): """ Zero fill by padding with zeros. Parameters ---------- dataset : ndarray Array of NMR data. pad : int Number of zeros to pad data with. mid : bool True to zero fill in middle of data. Returns ------- nda...
655871e2edc052e75180e47b6ad1ae6ec789480b
56,096
def magma_strerror(error): """ Return string corresponding to specified MAGMA error code. """ return _libmagma.magma_strerror(error)
d28f26d1418ef60f70919209af466a4f8469cac0
56,097
import scipy def rms(arr, size=5): """ A linear n-D smoothing filter. Can be used as a moving average on 1D data. Args: arr (ndarray): an n-dimensional array, such as a seismic horizon. size (int): the kernel size, e.g. 5 for 5x5. Should be odd, rounded up if not. Returns...
36f804512bec220a8544bf7c67b3e279fc0faaf5
56,099
def get_json_objects_async(urls): """retrieve a dict with urls and corresponding jsons. The data is fetched asynchronously to speed up the process.""" pool = ThreadPool(processes=4) url_json_dicts = pool.map(request_url_json_dict_from_url, urls) pool.close() pool.join() return url_json_dict...
942a8f25235359e240812a20bd16e5265d84c351
56,100
def refine_peak(tsmap, pix): """Solve for the position and uncertainty of source assuming that you are near the maximum and the errors are parabolic Parameters ---------- tsmap : `~numpy.ndarray` Array with the TS data. Returns ------- The position and uncertainty of the source,...
102953098f6245bc31c65a1d7826fb76c182ffb2
56,101
import types from typing import Dict from typing import Any from typing import List def merge_two_reconstructions( r1: types.Reconstruction, r2: types.Reconstruction, config: Dict[str, Any], threshold: float = 1, ) -> List[types.Reconstruction]: """Merge two reconstructions with common tracks IDs....
82914428ec6d45a7627ce59c788df952d5e0ff29
56,102
def idtostr(obj, membre='id', defaut='0'): """renvoie id d'un objet avec la gestion des null @param obj: l'objet a interroger @param defaut: la reponse si neant ou inexistant @param membre: l'attribut a demander si pas neant""" try: if getattr(obj, membre) is not None: retour = s...
35cc093b054b1eaa1a0417530dc940fb79232c07
56,103
def draw_values(params, point=None, size=None): """ Draw (fix) parameter values. Handles a number of cases: 1) The parameter is a scalar 2) The parameter is an RV a) parameter can be fixed to the value in the point b) parameter can be fixed by sampling from the RV ...
8d436911003685301448edb9353ec0e533f4fccc
56,104
def duplicate_detection( spark, idf, list_of_cols="all", drop_cols=[], treatment=False, print_impact=False ): """ As the name implies, this function detects duplication in the input dataset. This means, for a pair of duplicate rows, the values in each column coincide. Duplication check is confined to th...
862bfe5b3fbb14576e323b48b7209633082ef632
56,105
import torch def warp_with_mask(x, flo, masked_flow): """ warp an image/tensor (im2) back to im1, according to the optical flow x: [B, C, H, W] (im2) flo: [B, 2, H, W] flow mask: [B, C, H, W] """ B, C, H, W = x.size() # mesh grid xx = torch.arange(0, W).view(1, -1).repeat(H, 1) ...
3bdcbe496a816f1d3370737e61fda6d795da8fb9
56,106
import base64 def send_command( service_account_json, project_id, cloud_region, registry_id, device_id, command): """Send a command to a device.""" # [START iot_send_command] print('Sending command to device') client = get_client(service_account_json) device_path = 'projects/{}/loc...
507cacc4d41bd9282e4948e1fd328f3b8f72a442
56,107
def infer_joint_centers( markers: TimeSeries, /, segment: str, *, sex: str = 'M', ) -> TimeSeries: """ Infer joint centers based on anthropometric data. This function is aimed to be used on static acquisitions in quasi-neutral position. For the pelvis: C...
a8386ae9396d1b921ee1a6c1cdcc0a939be1de4f
56,109
import requests def get_observer_group_member(group_id=None, output='List'): """Gets data on observers in a group. If no group is requested, all is retrieved. :param group_id: [int] :param output: [string] 'List' or 'Dict' :return: [list] of class ObserverGroupMember or dictionary ...
887d770b1d51d3fb39bad3e5fcf3bdb4305e67cb
56,110
def fixture_categories() -> DatasetCategories: """ categories """ return DatasetCategories(init_categories=["ROW", "COLUMN"])
2ccc199e54406d57efbbbbc8052851287fc7851b
56,111
def create_disk(disk_name, source_image, size_gb, project, zone, wait_for_completion=False): """Create a disk.""" api = _get_api() operation = api.disks().insert( body={ 'name': disk_name, 'sizeGb': size_gb, ...
16c55de94346bf36c75f11a36bc192dac54ed659
56,112
from typing import List import ast def is_getting_element_by_unpacking(targets: List[ast.expr]) -> bool: """Checks if unpacking targets used to get first or last element.""" if len(targets) != 2: return False first_item = ( isinstance(targets[1], ast.Starred) and _is_unused_variabl...
84560e48d042a97863f2ac8ed6545b587d79bdd6
56,113
def file_is_text(file): """ Vérifie qu'un fichier est au format texte et non binaire :param file: Chemin vers le fichier :return: Vrai si le fichier est au format texte, faux s'il est au format binaire """ textchars = bytearray([7, 8, 9, 10, 12, 13, 27]) + bytearray(range(0x20, 0x100)) is_pl...
6a49486aa05e8627e7a0f6504e5c9b86c050df81
56,114
def ssd_warp_gt(batch_bboxes, batch_labels, bg_class): """Translates Ground truth boxes and labels into the internal format. :param batch_bboxes: Bbox coordinates :param batch_labels: Bbox labels :param bg_class: ID of background label :return: List of boxes """ assert batch_bboxes.shape[0...
8b1f15eee23d44065548bc9ed807d5114a000955
56,115
def on_color(clip, size=None, color=(0, 0, 0), pos=None, col_opacity=None): """ Returns a clip made of the current clip overlaid on a color clip of a possibly bigger size. Can serve to flatten transparent clips (ideal for previewing clips with masks). :param size: size of the final clip. By de...
1c50288c82d8148152109706c729f595c64cfea8
56,118
import typing def pretty_repr( src: typing.Any, indent: int = 0, no_indent_start: bool = False, max_indent: int = 20, indent_step: int = 4, ) -> str: """Make human readable repr of object. :param src: object to process :type src: typing.Any :param indent: start indentation, all ne...
5f65beab2f8c04197a62f5aecf379b59475407fd
56,119
def geoEro(*args): """ Function renamed. Use: r = geoErode(...) """ return geoErode(*args)
5a8253eee8dca470751fda8bfec52c8a01eba266
56,120
def EdgeDetect(clip, mode="kirsch", lthr=0, hthr=255, multi=1): """ Generates edge mask based on convolution kernel. The result of the convolution is then thresholded with lthr and hthr. Args: mode (string) - Chooses a predefined kernel used for the mask computing. Vaild...
037f6d89dc712b2e31c97cd4a73e98044409db9c
56,121
def modifies(repo, subset, x): """``modifies(pattern)`` Changesets modifying files matched by pattern. """ # i18n: "modifies" is a keyword pat = getstring(x, _("modifies requires a pattern")) return checkstatus(repo, subset, pat, 0)
a28af7d2872527b5b2116151398ee1c7a0ce10d4
56,123
def tnr(label, prediction): """calculate true negative rate between label and prediction TNR = TN / (TN + FP) Parameters ---------- label : tensor tensor of shape [batch_size, height, width, depth] containing the ground truth label prediction : tensor tensor of shape [batch_size...
a1947f3e271d32080acd894efd6f3611397d08b8
56,125
def transform_editor_features(metadata): """Transform editor-related features into metadata; editor uses are expressed as proportions of n_total_chgset, a proportion of local change sets is computed as a new feature and an ecdf transformation is applied on n_chgset and n_total_chgset Parameters...
0dbbd52f1909cd3ac750715867ae8886e7927c97
56,127
def SceneShadowManagerEnd(builder): """This method is deprecated. Please switch to End.""" return End(builder)
8471344512601902ffe0a61627603c1a5fbbad30
56,128
def invert_windows(windows, start=None, stop=None): """ Select all of the time except that covered by the given windows. You can use this to define a baseline time period that is far enough from key events: # select all time in the series excluding any 500 ms window after an induced spike baseline_...
ab0f534f933a805414155ddae652833ac5d63ab0
56,129
def formatIntervalSeconds2(oSeconds): """ Flexible input version of formatIntervalSeconds for use in WUI forms where data is usually already string form. """ if isinstance(oSeconds, (int, long)): return formatIntervalSeconds(oSeconds); if not isString(oSeconds): try: ...
05c33963b9dc333193bd313544a5096074c9aa44
56,131
def staging_gateway(request, server_authority, superdomain, manager, gateway_options, gateway_environment): """Deploy tls apicast gateway. We need APIcast listening on https port""" kwargs = dict( name=blame(request, "tls-gw"), manager=manager, server_authority=server_authority, ...
553e20a44cddab33c5d40994b2d50b2a4c831a8f
56,132
from bs4 import BeautifulSoup import re def update_bnc_words(xml_path): """ Function to extract words from one XML file. input: xml_path (str): path to BNC XML file returns set of all words in file at xml_path """ with open(xml_path) as f: content = f.read() ...
06ca257ea85edf63f242061f162c1c8dce99967f
56,133
from typing import List def admission_control(data: List[DataPoint]) -> List[DataPoint]: """ :rtype: list :param list data: :return: """ final_data = [] for dp in data: if isinstance(dp.sample, str) and len(dp.sample.split(',')) == 20: final_data.append(dp) if ...
73bb0e8794df1e7fea5c99cc3471228d2ac15b79
56,134
def generate_ei(N, pE=0.8): """ E/I signature. Parameters ---------- N : int Number of recurrent units. pE : float, optional Fraction of units that are excitatory. Default is the usual value for cortex. """ assert 0 <= pE <= 1 Nexc = int(pE*N) Ninh = N - Nex...
1231968940fb0d913a55b84d42fc5d4eb2575427
56,135
from typing import Dict def create_login_internal_config(app: Application, storage: AsyncpgStorage) -> Dict: """ Creates compatible config to update login.cfg.cfg object """ login_cfg = app[APP_CONFIG_KEY].get(CONFIG_SECTION_NAME, {}) # optional! smtp_cfg = app[APP_CONFIG_KEY][SMTP_SECTION] ...
e2f3e171c03846df856c37e645d469a94d302242
56,136
def hotfilm_velocity(veff1, veff2, k1=0.3, k2=0.3): """For a pair effective velocities from wire 1 and 2, calculates u and w components.""" un = np.sqrt((veff1**2 - k1**2 * veff2**2) / (1 - k1**2 * k2**2)) ut = np.sqrt((veff2**2 - k2**2 * veff1**2) / (1 - k1**2 * k2**2)) u = (ut + un) / np.sqrt(2.) ...
2251c524fa7ddf541e53d36e98a10f126820b7ed
56,137
def parse_oldrefs(matchobj): """Parse existing references. """ global oldreferences fullref = matchobj.group(0) no = matchobj.group(1) ref = matchobj.group(2) if ref is not None and ref is not '': oldreferences[ref] = no return ''
08cc1283e37e28add21aa52a9fb93d325689a6f7
56,138
import torch def pad_collate(data): """Creates mini-batch tensors from the list of tuples (src_seq, trg_seq).""" def pad_sequences(sequences): sequences = [torch.LongTensor(s) for s in sequences] lengths = torch.LongTensor([len(seq) for seq in sequences]) padded_seqs = torch.zeros(len(...
bb84d62e90418de7ac57974d69ac985a49cf5d35
56,140
def number_normalization(value, fromvalue, tovalue): """数値を範囲内の値に正規化する。 value: 正規化対象の数値。 fromvalue: 範囲の最小値。 tovalue: 範囲の最大値+1。 """ if 0 == tovalue: return value if tovalue <= value or value < fromvalue: value -= (value // tovalue) * tovalue if value < fromvalue: v...
912c515991246204ebc4d5eae8ffedb1c6d5823b
56,141
def node_count(): """Count the number of nodes with each label. Use this before migration and after migration to verify no unwanted nodes have been created. :returns: Mapping of label to counts. :rtype: dict """ counts = {} labels = [] driver = get_neo4j() for model_name, klass...
fd309bdd858c319f2e7da9e32e4368b45c7a3af2
56,142
def preprocessing(list_sentences, targets, max_len=60, max_batch=64): """ """ dict_sentences = {length: [] for length in range(2, max_len)} dict_targets = {length: [] for length in range(2, max_len)} bag_of_sentences = [ tokenization(sentence) for sentence in list_sentences...
4034ff54efe912027301d3d4a81589fcdb74bbdd
56,143
import math def controlled_integer_increment_phase(control_list, increment, target): """ The controlled version of integer_increment_phase. """ d = len(target) program = Program() for i in range(0, d): y = math.pi * increment / (2 ** (d - 1 - i)) gate = PHASE(y, target[i]) ...
16f711f4f561a33c15f75256b92578cfbb8b852a
56,144
from typing import Union import torch def lasso_cd_weight_update( x: FloatTensor, r: FloatTensor, j: int, w_j: Union[float, FloatTensor], col_l2: float, lmb: float, ) -> float: """ Returns new weight for lasso coordinate descent weight update. See the README section for the deriva...
911b34f661a8f117821551b5f8560512d26add88
56,145
def sets_diff(self: list, other: list, name: str, loc: str) -> list: """ Function to compare the sets of two lists. Returns a list of diff strings containing name and location. :param self: list :param other: list :param name: str :param loc: str :return: list[str] """ diffs = []...
04a295051f409f7748fca00ade9e509a74bcd188
56,147
def verify_mods(rel, subj, obj, mods, spatial_parser): """ Function returns all models in which the given relation, subject and object holds. The function can therefore be used to remove models corresponding to indeterminacies that turn out to be false. """ if PRINT_VERIFICATION: print("...
264482b5daf06a6a57901577f7a353dc3b2b6de2
56,148
import requests def get_profile(login): """Get the GitHub profile from login""" print("get profile for %s" % (login,)) try: profile = get("https://api.github.com/users/%s" % login).json() except requests.exceptions.HTTPError: return dict(name=login, avatar_url=LOGO_URL, html_url="") ...
661f737ba6146fdf38f7f70eb3c32341a6cb02f0
56,149
def sep_results(blends=None,no_blends=None,path=None): """blends= blended images no_blends= non blended images""" runner = Run_Sep() flags_b, sep_res_b = runner.process(blends) #We retrieve sep predictions and positions of blends flags_nb, sep_res_nb = runner.process(no_blends) #Compute accu...
2310ee308549421c0737f0f83dca5547b23e3a2d
56,150
from typing import Any from typing import Union from typing import List import re def _format_url( url: Any, col: str, remove_auth: Union[bool, List[str]], split: bool, errors: str ) -> Any: """ This function formats the input value "url" The last two components of the returned tuple hold the followi...
2b68f493b9e604cbb402590ccb55795a98d5e4db
56,151
def get_dt_df(df): """Return a new DataFrame containing only the columns from `df` that contain date-times. Columns containing mixed values where more than `fuzz_percent` of the values are parsable as date-times, are included. In mixed value columns, The NaT (not a time) rows are filled in with interpol...
59abbc53595cb99f28236fe0661473be2c613687
56,152
def crop_address(place): """ Crops address and returns new variant >>> crop_address("Jo's Cafe, San Marcos, Texas, USA") ' San Marcos, Texas, USA' >>> crop_address("San Marcos, Texas, USA") ' Texas, USA' >>> crop_address(" Texas, USA") ' USA' """ place = place.split(",") pla...
05cd88900d04ac7bca8dd45beb416ec7aa72c2f1
56,153