content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def validate_email_address( value=_undefined, allow_unnormalized=False, allow_smtputf8=True, required=True, ): """ Checks that a string represents a valid email address. By default, only email addresses in fully normalized unicode form are accepted. Validation logic is based on the...
85b590186f2e147c6c19e91bace33f0301115d0e
3,641,100
import numpy import math def rotation_matrix_from_quaternion(quaternion): """Return homogeneous rotation matrix from quaternion.""" q = numpy.array(quaternion, dtype=numpy.float64)[0:4] nq = numpy.dot(q, q) if nq == 0.0: return numpy.identity(4, dtype=numpy.float64) q *= math.sqrt(2.0 / nq...
51b169ffa702e3798f7a6138271b415b369566ba
3,641,101
import os def get_woosh_dir(url, whoosh_base_dir): """ Based on the bigbed url and base whoosh directory from settings generate the path for whoosh directory for index of this bed file """ path = urlparse(url).path filename = path.split('/')[-1] whoosh_dir = os.path.join(whoosh_base_dir, f...
d1429daaf419937cd751514520117acd51cfa91c
3,641,102
def get_metadata(doi): """Extract additional metadata of paper based on doi.""" headers = {"accept": "application/x-bibtex"} title, year, journal = '', '', '' sessions = requests.Session() retry = Retry(connect=3, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) sessions.mount('h...
8b7fee95ca247b0ffebfa704628be8a4659dd008
3,641,103
def format_channel(channel): """ Returns string representation of <channel>. """ if channel is None or channel == '': return None elif type(channel) == int: return 'ch{:d}'.format(channel) elif type(channel) != str: raise ValueError('Channel must be specified in string format....
4eeb42899762d334599df831b7520a956998155a
3,641,104
def download_emoji_texture(load=True): # pragma: no cover """Download emoji texture. Parameters ---------- load : bool, optional Load the dataset after downloading it when ``True``. Set this to ``False`` and only the filename will be returned. Returns ------- pyvista.Text...
3ff7805e6ab4f18d0064938f8863cbbe395a7c78
3,641,105
import random def shuffle_sequence(sequence: str) -> str: """Shuffle the given sequence. Randomly shuffle a sequence, maintaining the same composition. Args: sequence: input sequence to shuffle Returns: tmp_seq: shuffled sequence """ tmp_seq: str = "" while len(sequence...
9e833aed9e5a17aeb419a77176713e76566d2d06
3,641,106
def bayesian_twosample(countsX, countsY, prior=None): """ Calculates a Bayesian-like two-sample test between `countsX` and `countsY`. The idea is taken from [1]_. We assume the counts are generated IID. Then we use Dirichlet prior to infer the underlying discrete distribution. In the null hypothes...
fc64ba0d6e64ffcd7d57d51b3ea0f4967d4e5096
3,641,107
import torch def load_image(image_path): """ loads an image from the specified image path :param image_path: :return: the loaded image """ image = Image.open(image_path) image = loader(image) image = image.unsqueeze(0) image = image.to(device, torch.float) return image
064f9a4a71fdf9347a455269bf673bd2952dd9b2
3,641,108
import json def feed_reader(url): """Returns json from feed url""" content = retrieve_feed(url) d = feed_parser(content) json_string = json.dumps(d, ensure_ascii=False) return json_string
47726236afe429ab29720e917238960b17891938
3,641,109
def create_app(env_name): """ Create app """ # app initiliazation app = Flask(__name__) app.config.from_object(app_config[env_name]) cors = CORS(app) # initializing bcrypt and db bcrypt.init_app(app) db.init_app(app) app.register_blueprint(book_blueprint, url_prefix='/api/v1/books') @app...
b694e8867b0bd3efefff0f7cae753b0ede91a36c
3,641,110
def get_shed_tool_conf_dict( app, shed_tool_conf ): """Return the in-memory version of the shed_tool_conf file, which is stored in the config_elems entry in the shed_tool_conf_dict associated with the file.""" for index, shed_tool_conf_dict in enumerate( app.toolbox.shed_tool_confs ): if shed_tool_conf ...
21eae3a037498758425b29f10110f8e4e8ad24ff
3,641,111
import time def get_column_interpolation_dust_raw(key, h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a, target_a, dust_factors, kdtree_index=None, luminosit...
d7f0c221cac7c2d72352db61f04c7b7efdd994e1
3,641,112
import os def _get_next_foldername_index(name_to_check,dir_path): """Finds folders with name_to_check in them in dir_path and extracts which one has the hgihest index. Parameters ---------- name_to_check : str The name of the network folder that we want to look repetitions for. dir_pa...
c8239f8ae8a34c2ae8432e7a9482f169ce0962ce
3,641,113
def oio_make_subrequest(env, method=None, path=None, body=None, headers=None, agent='Swift', swift_source=None, make_env=oio_make_env): """ Same as swift's make_subrequest, but let some more headers pass through. """ return orig_make_subrequest(env, method...
f454b027243f2e72b9e59c50dfc3819a22b887d6
3,641,114
from typing import Callable def offline_data_fetcher(cfg: EasyDict, dataset: Dataset) -> Callable: """ Overview: The outer function transforms a Pytorch `Dataset` to `DataLoader`. \ The return function is a generator which each time fetches a batch of data from the previous `DataLoader`.\ ...
88d7a8d58bb9a77e4656c1b1294e793e6d32f829
3,641,115
from typing import Optional def get_channel(id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetChannelResult: """ Resource schema for AWS::MediaPackage::Channel :param str id: The ID of the Channel. """ __args__ = dict() __args__['id'] = id ...
28ca816326203ca37cf514dade19ce9b6205144d
3,641,116
import torch def _get_activation_fn(activation): """Return an activation function given a string""" if activation == "relu": return torch.nn.functional.relu if activation == "gelu": return torch.nn.functional.gelu if activation == "glu": return torch.nn.functional.glu raise...
ecc690e9b9ec6148b6ea8df4bd08ff2d0c1c322e
3,641,117
def make_05dd(): """移動ロック終了(イベント終了)""" return ""
bb85e01a4a4515ac88688690cacd67e7c9351034
3,641,118
import json def lambda_handler(request, context): """Main Lambda handler. Since you can expect both v2 and v3 directives for a period of time during the migration and transition of your existing users, this main Lambda handler must be modified to support both v2 and v3 requests. """ try: ...
8eddd8ac2a47ecbc9c15f2644da6a2c7c6575371
3,641,119
from re import T def batch_flatten(x): """Turn a n-D tensor into a 2D tensor where the first dimension is conserved. """ y = T.reshape(x, (x.shape[0], T.prod(x.shape[1:]))) if hasattr(x, '_keras_shape'): if None in x._keras_shape[1:]: y._keras_shape = (x._keras_shape[0], None) ...
6543f3056d9e08b382cbd9e0ac1df6df84c59716
3,641,120
import typing def msg_constant_to_behaviour_type(value: int) -> typing.Any: """ Convert one of the behaviour type constants in a :class:`py_trees_ros_interfaces.msg.Behaviour` message to a type. Args: value: see the message definition for details Returns: a behaviour class ty...
bdb2342ad9abbbc6db51beebcb82313799bc110e
3,641,121
def calc_skewness(sig): """Compute skewness along the specified axes. Parameters ---------- input: ndarray input from which skewness is computed. Returns ------- s: int skewness result. """ return skew(sig)
cad86d0a358a9bfe1891411522a6281e1eb291ed
3,641,122
import os from aiida.common import UniquenessError, NotExistent from aiida.orm.querybuilder import QueryBuilder from .otfg import OTFGGroup def upload_usp_family(folder, group_label, group_description, stop_if_existing=True): """ Upload a set o...
3a51d7bdedec47fc0334ee9295d2b95d5f518eb1
3,641,123
import pandas as pd import pkgutil def check_is_pandas_dataframe(log): """ Checks if a log object is a dataframe Parameters ------------- log Log object Returns ------------- boolean Is dataframe? """ if pkgutil.find_loader("pandas"): return type(log) ...
93fa02445302cf695fd86beb3e4836d58660e376
3,641,124
def mk_creoson_post_sessionId(monkeypatch): """Mock _creoson_post return dict.""" def fake_func(client, command, function, data=None, key_data=None): return "123456" monkeypatch.setattr( creopyson.connection.Client, '_creoson_post', fake_func)
c8f5fcec40d55e14a7c955a90f32eccf597179f3
3,641,125
def isUsernameFree(name): """Checks to see if the username name is free for use.""" global username_array global username for conn in username_array: if name == username_array[conn] or name == username: return False return True
6a30766e35228e1ebea47c7f6d4f7f4f2832572d
3,641,126
def get_quadrangle_dimensions(vertices): """ :param vertices: A 3D numpy array which contains a coordinates of a quadrangle, it should look like this: D---C | | A---B [ [[Dx, Dy]], [[Cx, Cy]], [[Bx, By]], [[Ax, Ay]] ]. :return: width, height (which are integers) """ temp = np.zeros((4, 2), dtype=int)...
25e74cf63237d616c1fd0b1b3428dd0763a27fba
3,641,127
def optimal_r(points, range_min, range_max): """ Computes the optimal Vietoris-Rips parameter r for the given list of points. Parameter needs to be as small as possible and VR complex needs to have 1 component :param points: list of tuples :return: the optimal r parameter and list of (r, n_componen...
950c8cc40de9ff9fbb0bd142461fc2710b54ead9
3,641,128
from pathlib import Path def get_root_path(): """ this is to get the root path of the code :return: path """ path = str(Path(__file__).parent.parent) return path
bc01b4fb15569098286fc24379a258300ff2dfa0
3,641,129
def _handle_requirements(hass: core.HomeAssistant, component, name: str) -> bool: """Install the requirements for a component.""" if hass.config.skip_pip or not hasattr(component, 'REQUIREMENTS'): return True for req in component.REQUIREMENTS: if not pkg_util.instal...
6608228271fe37d607e7980d6c4cfe876b45b853
3,641,130
def check_image(filename): """ Check if filename is an image """ try: im = Image.open(filename) im.verify() # is it an image? return True except OSError: return False
b2854195c83cc6ab20e967e25f3892a46d3c146f
3,641,131
import torch def encode_save(sig=np.random.random([1, nfeat, nsensors]), name='simpleModel_ini', dir_path="../src/vne/models"): """ This function will create a model, test it, then save a persistent version (a file) Parameters __________ sig: a numpy array with shape (nsamples, nfeatures,...
96fbeb853c66afd7f4a6c3a1a087faee64ec76d0
3,641,132
from typing import Set from typing import Tuple from typing import Counter def _imports_to_canonical_import( split_imports: Set[Tuple[str, ...]], parent_prefix=(), ) -> Tuple[str, ...]: """Extract the canonical import name from a list of imports We have two rules. 1. If you have at least 4 impor...
e9cfd11b5837576ccc6f380463fe4b8ce9f4a63d
3,641,133
import os def _bin_file(script): """Return the absolute path to scipt in the bin directory""" return os.path.abspath(os.path.join(__file__, "../../../bin", script))
3b7dbe4061ff88bd42da91f854f561715df101df
3,641,134
def score_hmm_logprob(bst, hmm, normalize=False): """Score events in a BinnedSpikeTrainArray by computing the log probability under the model. Parameters ---------- bst : BinnedSpikeTrainArray hmm : PoissonHMM normalize : bool, optional. Default is False. If True, log probabilities ...
d20e5e75c875602c7ac2e3b0dadc5adcae45406d
3,641,135
def rotate_2d_list(squares_list): """ http://stackoverflow.com/questions/8421337/rotating-a-two-dimensional-array-in-python """ return [x for x in zip(*squares_list[::-1])]
a6345ce6954643b8968ffb4c978395baf777fca4
3,641,136
def next_ticket(ticket): """Return the next ticket for the given ticket. Args: ticket (Ticket): an arbitrary ticket Returns: the next ticket in the chain of tickets, having the next pseudorandom ticket number, the same ticket id, and a generation number that is one larger. ...
7f5cfbd9992322e394a9e3f4316d654ef9ad6749
3,641,137
def icecreamParlor4(m, arr): """I forgot about Python's nested for loops - on the SAME array - and how that's actually -possible-, and it makes things so much simplier. It turns out, that this works, but only for small inputs.""" # Augment the array of data, so that it not only includes the item, but ...
6af2da037aa3e40c650ac48ebeb931399f1a6eaa
3,641,138
import datasets def get_data(filepath, transform=None, rgb=False): """ Read in data from the given folder. Parameters ---------- filepath: str Path for the file e.g.: F'string/containing/filepath' transform: callable A function which tranforms the data to the required format ...
99eb506c9033e259ad5769d8eff10b7fd985a1d6
3,641,139
from ozmo import EcoVacsAPI, VacBot def setup(hass, config): """Set up the Ecovacs component.""" _LOGGER.debug("Creating new Ecovacs component") hass.data[ECOVACS_DEVICES] = [] hass.data[ECOVACS_CONFIG] = [] ecovacs_api = EcoVacsAPI( ECOVACS_API_DEVICEID, config[DOMAIN].get(CONF...
11c51d640f4e12f520a2ca7f8c3c4b8279392a7b
3,641,140
def read_input_files(input_file: str) -> frozenset[IntTuple]: """ Extracts an initial pocket dimension which is a set of active cube 3D coordinates. """ with open(input_file) as input_fobj: pocket = frozenset( (x, y) for y, line in enumerate(input_fobj) fo...
c44e85e0c4f998e04b3d5e8b1e4dc30260102fce
3,641,141
def resnet101(pretrained=False, root='./pretrain_models', **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load...
ba77d75d52aa5ce92cc5a8bec09347c799ebc02a
3,641,142
def insert_left_side(left_side, board_string): """ Replace the left side of the Sudoku board 'board_string' with 'left_side'. """ # inputs should match in upper left corner assert(left_side[0] == board_string[0]) # inputs should match in lower left corner assert(left_side[8] == low_left_digi...
da607155e5c82a597f1ec62e6def3fbe31119c36
3,641,143
import tqdm import uuid def collect_story_predictions(story_file, policy_model_path, nlu_model_path, max_stories=None, shuffle_stories=True): """Test the stories from a file, running them through the stored model.""" def actions_since_last_utterance(tracker): actions = [...
d47d83c62d119f99c5c3c74b490866ffc64dc3ed
3,641,144
def get_plaintext_help_text(testcase, config): """Get the help text for this testcase for display in issue descriptions.""" # Prioritize a HELP_FORMAT message if available. formatted_help = get_formatted_reproduction_help(testcase) if formatted_help: return formatted_help # Show a default message and HEL...
6ad30b86d75c694f4027aacb7a49607af02819d2
3,641,145
import select def sniff(store=False, prn=None, lfilter=None, count=0, stop_event=None, refresh=.1, *args, **kwargs): """Sniff packets sniff([count=0,] [prn=None,] [store=1,] [offline=None,] [lfilter=None,] + L2ListenSocket args) store: wether to store sniffed packets or discard them prn...
06309d056c0a68046025b806d91b7c7f0c5fdeb6
3,641,146
def generate_margined_binary_data ( num_samples, count, limits, rng ): """ Draw random samples from a linearly-separable binary model with some non-negligible margin between classes. (The exact form of the model is up to you.) # Arguments num_samples: number of samples to generate ...
5345be6c21cedfb62bf33a5c3a3b6ff75f7be892
3,641,147
def _brighten_images(images: np.ndarray, brightness: int = BRIGHTNESS) -> np.ndarray: """ Adjust the brightness of all input images :params images: The original images of shape [H, W, D]. :params brightness: The amount the brighness should be raised or lowered :return: Images with adjusted brightne...
b2bc8c801e459b5f913a2bf725709cbc80df128a
3,641,148
import os import sys def findBaseDir(basename, max_depth=5, verbose=False): """ Get relative path to a BASEDIR. :param basename: Name of the basedir to path to :type basename: str :return: Relative path to base directory. :rtype: StringIO """ MAX_DEPTH = max_depth BASEDIR = os.pat...
75d11503ef02cb0671803ab7b13dcd6d77322330
3,641,149
def CreateMovie(job_name, input_parameter, view_plane, plot_type): """encoder = os.system("which ffmpeg") print encoder if(len(encoder) == 0): feedback['error'] = 'true' feedback['message'] = ('ERROR: Movie create encoder not found') print feedback return """ movie_name = job_name + '_' + input_parameter+ ...
ff518f485db1de7a2d00af2984f5829cfe4279dc
3,641,150
def describe_recurrence(recur, recurrence_dict, connective="and"): """Create a textual description of the recur set. Arguments: recur (Set): recurrence pattern as set of day indices eg Set(["1","3"]) recurrence_dict (Dict): map of strings to recurrence patterns connective (Str): word to...
0189fa88f64a284367829c3f95ecd056aec7bfa8
3,641,151
def route_image_zoom_in(): """ Zooms in. """ result = image_viewer.zoom_in() return jsonify({'zoom-in' : result})
758acf681718cc1c2be2c3bac112f4fc83243cf9
3,641,152
def evaluate_flow_file(gt_file, pred_file): """ evaluate the estimated optical flow end point error according to ground truth provided :param gt_file: ground truth file path :param pred_file: estimated optical flow file path :return: end point error, float32 """ # Read flow files and calcula...
ecbe960cd011f4282758a3f6bf4f345853f9a49d
3,641,153
def get_heavy_load_rses(threshold, session=None): """ Retrieve heavy load rses. :param threshold: Threshold as an int. :param session: Database session to use. :returns: . """ try: results = session.query(models.Source.rse_id, func.count(models.Source.rse_id).label('load'))\ ...
52b44132c1680e0ca9ba64a0afb2938abcab1228
3,641,154
import operator def facetcolumns(table, key, missing=None): """ Like :func:`petl.util.materialise.columns` but stratified by values of the given key field. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar', 'baz'], ... ['a', 1, True], ... ['b', 2, ...
bec3419a22128c2863032022c5e9e507c9791f1b
3,641,155
def divide_set(vectors, labels, column, value): """ Divide the sets into two different sets along a specific dimension and value. """ set_1 = [(vector, label) for vector, label in zip(vectors, labels) if split_function(vector, column, value)] set_2 = [(vector, label) for vector, label in zip(vectors...
dd99c4d700ad8294ce2b2a33b18feb79165487fb
3,641,156
def execute_freezerc(dict, must_fail=False, merge_stderr=False): """ :param dict: :type dict: dict[str, str] :param must_fail: :param merge_stderr: :return: """ return execute([FREEZERC] + dict_to_args(dict), must_fail=must_fail, merge_stderr=merge_stderr)
596490d1fe0ae90a807c6553674273e470165e57
3,641,157
def corField2D_vector(field): """ 2D correlation field of a vector field. Correlations are calculated with use of Fast Fourier Transform. Parameters ---------- field : (n, n, 2) shaped array like Vector field to extract correlations from. Points are supposed to be uniformly dist...
35b4c1dc646c30b9fdae7c1ad1095ae67ea1356d
3,641,158
import json def load_json_fixture(filename: str): """Load stored JSON data.""" return json.loads((TEST_EXAMPLES_PATH / filename).read_text())
1021975d2111a9391a93ff9bd757479a8c9663f6
3,641,159
from typing import List from typing import Optional def stat_list_card( box: str, title: str, items: List[StatListItem], name: Optional[str] = None, subtitle: Optional[str] = None, commands: Optional[List[Command]] = None, ) -> StatListCard: """Render a card display...
fa9036442fdad3028d40918741e91ca5077925fb
3,641,160
def test_DataGeneratorAllSpectrums_fixed_set(): """ Test whether use_fixed_set=True toggles generating the same dataset on each epoch. """ # Get test data binned_spectrums, tanimoto_scores_df = create_test_data() # Define other parameters batch_size = 4 dimension = 88 # Create norm...
95d8a13f1eaa5d7ef93936a8f9e224a56119e6af
3,641,161
import math def inverse_gamma(data, alpha=0.1, beta=0.1): """ Inverse gamma distributions :param data: Data value :param alpha: alpha value :param beta: beta value :return: Inverse gamma distributiion """ return (pow(beta, alpha) / math.gamma(alpha)) *\ pow(alpha, data-1) * ...
c13f5e4a05e111ae0082b7e69ef5b31498d2c221
3,641,162
def query(queryid): """ Dynamic Query View. Must be logged in to access this view, otherwise redirected to login page. A unique view is generated based off a query ID. A page is only returned if the query ID is associated with a logged in user. Otherwise a logged in user will be redirected to a...
22c77dc122b15d8bb6589a823a8f3904f189371a
3,641,163
def get_ssid() -> str: """Gets SSID of the network connected. Returns: str: Wi-Fi or Ethernet SSID. """ process = Popen( ['/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport', '-I'], stdout=PIPE) out, err = process.communicate()...
def6c485099219cd0894cde636ac93dc1b130a98
3,641,164
def train_predict(clf, X_train, X_test, y_train, y_test): """Train clf on <X_train, y_train>, predict <X_test, y_test>; return y_pred.""" print("Training a {}...".format(clf.__class__.__name__)) get_ipython().run_line_magic('time', 'clf.fit(X_train, y_train)') print(clf) print("Predicting test ...
eda266df2cea704d557e4de4f7600b62c533f362
3,641,165
import subprocess def FindFilesWithContents(string_a, string_b): """Returns list of paths of files that contain |string_a| or |string_b|. Uses --name-only to print the file paths. The default behavior of git grep is to OR together multiple patterns. Args: string_a: A string to search for (not a regular ...
d7b36ae2aaac98b79276f9bbd1b82dc7172520a6
3,641,166
def get_executable_choices(versions): """ Return available Maya releases. """ return [k for k in versions if not k.startswith(Config.DEFAULTS)]
df0c253b8ca29b42f7863a8944d21678847b7c9a
3,641,167
def list_songs(): """ Lists all the songs in your media server Can do this without a login """ # # Check if the user is logged in, if not: back to login. # if('logged_in' not in session or not session['logged_in']): # return redirect(url_for('login')) page['title'] = 'List Songs' ...
bbeb4e11404dcce582ed86cc711508645399a7cd
3,641,168
import statistics def linear_regression(xs, ys): """ Computes linear regression coefficients https://en.wikipedia.org/wiki/Simple_linear_regression Returns a and b coefficients of the function f(y) = a * x + b """ x_mean = statistics.mean(xs) y_mean = statistics.mean(ys) num, den = 0...
6b6ecbd31262e5fe61f9cf7793d741a874327598
3,641,169
def calcR1(n_hat): """ Calculate the rotation matrix that would rotate the position vector x_ae to the x-y plane. Parameters ---------- n_hat : `~numpy.ndarray` (3) Unit vector normal to plane of orbit. Returns ------- R1 : `~numpy.matrix` (3, 3) Rotation matrix. ...
c3202c477eefe43648e693316079f9e2c6ac0aa0
3,641,170
def get_arb_info(info, n=1000): """ Example: info := {'start':1556668800, 'period':300, 'trading_pair':'eth_btc', 'exchange_id':'binance'} """ assert {'exchange_id', 'trading_pair', 'period', 'start'}.issubset(info.keys()) info['n'] = n q = """with sub as ( select * from candlestick...
20177d71b0a816031aded0151e91711f729fe0bf
3,641,171
from typing import List def parse_nested_root(stream: TokenStream) -> AstRoot: """Parse nested root.""" with stream.syntax(colon=r":"): colon = stream.expect("colon") if not consume_line_continuation(stream): exc = InvalidSyntax("Expected non-empty block.") raise set_location(exc,...
ea559c4c2592b4ecabfb10df39059391799f4462
3,641,172
def wg_config_write(): """ Write configuration file. """ global wg_config_file return weechat.config_write(wg_config_file)
add032c3447d2c68005bbc1cc33006ba452afaa3
3,641,173
def is_palindrome_permutation(phrase): """checks if a string is a permutation of a palindrome""" table = [0 for _ in range(ord("z") - ord("a") + 1)] countodd = 0 for c in phrase: x = char_number(c) if x != -1: table[x] += 1 if table[x] % 2: countod...
dac9d0fc67f628cb22213d5fcad947baa3d2d8f1
3,641,174
import json def get_stored_username(): """Get Stored Username""" filename = 'numbers.json' try: with open(filename) as file_object: username = json.load(file_object) except FileNotFoundError: return None else: return username
3471369cfc147dd9751cedb7cde92ceb5d69e908
3,641,175
import posixpath def post_process_symbolizer_image_file(file_href, dirs): """ Given an image file href and a set of directories, modify the image file name so it's correct with respect to the output and cache directories. """ # support latest mapnik features of auto-detection # of image sizes ...
42026823be510b5ffbb7404bd24809a1232e8206
3,641,176
import torch def collate_fn_feat_padded(batch): """ Sort a data list by frame length (descending order) batch : list of tuple (feature, label). len(batch) = batch_size - feature : torch tensor of shape [1, 40, 80] ; variable size of frames - labels : torch tensor of shape (1) ex) sampl...
b901b6c3eacfd4d0bac93e1569d59ad944365fd2
3,641,177
import unicodedata import re def slugify(value, allow_unicode=False): """ Taken from https://github.com/django/django/blob/master/django/utils/text.py Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated dashes to single dashes. Remove characters that aren't alphanumerics, unde...
39f7ed291e6a2cec5111ba979c35a6aaa8e521c0
3,641,178
def average_gradient_norm(model, data): """ Computes the average gradient norm for a keras model """ # just checking if the model was already compiled if not hasattr(model, "train_function"): raise RuntimeError("You must compile your model before using it.") weights = model.trainable_weights #...
84f5feb894f72856ef43eea8befc048f216020bd
3,641,179
import logging def string_regex_matcher(input_str: str, regex: str, replacement_str=""): """Python version of StringRegexMatcher in mlgtools. Replaces all substring matched with regular expression (regex) with replacement string (replacement_str). Args: input_str (str): input string to match ...
c813447a1453347a1b263f603970d8ff4f709696
3,641,180
def cont_scatterplot(data: pd.DataFrame, x: str, y: str, z: str or None, label: str, cmap: str, size: int or str or None, fig: plt.Figure, cbar_kwargs: ...
e6c85d1fafa93c9000c807c7ec82ac7851082aec
3,641,181
def performance(problem, W, H, C, R_full): """Compute the performance of the IMC estimates.""" assert isinstance(problem, IMCProblem), \ """`problem` must be an IMC problem.""" assert W.ndim == H.ndim, """Mismatching dimensionality.""" if W.ndim < 3: W, H = np.atleast_3d(W, H) n_i...
79635826cc72633a0024df29980ecc678f20e32d
3,641,182
import pytz from datetime import datetime def courseschedules_to_private_ical_feed(user): """ Generate an ICAL feed for all course schedules associated with the given user. The IDs given for each event are sequential, unique only amongst the results of this particular query, and not guaranteed to be ...
1d1ae7f650416eb240d0ce5240523d8c66067389
3,641,183
def AuxStream_Cast(*args): """ Cast(BaseObject o) -> AuxStream AuxStream_Cast(Seiscomp::Core::BaseObjectPtr o) -> AuxStream """ return _DataModel.AuxStream_Cast(*args)
a38248e5476273aa6b18da5017a7ca0a033fd0a8
3,641,184
def BPNet(tasks, bpnet_params): """ BPNet architecture definition Args: tasks (dict): dictionary of tasks info specifying 'signal', 'loci', and 'bias' for each task bpnet_params (dict): parameters to the BPNet architecture The keys includ...
cfffac8da543241160b6fc1963b8b19df7fa2b02
3,641,185
def getCubePixels(cubeImages): """ Returns a list containing the raw pixels from the `bpy.types.Image` images in the list `cubeImages`. Factoring this functionality out into its own function is useful for performance profiling. """ return [face.pixels[:] for face in cubeImages]
cdb2ba02ce9466e1b92a683dbea409e66b60c8da
3,641,186
import select async def get_round_details(round_id): """ Get details for a given round (include snapshot) """ query = ( select(detail_columns) .select_from(select_from_default) .where(rounds_table.c.id == round_id) ) # noqa: E127 result = await conn.fetch_one(query=que...
b7d64f52a8dff1a68a327651653f1f217f688146
3,641,187
import random def dens_hist_plot(**kwargs): """ plot prediction probability density histogram Arguments: df: classification prediction probability in pandas datafrane """ data = {'top1prob' : random.sample(range(1, 100), 5), 'top2prob' : random.sample(range(...
9b9e65f4aef04c2676b48737f4b9bf525172b6ea
3,641,188
import time def run_query(run_id, athena_client, query, athena_database_name, wait_to_finish): """ Run the given Athena query Arguments: run_id {string} -- run_id for the current Step Function execution athena_client {boto3.client} -- Boto3 Athena client query {string} -- Athena query...
0ee4618de6df9e32bbe3255f7a423dd838a564f1
3,641,189
def next_version(v: str) -> str: """ If ``v`` is a prerelease version, returns the base version. Otherwise, returns the next minor version after the base version. """ vobj = Version(v) if vobj.is_prerelease: return str(vobj.base_version) vs = list(vobj.release) vs[1] += 1 vs...
aea76df6874e368494ca630d594bee978ffc7e08
3,641,190
def sample_translate_text(text, target_language, project_id): """ Translating Text Args: text The content to translate in string format target_language Required. The BCP-47 language code to use for translation. """ client = translate.TranslationServiceClient() # TODO(developer): U...
968e4f739f801aea0692db721cafb7cbd8d1e36e
3,641,191
def temp_obs(): """Return a list of tobs from the 2016-08-24 to 2017-08-23""" # Query temperature data with date temp_query = session.query(Measurement.date, Measurement.tobs).filter(Measurement.date > year_start_date).all() # Create a dictionary from the row data and append to a list of all temp...
6a74ad37cb95d1103943f15dfcac82e39c38620d
3,641,192
def pcmh_5_5c__3(): """ER/IP discharge log""" er_ip_log_url = URL('init', 'word', 'er_ip_log.doc', vars=dict(**request.get_vars), hmac_key=MY_KEY, salt=session.MY_SALT, hash_vars=["app_id", "type"]) # er_ip_log tracking chart er_ip_log = MultiQNA( ...
968bcc181cf3ec4513cfeb73004cdd3336f62003
3,641,193
def get_largest_component_size(component_size_distribution): """Finds the largest component in the given component size distribution. Parameters ---------- component_size_distribution : dict The component size distribution. See the function get_component_size_dist Returns ------- Th...
2f922d465a61b4c65eacfdb3d5284e97d23f9659
3,641,194
import os def bin_regions_parallel( bed_files, out_dir, chromsizes, bin_size=200, stride=50, final_length=1000, parallel=12): """bin in parallel """ split_queue = setup_multiprocessing_queue() for bed_file in bed_files: prefix = os.p...
634a0977918b25da3898f24bcf5d4027a11576a3
3,641,195
import json def is_jsonable(data): """ Check is the data can be serialized Source: https://stackoverflow.com/a/53112659/8957978 """ try: json.dumps(data) return True except (TypeError, OverflowError): return False
acfc697025a8597fdd8043fe3245a339b27051c4
3,641,196
def check_ref_type(ref, allowed_types, ws_url): """ Validates the object type of ref against the list of allowed types. If it passes, this returns True, otherwise False. Really, all this does is verify that at least one of the strings in allowed_types is a substring of the ref object type name. ...
263cf56124fb466544dfba8879a55d1f09160d35
3,641,197
from typing import Dict from typing import List def check_infractions( infractions: Dict[str, List[str]], ) -> int: """ Check infractions. :param infractions: the infractions dict {commit sha, infraction explanation} :return: 0 if no infractions, non-zero otherwise """ if len(infractions)...
954f5f80dbfdd2a834f56662f4d04c1f788bb9ef
3,641,198
def get_particle_tracks(_particle_tracker, particle_detects, time, is_last, debug_axis=None, metrics=None): """This module constructs the particle tracks. WARNING: No examples for Finishing. No error warning. Parameters ---------- _particle_tracker: dict A particle tracker dictionary p...
57525a488b12cd3b5024879f66cd8e9904e2d71f
3,641,199