content
stringlengths
22
815k
id
int64
0
4.91M
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) * math.exp(-beta...
5,332,100
def plot_metric(n_points, metric_ts, metric_name, ax): """ generate an incertitude plot for the metric data passed in parameter """ incertitude_plot(n_points, metric_ts, ax) ax.set_xlabel('Number of points in the point cloud') ax.set_ylabel(f'{metric_name} difference')
5,332,101
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...
5,332,102
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()...
5,332,103
def retrieval_def(ws): """Context manager for the RetrievalDef[Init/Close] context.""" ws.covmat_block = [] ws.covmat_inv_block = [] ws.retrievalDefInit() yield ws ws.retrievalDefClose()
5,332,104
def predict_recording_level_label(audio_file, model1, model2=None): """ :param audio_file: the path of audio file to test :param model_path: the path of the recording level model to use :return: class_name : the predicted class of the input file """ basic_features_params = {} basic_features_...
5,332,105
def test_stovoltpl_find_list(dpm_mode_cpcs): # noqa: F811 # pylint: disable=redefined-outer-name """ Test list(), find(), findall(). """ if not dpm_mode_cpcs: pytest.skip("No CPCs in DPM mode provided") for cpc in dpm_mode_cpcs: assert cpc.dpm_enabled print("Testing on ...
5,332,106
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 ...
5,332,107
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 expression). str...
5,332,108
def get_executable_choices(versions): """ Return available Maya releases. """ return [k for k in versions if not k.startswith(Config.DEFAULTS)]
5,332,109
def test_1T1E1A_lastN_with_limit(reporter_dataset): """ See GitHub issue #249. """ # Query query_params = { 'type': entity_type, 'lastN': 3, 'limit': 10 } r = requests.get(query_url(), params=query_params) assert r.status_code == 200, r.text # Expect only las...
5,332,110
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' ...
5,332,111
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.0, 0.0 for x, y...
5,332,112
def scp_amazon(runmap_file,ec_key,dns,anl_fold): """ Copy relevant files and folders to EC2 instance """ run_map_dict = {} infile = open(runmap_file, 'rU') for line in infile: spline = line.strip().split("\t") run_map_dict[spline[0]] = spline[1].strip().split(".txt")[0]+"_corrected"+".txt" #Run IDs as keys an...
5,332,113
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. ...
5,332,114
def load(): """ entry point for the UI, launch an instance of the tool with this method """ global _win try: _win.close() except(NameError, RuntimeError): pass finally: _win = QThreadDemoWindow() _win.show()
5,332,115
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...
5,332,116
def compare_gaussian_classifiers(): """ Fit both Gaussian Naive Bayes and LDA classifiers on both gaussians1 and gaussians2 datasets """ for f in ["gaussian1.npy", "gaussian2.npy"]: # Load dataset X, y = load_dataset('../datasets/' + f) # print(data[0].shape,data[1].shape) ...
5,332,117
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, colon) level, comman...
5,332,118
def wg_config_write(): """ Write configuration file. """ global wg_config_file return weechat.config_write(wg_config_file)
5,332,119
def _pip(params): """ Runs pip install commands """ for pkg in params: _sudo("pip install %s" % pkg)
5,332,120
def validate_twitter_handle(value): """Raises a ValidationError if value isn't a valid twitter handle.""" if not VALID_TWITTER_RE.match(value): raise ValidationError( u'This is not a valid twitter handle.' u' Please enter just the portion after the @.' )
5,332,121
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...
5,332,122
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
5,332,123
def test_classes_shape(): """Test that n_classes_ and classes_ have proper shape.""" # Classification, single output clf = RandomForestClassifier() clf.fit(X, y) assert_equal(clf.n_classes_, 2) assert_equal(clf.classes_, [-1, 1]) # Classification, multi-output _y = np.vstack((y, np.arr...
5,332,124
def find_app(pattern: Optional[str]) -> None: """projector ide find [pattern] Find projector-compatible IDE with the name matching to the given pattern. If no pattern is specified, finds all the compatible IDEs. """ do_find_app(pattern)
5,332,125
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 and jpeg reading su...
5,332,126
def describe_trusted_advisor_check_summaries(checkIds=None): """ Returns the summaries of the results of the Trusted Advisor checks that have the specified check IDs. Check IDs can be obtained by calling DescribeTrustedAdvisorChecks . The response contains an array of TrustedAdvisorCheckSummary objects. ...
5,332,127
def _register_cli_commands(ext_registry: extension.ExtensionRegistry): """ Register xcube's standard CLI commands. """ cli_command_names = [ 'chunk', 'compute', 'benchmark', 'dump', 'edit', 'extract', 'gen', 'gen2', 'genpts', ...
5,332,128
def qft(q): """Quantum Fourier Transform on a quantum register. Args: q (list): quantum register where the QFT is applied. Returns: generator with the required quantum gates applied on the quantum circuit. """ for i1 in range(len(q)): yield gates.H(q[i1]) for i2 in r...
5,332,129
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) samples = coll...
5,332,130
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, underscores, or hyphens. Convert to...
5,332,131
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 #...
5,332,132
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 regex (str): ...
5,332,133
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: ...
5,332,134
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...
5,332,135
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 consistent across calls. :param user: T...
5,332,136
def uninstall(packages, options=None): """ Remove one or more packages. Extra *options* may be passed to ``opkg`` if necessary. """ manager = MANAGER command = "remove" if options is None: options = [] if not isinstance(packages, six.string_types): packages = " ".join(pa...
5,332,137
def print_init_dict(dict_, fname='test.trempy.ini'): """Print an initialization dictionary.""" version = dict_['VERSION']['version'] keys = ['VERSION', 'SIMULATION', 'ESTIMATION', 'SCIPY-BFGS', 'SCIPY-POWELL', 'SCIPY-L-BFGS-B', 'CUTOFFS', 'QUESTIONS'] # Add keys based on versio...
5,332,138
def test_chip_data(client) -> None: """ Test chip data. :param client: client :return: None """ response_value = client.get("/api/v1/chip_data") assert response_value.status_code == 200
5,332,139
def AuxStream_Cast(*args): """ Cast(BaseObject o) -> AuxStream AuxStream_Cast(Seiscomp::Core::BaseObjectPtr o) -> AuxStream """ return _DataModel.AuxStream_Cast(*args)
5,332,140
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...
5,332,141
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]
5,332,142
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=query) return r...
5,332,143
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(1, 100), 5) ...
5,332,144
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 to execute ...
5,332,145
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...
5,332,146
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...
5,332,147
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...
5,332,148
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( ...
5,332,149
def prettify_users(users: List[Dict]): # -> List[Dict]: """ Modify list of users in place. Make 'money' int, remove 'num' """ for user in users: user['money'] = int(user['money']) del user['num']
5,332,150
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...
5,332,151
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.path.basename...
5,332,152
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
5,332,153
def handle_jumbo_message(conn, message): """Handle a jumbo message received. """ payload = message.payload.message # TODO: this cuts out all sender and receiver info -- ADD SENDER GID logger.info(f"Received jumbo message fragment") prefix, seq, length, msg = payload.split("/") # if a jumbo ...
5,332,154
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. ...
5,332,155
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) > 0: logger.print('Missing sign-off(s):')...
5,332,156
def _reduction_range_bars(y, ylow, yhigh, sitecol, data=None, **kwargs): """ Draws upper/lower bound bars on `reduction_plots` """ ax = plt.gca() offset_map = { 'ED-1': 0.0, 'LV-2': -0.2, 'LV-4': +0.2 } data = ( data.assign(offset=data[sitecol].map(offset_map)) ...
5,332,157
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...
5,332,158
def handle_removed_term(event): """Un-index term into inner catalog""" parent = event.oldParent if IThesaurusTermsContainer.providedBy(parent): # pylint: disable=no-value-for-parameter thesaurus = parent.__parent__ if IThesaurus.providedBy(thesaurus): # pylint: disable=no-value-for-paramet...
5,332,159
def test_server_fixture( loop, aiohttp_client, ): """A pytest fixture which yields a test server to be used by tests. Args: loop (Event loop): The built-in event loop provided by pytest. aiohttp_client (aiohttp_client): Built-in pytest fixture used as a wrapper to the aiohttp web server...
5,332,160
def default_role(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """Set the default interpreted text role.""" if not arguments: if roles._roles.has_key(''): # restore the "default" default role del roles._roles[''] ...
5,332,161
def init(self): """Initialize the Instrument object with instrument specific values.""" self.acknowledgements = " ".join(("This work uses the SAMI2 ionosphere", "model written and developed by the", "Naval Research Laboratory.")) s...
5,332,162
def get_zind_json(server_token, output_folder) -> Dict: """ Returns the dict for the ZInD json. Sends a request to the BridgeAPI to get details about the ZInD Dataset Stores the respose json file in output folder :param server_token: token for access to the API :param output_folder: path to stor...
5,332,163
def input_fn(evaluate=False) -> tf.data.Dataset: """ Returns the text as char array Args: n_repetitions: Number of times to repeat the inputs """ # The dataset g = ( evaluate_generator if evaluate else train_generator ) ds = tf.data.Dataset.from_generator( generator=g, out...
5,332,164
def battle(players): """ Турнир - персонажи делятся на две команды и соревнуются. """ count_players = 10 winner_players = [] # перемешиваем участников и потом берём попарно shuffle(players) command1 = players[0:5] command2 = players[5:10] for i in range(5): winner = duel(...
5,332,165
def make_model_path(model_base_path: Text, model_name: Text, version: int) -> Text: """Make a TFS-flavored model path. Args: model_base_path: A base path containing the directory of model_name. model_name: A name of the model. version: An integer version of the model. Returns: ...
5,332,166
async def validate_input(data): """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ harmony = await get_harmony_client_if_available(data[CONF_HOST]) if not harmony: raise CannotConnect return { CONF_NAME: fin...
5,332,167
def to_wiggle_pairs(filein, fileout, region_string, endcrop=False): """ Constructs fragment pile-ups in wiggle format using paired-end information :param filein: BAM file that contains paired-end reads :param fileout: base output file name with extension (.wig) omitted :param region_string: region of i...
5,332,168
def window_tukey(M, alpha=0.5): """Return a Tukey window, also known as a tapered cosine window. The function returns a Hann window for `alpha=0` and a boxcar window for `alpha=1` """ if alpha == 0: return numpy.hann(M) elif alpha == 1: return window_boxcar(M) n = numpy.arange(0...
5,332,169
def workshopsDF(symbol="", **kwargs): """This is a meeting or series of meetings at which a group of people engage in discussion and activity on a particular subject, product or service to gain hands-on experience. https://iexcloud.io/docs/api/#workshops Args: symbol (str): symbol to use """ ...
5,332,170
def free_path(temp, diff, m_mol): """ Calculates the free path for a molecule Based on free_path.m by Joni Kalliokoski 2014-08-13 :param temp: temperature (K) :param diff: diffusion coefficient (m^2/s) :param m_mol: molar mass (kg/mol) :return: free path (m) """ return 3*diff*np.sqrt...
5,332,171
def comp_periodicity_spatial(self): """Compute the (anti)-periodicities of the machine in space domain Parameters ---------- self : Machine A Machine object Returns ------- pera : int Number of spatial periodicities of the machine over 2*pi is_apera : bool True ...
5,332,172
def download(date_array, tag, sat_id, data_path, user=None, password=None): """Routine to download F107 index data Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are '' and 'forecast'. (default=None) sat_id : (string or NoneType) ...
5,332,173
def shuffle_tensor(input): """ Returns a new tensor whose elements correspond to a randomly shuffled version of the the elements of the input. Args: input (`torch.Tensor`): input tensor. Returns: (`torch.Tensor`): output tensor. """ return input[torch.randperm(input.nelement())...
5,332,174
def relaunch_failed_jobs(tasks, spec_file, verbose=False): """ Relaunch jobs that are failed from the given list """ job_cnts = 0 # number of newly launched jobs for i, task in enumerate(tasks): job_id = str(task[-1]) # the last entry # Try to launch until succeed while True: ...
5,332,175
def intensityTriWave(coeff,L,ang): """Simulate the intensity observed a distance L from the grating. Standard Zernike coefficients, L, and the diffraction angle ang are used as input. """ k = 2*np.pi/405.e-6 #blue wavevector x,y = np.meshgrid(np.linspace(-1.1,1.1,1000),np.linspace(-1.1,1.1,1000)...
5,332,176
def do_auth_code_grant(fqdn, force_login=False, identity=None): """Perform an Oauth2 authorization grant consent flow.""" code_verifier, code_challenge = _gen_code() scope = (SCOPE_FORMAT.format(fqdn=fqdn)) host = GLOBUS_AUTH_HOST creds = _lookup_credentials() params = { 'redirect_uri...
5,332,177
def decode(serialized: str) -> Node: """Decode JSON as a `Node`""" node = json.loads(serialized) return dict_decode(node) if isinstance(node, dict) else node
5,332,178
def validate_duration_unit(recv_duration_unit): """Decapitalize and check in units_list""" units_list = DaysAndUnitsList.units_list recv_duration_unit = recv_duration_unit.lower() if recv_duration_unit in units_list: return True else: return False
5,332,179
def make_word_list1(): """Reads lines from a file and builds a list using append.""" t = [] fin = open('words.txt') for line in fin: word = line.strip() t.append(word) return t
5,332,180
def pytest_configure(config): """ Loads the test context since we are no longer using run.py """ # Monkey patch ssl so we do not verify ssl certs import ssl try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: # Legacy Python that doe...
5,332,181
def create_app(environment: str = None): """Create the Flask application. Returns: obj: The configured Flask application context. """ app = Flask(__name__) if environment is None: app.config.from_object(ConfigurationFactory.from_env()) else: app.config.from_object(Conf...
5,332,182
def metropolis(data, likelihood, priors, samples=1000, par_init=None, width_prop=.5): """ Returns the posterior function of the parameters given the likelihood and the prior functions. Returns also the number of the accepted jumps in the Metropolis-Hastings algorithm. Notes: - <w...
5,332,183
def _get_single_spec_df(reference_dict, mapping_dict, spectrum): """Primary method for reading and storing information from a single spectrum. Args: reference_dict (dict): dict with reference columns to be filled in mapping_dict (dict): mapping of engine level column names to ursgal unified col...
5,332,184
def in2func(inp): """Function converts input expression to a mathematical expression.""" # Validate Function if inp == "": raise ValueError( f"Enter a function to plot!") for char in re.findall("[a-zA-Z_]+", inp): if char not in allowed_inputs: # Error will communicate over s...
5,332,185
def filter_posts(posts: list, parsing_date: datetime) -> list: """Отфильтровывает лишние посты, которые не входят в месяц парсинга""" res = [] for post in posts: post_date = datetime.fromtimestamp(post['date']) if post_date.month == parsing_date.month: res.append(post) return...
5,332,186
def parse_bing(): """ 解析bing网页的壁纸链接,采用正则表达式匹配 :return: IMG_info,IMG_url """ base_url = 'https://cn.bing.com/' language_parameter = '?mtk=zh-CN' # base_url = 'https://www.bing.com/?mkt=zh-CN' try: resp = requests.get(base_url+language_parameter, headers=header).text except Req...
5,332,187
def quadsum(*args, **kwargs): """Sum of array elements in quadrature. This function is identical to numpy.sum except that array elements are squared before summing and then the sqrt of the resulting sums is returned. The docstring from numpy.sum is reproduced below for convenience (copied 2014-12-...
5,332,188
def open_file(path): """open_file.""" return codecs.open(path, encoding='utf8').read()
5,332,189
def plot_anomaly(ts: TimeSeries, anomaly, normal, lb, ub): """ Plotting the data points after classification as anomaly/normal. Data points classified as anomaly are represented in red and normal in green. """ plt.figure(figsize=(12, 8)) plt.plot(normal.index, normal, 'o', color='green') plt...
5,332,190
def get_api_status(): """Get API status""" return "<h4>API Is Up</h4>"
5,332,191
def loadtxt(filetxt, storage): """ Convert txt file into Blaze native format """ Array(np.loadtxt(filetxt), params=params(storage=storage))
5,332,192
def do_image_delete(gc, args): """Delete specified image.""" failure_flag = False for args_id in args.id: try: gc.images.delete(args_id) except exc.HTTPForbidden: msg = "You are not permitted to delete the image '%s'." % args_id utils.print_err(msg) ...
5,332,193
def save_changes( book, form, new = False): """ Save the changes to a given book """ import datetime book.title = form.title.data book.publisher = form.publisher.data book.author = form.author.data book.isbn13 = form.isbn13.data book.renter_name = '' book.rented_time = None ...
5,332,194
def kmeans_anchors(train_path='../datasets/ego-hand/train.txt', k_clusters=9, img_size=416, save_path=None): """Generate anchors for the dataset. Normalised labels: cls id, center x, center y, width, height """ # Get paths of training images and labels ann_paths = [] train_name = os.path.basena...
5,332,195
def test_attach_create_resource(fc_node_builder): """ Make sure upstream resource-create operator insertion works correctly """ node0 = OperatorNode({}, { 'name': 'test0', 'type': 'none', }) node1 = OperatorNode({}, { 'name': 'test1', 'type': 'none', }) node...
5,332,196
def test_peak_finder(): """Tests that the correct indices, voltage, and dq/dv value are returned for peaks found with peak_finder""" result = peak_finder(test_cycle1_df, 'c', 5, 3, test_datatype, 5, 0.4) assert len(result) == 3 peak_indices = result[0] peak_sigx_volts = result[1] peak_heigh...
5,332,197
def fgt_set_pressureUnit(pressure_index, unit): """Override the default pressure unit for a single pressure channel""" unit_array = (c_char * (len(unit)+1))(*([c_char_converter(c) for c in unit])) c_error = c_ubyte(lib.fgt_set_pressureUnit(c_uint(pressure_index), unit_array)) return c_error.value,
5,332,198
def login_basic(): """fails because not using formkey """ data = {'email': LOGIN_EMAIL, 'password': LOGIN_PASSWORD} encoded_data = urllib.urlencode(data) request = urllib2.Request(LOGIN_URL, encoded_data) response = urllib2.urlopen(request) print response.geturl()
5,332,199