content
stringlengths
22
815k
id
int64
0
4.91M
def _pluck(key: Any) -> Callable[[Observable], Observable]: """Retrieves the value of a specified key using dict-like access (as in element[key]) from all elements in the Observable sequence. Args: key: The key to pluck. Returns a new Observable {Observable} sequence of key values. To plu...
5,311,100
def delete_queue(*queues): """Delete queues from RabbitMQ""" with new_instance().connection() as conn: for name in queues: logger.debug("deleting queue %s", name) with conn.channel() as ch: ch.queue_delete(queue=name)
5,311,101
def change_rv_size( rv_var: TensorVariable, new_size: PotentialShapeType, expand: Optional[bool] = False, ) -> TensorVariable: """Change or expand the size of a `RandomVariable`. Parameters ========== rv_var The `RandomVariable` output. new_size The new size. expand:...
5,311,102
def validate_number_in_board(number, project, old_value=None): """ Validates `Column's` `number_in_board` field. Args: number (int) - Number to validate. project (`Project`) - Project instance. Returns: Tuple (bool, str) - Tuple which first value is success status and second ...
5,311,103
def translate(value, leftMin, leftMax, rightMin, rightMax): """ Normalize the data in range rightMin and rightMax :param value: Value to be normalize :param leftMin: original min value :param leftMax: original max value :param rightMin: final min value :param rightMax: final max value :r...
5,311,104
def validate_filters_parameter(fields_dict, args): """validate filters parameter""" _filter_sch = fields_dict.get("filter") _filter = args.get("filter") if not _filter: default_filter = { "field":_filter_sch.get("default_field"), "operation": _filter_sch.get("default_operation"), "value": args.get("user"...
5,311,105
async def yield_messages(generator): """Yield only the event and messages from generator.""" async for event, *data in generator: yield [ event, *list(filter( lambda item: isinstance(item, Message), data )) ]
5,311,106
def develop(action): """ Making sciwing developer workflow easy You can pass either one of this as argument ["makedirs", "download"] makedirs creates appropriate directories in the developer environment download - downloads the appropriate folders. """ HOME_DIR = pathlib.Path("~").expanduser() ...
5,311,107
def get_html_theme_path(): """Return the html theme path for this template library. :returns: List of directories to find template files in """ curdir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) return [curdir]
5,311,108
def test_measurement_base_metadata_type(measurement_base_01): """ Make sure that our measurement base type is indeed I07Nexus. If it is, then the following tests just quickly make sure that its values have remained intact. """ assert isinstance(measurement_base_01.metadata, I07Nexus)
5,311,109
def write_voc_results_file(write_dir, all_boxes, dataset): """ Args: write_dir: where evaluate result to be written down all_boxes: two-dimensional list, e.g. all_boxes[cls_idx][image_id], and cls_idx starts from 0 to num_classes - 1 that not including the background. ...
5,311,110
def generated_refl(): """Generate a reflection table.""" # these miller_idx/d_values don't make physical sense, but I didn't want to # have to write the tests for lots of reflections. reflections = flex.reflection_table() reflections["intensity.prf.value"] = flex.double([1.0, 10.0, 10.0, 1.0, 2.0]) ...
5,311,111
def euclidean_distance(position1, position2): """ :return: Euclidean distance between current pose and the goal pose """ x1, y1 = position1 x2, y2 = position2 return np.sqrt(pow((x2 - x1), 2) + pow((y2 - y1), 2))
5,311,112
def remove_unused_resources(issues, app_dir, ignore_layouts): """ Remove the file or the value inside the file depending if the whole file is unused or not. """ for issue in issues: filepath = os.path.join(app_dir, issue.filepath) if issue.remove_file: remove_resource_file(is...
5,311,113
def post_process_content(org_docs, api_method): """ Processes the content retrieved from mongo before presenting this to the users. :param org_docs: documents retrieved from mongo :param api_method: the fully qualified name of the target API method :return: """ docs = list(org_docs) for ...
5,311,114
def get_sqrt_2(): """Returns an approximation for the square root of 2""" return 1.41421356
5,311,115
def _wavefunctions_to_density(num_electrons, wavefunctions, grids): """Converts wavefunctions to density.""" # Reduce the amount of computation by removing most of the unoccupid states. wavefunctions = wavefunctions[:num_electrons] # Normalize the wavefunctions. wavefunctions = wavefunctions / jnp.sqrt(jnp.su...
5,311,116
def TempFile(**kw): """NamedTemporaryFile wrapper that doesn't fail if you (re)move the file """ f = NamedTemporaryFile(**kw) try: yield f finally: with ignore_missing_file(): f.__exit__(None, None, None)
5,311,117
def get_config(): """ Where you would normally do something like: parser = argparse.ArgumentParser(...) parser.add_argument(...) ... Now you need to store all your parameters in a function called get_config(). Put the @ex.config handle above it to ensure that Sacred knows this is the config ...
5,311,118
def get_gsx_entry_value(entry: Dict[str, Dict[str, str]], field: str) -> Optional[str]: """Returns the `entry` value for the given `field`.""" if not entry or not field: return None field = f"gsx${field}" if field not in entry: return None return entry[field]["$t"].strip()
5,311,119
def SEResNet(input_shape=None, num_outputs=1000, initial_conv_filters=64, depth=(3, 4, 6, 3), filters=(64, 128, 256, 512), width=1, bottleneck=False, weight_decay=1e-4, include_top=True, weights=None, ...
5,311,120
def subs_status(subs, prefix): """ Subcommand parsing for status """ sub = subs.add_parser(prefix + 'status', description='Info about this bot.') sub.set_defaults(cmd='Status') CMD_MAP['Status'] = 'status'
5,311,121
def test_moment_0_err(): """ zeroth order moment error """ moment, err = survey.moment(return_sigma = True) assert moment.unit == err.unit
5,311,122
def binary(gray_img, threshold, max_value, object_type="light"): """Creates a binary image from a grayscale image based on the threshold value. Inputs: gray_img = Grayscale image data threshold = Threshold value (0-255) max_value = value to apply above threshold (usually 255 = white) ...
5,311,123
def tf_hgrid_coords(shape: RankStaticShape) -> tf.Tensor: """ Produce hyper-grid coordinates :param shape: :return: """ static_rank = len(shape) shape = tf.convert_to_tensor(shape, dtype=tf.int64) comps = [tf.tile(tf_repeat_1d(tf.range(shape[k]), t=tf.reduce_prod(shape[k+1:])), [tf.reduc...
5,311,124
def listify(revision_str): """Split a revision string into a list of alternating between strings and numbers, padded on either end to always be "str, int, str, int..." and always be of even length. This allows us to trivially implement the comparison algorithm described at http://debian.org/doc/deb...
5,311,125
def parse_fvalues(fvalues: Sequence) -> frozenset: """ Parse a sequence of fvalues as a frozenset. This function is mostly used for parsing string provided by the user, splitting them accordingly, but accepts any sequence type. If a string is passed, it will use different delimiters and guarantees ...
5,311,126
def get_resume(text): """ :param text: text to resume :return: first paragraphe in the text """ # regex = re.compile(r"^(.*?)\n") # return regex.match(text).group(1) return text[:500]
5,311,127
def test_dependencies_for_spyder_dialog_in_sync(): """ Spyder dependencies dialog should share deps with conda.txt. """ spyder_deps = parse_spyder_dependencies() spyder_reqs = parse_requirements(REQ_FPATH) # No need to check for these deps because either we're using # a subrepo for them or ...
5,311,128
def convert_quat_to_rotmat(quat, quat_scalar_last=False): """Convert quaternion rotation to rotation matrix.""" if quat_scalar_last: return R.from_quat(quat).as_matrix() else: return R.from_quat( convert_quat_wxyz_to_xyzw(quat) ).as_matrix()
5,311,129
def vgg_like_v2(input_shape, base_filters=32): """ a VGG structure model, used this one in final object-wise detection input_shape: input size in (x,y,z) """ input_shape = input_shape + (1,) # one channel inputs = Input(shape=input_shape) # 48x48x48 conv1 = _conv_block(input_tensor=input...
5,311,130
def fuse_conv(conv, norm): """ [https://nenadmarkus.com/p/fusing-batchnorm-and-conv/] """ fused_conv = torch.nn.Conv2d(conv.in_channels, conv.out_channels, conv.kernel_size, conv.stride, ...
5,311,131
def duo_private(request): """ View which requires a login and Duo authentication. """ return HttpResponse( '<p>Content protected by Django and Duo auth.' '<p><a href="/accounts/logout">Log out of primary Django auth.</a>' '<p><a href="/accounts/duo_logout">Log out of secondary Du...
5,311,132
def inspect_model(model_file, cppn_genome): """ Load and inspect the performance of an agent in a given environment :param model_file: The full path of the .json file containing the agent model to be inspected. :param cppn_genome: Either the full path of the pickle file containing the CPPN that the agen...
5,311,133
def eval_postprocess(positive_path, negative_type): """ get accuracy """ files = os.listdir(positive_path) log = [] for f in files: score_file = os.path.join(config.result_path, f.split('.')[0] + '_0.bin') positive_file = os.path.join(positive_path, f) argsort = np.fromfile(score...
5,311,134
def compute_q10_correction(q10, T1, T2): """Compute the Q10 temperature coefficient. As explained in [1]_, the time course of voltage clamp recordings are strongly affected by temperature: the rates of activation and inactivation increase with increasing temperature. The :math:`Q_{10}` temperature ...
5,311,135
def get_frameworks_table(): """ Generates a dataframe containing the supported auto classes for each model type, using the content of the auto modules. """ # Dictionary model names to config. config_maping_names = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES model_...
5,311,136
def player(stream_url): """ Takes the stream url and plays the audio in background process while listening for input controls. :param stream_url: :return: """ valid_media_extensions = [ "audio/mpeg", "audio/aac", "application/ogg", "audio/x-m4a", "audio/3g...
5,311,137
def add_user_to_session(user): """Store user info on session""" ppc.db.session.add(user) ppc.db.session.flush() flask.session['user.biv_id'] = user.biv_id flask.session['user.oauth_type'] = user.oauth_type flask.session['user.is_logged_in'] = True flask.session['user.display_name'] = user.di...
5,311,138
def explode(coords): """Explode a GeoJSON geometry's coordinates object and yield coordinate tuples. As long as the input is conforming, the type of the geometry doesn't matter.""" for e in coords: if isinstance(e, (float, int, int)): yield coords break else: ...
5,311,139
def extract_video_features(model, get_frame_fn, video_names, video_frame_counts, update_progress_cb=None): """ :param model: :param get_frame_fn: :param video_names: :param video_frame_counts: :param update_progress_cb: :return: VxF np.float32 array """ clip_features = [] for v...
5,311,140
def test_subset_run_no_prep(): """[SequentialEnsemble | Subset | No Prep] retrieves fit predictions.""" run(SequentialEnsemble, 'subsemble', False, False, partitions=2, folds=2, model_selection=True)
5,311,141
def test_parser(): """ test md file parser """ assert config_file.exists(), 'config file not found' parser = MD_Parser(config_file) assert parser._cfg['index']['template'] == 'index.html' blocks = parser.parse_section('index') print(blocks) assert len(blocks) == 2 assert blocks[0]['n...
5,311,142
def osarch_is_amd64(): """Check if the architecture maps to amd64.""" return osarch_match("amd64")
5,311,143
def test_all_methods_adhere_to_contract(filter_class): """Test that all filter algorithms adhere to the filtering contract""" default_kwargs = filter_class._DEFAULT_TESTING_PARAMETERS # TODO ambrosejcarr: all filters should accept boolean is_volume instance = filter_class(**default_kwargs) # TODO...
5,311,144
def increase_contrast(im, method = 'adaptive'): """ Adative method seems to deal with background gradients the best, but two other options are possible using scikit package """ ## SEE: https://scikit-image.org/docs/dev/auto_examples/color_exposure/plot_equalize.html from skimage import exposure if ...
5,311,145
def without(array, *values): """Creates an array with all occurrences of the passed values removed. Args: array (list): List to filter. values (mixed): Values to remove. Returns: list: Filtered list. Example: >>> without([1, 2, 3, 2, 4, 4], 2, 4) [1, 3] ....
5,311,146
def get_total_mnsp_ramp_rate_violation(model): """Get total MNSP ramp rate violation""" ramp_up = sum(v.value for v in model.V_CV_MNSP_RAMP_UP.values()) ramp_down = sum(v.value for v in model.V_CV_MNSP_RAMP_DOWN.values()) return ramp_up + ramp_down
5,311,147
def get_row_line(p1,p2): """ Compute x,y values and alpha angle for the line between start (p1) and ending (p2) points """ l,alpha = line_polar(p1,p2) x,y = line_polar_to_cart(l,alpha,p1) return (np.round(x).astype("int"),np.round(y).astype("int"),alpha)
5,311,148
def shortestpath(fst, output_file, nshortest=1, **kwargs): """ Find shortet path through fst :param fst: input fst in binary format :param output_file: output fst in binary format :param nshortest: number of shortest paths :param kwargs: see fstpostprocess_cmd """ cmd = fstshortestpath_cmd...
5,311,149
def doctor() -> None: """ Diagnose common issues which stop this CLI from working correctly. """ check_functions = [ check_docker, check_1_9_sed, check_ssh, check_vagrant, check_vagrant_plugins_installed, check_vagrant_plugin_versions, check_virtua...
5,311,150
def train_substage(model, sess, lr_val, l1_lambda, l2_lambda, n_epoch, n_iter, n_iter_buffer, n_iter_patience, args): """ Training function that does one stage of training. The stage training can be repeated and modified to give better training result. Args: model (CellBox): an CellBox instance...
5,311,151
def parse_traceroute(raw_result): """ Parse the 'traceroute' command raw output. :param str raw_result: traceroute raw result string. :rtype: dict :return: The parsed result of the traceroute command in a \ dictionary of the form: :: {1: {'time_stamp2': '0.189', ...
5,311,152
def SetAliasEthernetIp(ip, alias_index=0, interface=None, mask='255.255.255.0'): """Sets the alias IP address for Ethernet. Args: ip: The ip address want to set. alias_index: Alias interface index. interface: The target interface. mask: Network mask. """ interface = interface or FindUsableEthDe...
5,311,153
def get_scheds(aircraft_list, flights): """ Generates a list of Schedule objects with the appropriate attributes Parameters ---------- aircraft_list : list, aircrafts in plan flights : list, list of classes.Flight objects Returns ------- schedules : list, l...
5,311,154
def make_kml(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, figs, colorbar=None, **kw): """TODO: LatLon bbox, list of figs, optional colorbar figure, and several simplekml kw...""" kml = Kml() altitude = kw.pop('altitude', 2e7) roll = kw.pop('roll', 0) tilt = kw.pop('tilt', 0) alt...
5,311,155
def update_from_copyright_info(delta): """ Increase an 'added' or 'modified' Delta object's 'score' attribute and add one or more appropriate categories to its 'factors' attribute if there has been a copyright change and depending on the nature of that change. """ if delta.is_added(): up...
5,311,156
def exception_caught_in_background_thread(e): """ Function which handled exceptions that are caught in background thread. This is typically called from the callback thread inside the pipeline. These exceptions need special handling because callback functions are typically called inside a non-appli...
5,311,157
def save_alias(tab_lib): """Save alias into the library file""" alias = '' if 'alias' in tab_lib: alias += tab_lib['alias'].strip() + '\n' if 'lib_name' in tab_lib: lib_name = tab_lib["lib_name"] if 'simple_alias' in tab_lib: mapping = _parse_mapping_config(tab_lib['s...
5,311,158
def _transform_get_item_to_module(module: Module, debug: bool) -> GraphModule: """Transforms the built-in getitem function to ReduceTuple module. This function is usually used to reduce the tuple output of RNNs. Args: module: container module to transform debug: whether to print debug mess...
5,311,159
def build_parser(argv: Optional[List] = None): """Return ArgumentParser parser for script.""" # Create parser object parser = argparse.ArgumentParser( prog="cw_query_database", description="Interrogate a local CAZyme database", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ...
5,311,160
def test_running_state_during_test(tmpdir): """ Tests that state is set to RUNNING during test """ hparams = EvalModelTemplate.get_default_hparams() model = EvalModelTemplate(**hparams) snapshot_callback = StateSnapshotCallback(snapshot_method='on_test_batch_start') trainer = Trainer( cal...
5,311,161
def symptom_LDAP_user_enabled_emulation_use_group_config_ignored(): """`[ldap] user_enabled_emulation_use_group_config` is being ignored. There is no reason to set this value unless `keystone.conf [ldap] user_enabled_emulation` is also enabled. """ return ( not CONF.ldap.user_enabled_emulat...
5,311,162
def measure_from_structure(f): """ Do geometric measures required on a given filename """ name = f.split('.')[0] global idxQueue thr_idx = idxQueue.get() setproctitle(f"RNANet statistics.py Worker {thr_idx+1} measure_from_structure({f})") # Open the structure with warnings.catch_...
5,311,163
def test_execute_local_query(): """ Ensure we can run "local" queries against a single db conveniently """ queries = core.load_queries() with core.connect() as connection: result = list( core.execute_local(connection, queries.db, "dbname", "index_io") ) for row in res...
5,311,164
def add_user(): """Add a new user, you must have permissions""" form = UserForm() resp_message = 'Invalid payload.' if not form.validate(): return BadRequest(resp_message) username = form.username.data email = form.email.data password = form.password.data user = User.query.filte...
5,311,165
def _fetch_remote(remote, dirname=None): """Helper function to download a remote dataset into path Fetch a dataset pointed by remote's url, save into path using remote's filename and ensure its integrity based on the SHA256 Checksum of the downloaded file. Parameters ---------- re...
5,311,166
def evaluate(config: ConfigLoader, model, validationloader): """ evaluate model using the data given by validationloader Args: config (ConfigLoader): config of the experiment model (nn.Module): model to be evaluated validationloader (torch.utils.data.DataLoader): dataloader containing t...
5,311,167
def curve( data: dict, *, ax: Union[plt.Axes, None] = None, curve_layout: Literal["overlay", "stacked", "shifetd"] = "overlay", shade: bool = True, kde_norm: bool = True, order: Union[list, None] = None, kernel_kws: Union[dict, None] = None, style: Union[Literal["default"], None] = "...
5,311,168
def load_kaldi_hmms(fctx): """Load HMMs from text output of context to pdf binary""" hmms ={} hmm = [] for line in open(fctx): lx = line.strip().split() ctx = (lx[0], lx[1], lx[2]) n = int(lx[3]) pdf = int(lx[4]) # we do not need disambig phones if "#" in ctx[0] or "#" in ctx[1] or "#" in ctx[2]: c...
5,311,169
def mask (raster, threshold, symName): """Highlight those raster pixels that reach/exceed the given threshold.""" return layer(Local("U8", "Greater Than Equal", Resample(raster,5), threshold), symName)
5,311,170
def get_vector_w2v(sent:Series, model:gensim.models.keyedvectors.Word2VecKeyedVectors): """ Create a word vector for a given sentence using a Word2Vec model. This function is called in a lambda expression in `core.get_vectors`. Returns list """ tokens = [token for token in sent.phrase if token ...
5,311,171
def inc(initial_value): """Return arithmetic increase of 1 to initial_value""" print "In inc() subroutine now" return initial_value + 1
5,311,172
def search(): """Search page ui.""" return render_template(current_app.config["SEARCH_UI_SEARCH_TEMPLATE"])
5,311,173
def vendor_id(request): """ Return the paddle.com vendor ID as a context variable """ return {"DJPADDLE_VENDOR_ID": settings.DJPADDLE_VENDOR_ID}
5,311,174
def factory(cls, modules=None, **kwargs): """ Factory for creating objects. Arguments are passed directly to the constructor of the chosen class. """ # Format modules into a list if modules is None: modules = [__name__] elif isinstance(modules,basestring): modules = [modules] # Import t...
5,311,175
def filter_samplesheet_by_project(file_path, proj_id, project_column_label='SampleProject', output_ini_headers=False): """ Windows \r\n :param file_path: :type file_path: :param proj_id: :type proj_id: :param project_column...
5,311,176
def ecliptic_obliquity_radians(time): """Returns ecliptic obliquity radians at time.""" return math.radians(23.439 - 0.0000004 * time)
5,311,177
def hessian_Y(D , Gamma, eigQ, W, sigma_t): """ this is the linear operator for the CG method argument is D Gamma and W are constructed beforehand in order to evaluate more efficiently """ tmp1 = eval_jacobian_phiplus(D, Gamma, eigQ) tmp2 = eval_jacobian_prox_p( D , W) res = - sigma_t *...
5,311,178
def spec_pix_to_world(pixel, wcs, axisnumber, unit=None): """ Given a WCS, an axis ID, and a pixel ID, return the WCS spectral value at a pixel location .. TODO:: refactor to use wcs.sub """ coords = list(wcs.wcs.crpix) coords[axisnumber] = pixel+1 coords = list(np.broadcast(*coords...
5,311,179
def share_replica_get(context, replica_id, with_share_data=False, with_share_server=False, session=None): """Returns summary of requested replica if available.""" session = session or get_session() result = _share_replica_get_with_filters( context, with_share_server=with_share...
5,311,180
def create_cache_dir(cache_dir): """Create cache directory.""" Path(cache_dir).mkdir(parents=True, exist_ok=True)
5,311,181
async def playing_song(this, ctx: Context): """재생중인 컨텐츠 정보 보기 :param this: self :param ctx: discord.ext.commands.Context """ vc = ctx.voice_client if not vc or not vc.is_connected(): return await ctx.send(embed=embed_ERROR, delete_after=20) player = this.get_player(ctx) if not...
5,311,182
def check_and_record_restart_request(service, changed_files): """Check if restarts are permitted, if they are not log the request. :param service: Service to be restarted :type service: str :param changed_files: Files that have changed to trigger restarts. :type changed_files: List[str] :return...
5,311,183
def get_user_wantlist(user: Union[UserWithoutAuthentication, UserWithUserTokenBasedAuthentication], username: str, page: Union[int, None] = None, per_page: Union[int, None] = None, ) -> requests.mod...
5,311,184
def unplug_contrail_vif(port_id, dev_name=None, vnic_type=None, pci_dev=None, vhostuser_socket=None, vhostuser_mode=None): """Call the vrouter port control script to unplug a vif :param port_id: VIF ID to unplug :param dev_name: Name of the TAP/device to unplug :param vnic_type:...
5,311,185
def gaussian_additive_noise(x, sigma): """Gaussian additive noise. Parameters ---------- x : array input data matrix. sigma : float noise standard deviation. Noise values are sampled from N(0, sigma) for each input feature. Returns ------- x_noise : array output...
5,311,186
def test_entities__Entities__1(): """`Entities` fulfills the `IEntities` interface.""" zope.interface.verify.verifyObject(IEntities, Entities())
5,311,187
def LCOH_fn(well_cost = None, Ed = None, mdot = None, dP_inj = None): """ Calculates the LCOH based on the well cost as capital cost and the pumping cost for operating cost, and the thermal energy recovered. Results match simplified_LCOH_fn, but simplified_LCOH_fn is preferred because it matches th...
5,311,188
def confirm_uid(request): """confirm with code sent to uid""" params = request.get_params(schemas.AddUIDCodeSchema()) device = get_device(request) customer = device.customer wc_params = { 'secret': params['secret'], 'code': params['code'], 'attempt_id': params['attempt_id'],...
5,311,189
def get_coverage(file, label, regions=None, nth=1, readcount=-1): """Get coverage for every `nth` position from alignment file.""" readcount = float(readcount) contigs_coverage = defaultdict(dd) with pysam.AlignmentFile(file) as f: if isinstance(regions, str): regions = [regions] ...
5,311,190
def equations_to_matrix() -> list: """ :return: augmented matrix formed from user input (user inputs = linear equations) :rtype: list """ n = int(input("input number of rows ")) m = int(input("input number of columns ")) A = [] for row_space in range(n): print("input row ", row_...
5,311,191
async def base_control(timestamp: datetime.datetime, base_id: int, new_faction_id: int, old_faction_id: int, server_id: int, continent_id: int, conn: Connection[Row]) -> bool: """Dispatch a ``BaseControl`` Blip to the database.""" try: ...
5,311,192
def get_ports(): """List all serial port with connected devices. Returns ------- port_list : list(str) Names of all the serial ports with connected devices. """ port_list = list(list_ports.comports()) for i in range(len(port_list)): port_list[i] = port_list[i].device ...
5,311,193
def disable_distribution( distribution_id: str, configuration: Configuration = None, secrets: Secrets = None, ) -> AWSResponse: """ Disables a cloudfront distribution. Input distribution id. """ if not distribution_id: raise FailedActivity( "you must specify the distribut...
5,311,194
def same_origin(origin1, origin2): """ Return True if these two origins have at least one common ASN. """ if isinstance(origin1, int): if isinstance(origin2, int): return origin1 == origin2 return origin1 in origin2 if isinstance(origin2, int): return origin2 in o...
5,311,195
def generate_output(model, sequences, idx_word, seed_length=50, new_words=50, diversity=1, return_output=False, n_gen=1): """Generate `new_words` words of output from a trained...
5,311,196
def stagewise_grad(w, X, Y, alpha, valpha): """ the gradient loss used in the stage-wise gradient descent (where the value-at-risk is fixed) Parameters ---------- w : d-array, candidate X : d-n array, sample Y : n array, sample alpha : float, quantile leve...
5,311,197
def db_init(): """Clear existing data and create new tables.""" with current_app.open_resource('schema.sql') as f: get_db().executescript(f.read().decode('utf8'))
5,311,198
def save_database(database, filename): """Saves a database to disk""" compressed_db = compress_database(database) print("[database] Saving database to '" + filename + "'") with open(filename, "w") as f: json.dump(compressed_db, f, sort_keys=True, indent=2, separators=(',', ': '))
5,311,199