content
stringlengths
22
815k
id
int64
0
4.91M
def absModuleToDist(magApp, magAbs): """ Convert apparent and absolute magnitude into distance. Parameters ---------- magApp : float Apparent magnitude of object. magAbs : float Absolute magnitude of object. Returns ------- Distance : float The distance resu...
3,100
def decoded_anycli(**kwargs): """ Return the decoded return from AnyCLI request - Do not print anything :param kwargs: keyword value: value to display :return: return the result of AnyCLI in UTF-8 :Example: result = cli(url=base_url, auth=s, command="show vlan") decoded_anycli(resul...
3,101
def job_results_html(request): """ Used for testing the update with debug toolbar. """ response = job_results(request) return render(request, 'ci/ajax_test.html', {'content': response.content})
3,102
def open_mcrae_nature_cohort(): """ get proband details for McRae et al., Nature 2017 McRae et al Nature 2017 542:433-438 doi: 10.1038/nature21062 Supplementary table S1. """ data = pandas.read_excel(url, sheet_name='Supplementary Table 1') data['Individual ID'] += '|DDD' pheno...
3,103
def copia_coords_alineadas(align1,align2,coords_molde,PDBname): """ Devuelve: 1) una lista con las coordenadas de coords_molde que se pueden copiar segun el alineamiento align1,align2. 2) una estimacion del RMSD segun la curva RMSD(A) = 0.40 e^{l.87(1-ID)} de Chothia & Lesk (1986) """ aanames = { "A":"ALA",...
3,104
def get_amati_relationship(value='o'): """ Return the Amati relationship and it's 1 sigma dispersion as given by Tsutsui et al. (2009). :param value: a string that can be 'o', '+', or '-'. The default is set to 'o' for the actual Amati relationship. '+' gives the upper bound of uncertainty and '-' gives the lower...
3,105
def load(name, final=False, torch=False, prune_dist=None): """ Returns the requested dataset. :param name: One of the available datasets :param final: Loads the test/train split instead of the validation train split. In this case the training data consists of both training and validation. :retu...
3,106
def is_paragraph_debian_packaging(paragraph): """ Return True if the `paragraph` is a CopyrightFilesParagraph that applies only to the Debian packaging """ return isinstance( paragraph, CopyrightFilesParagraph ) and paragraph.files.values == ['debian/*']
3,107
def update_b(b, action_prob, yr_val, predict_mode): """Update new shape parameters b using the regression and classification output. Args: b: current shape parameters values. [num_examples, num_shape_params]. action_prob: classification output. [num_actions]=[num_examples, 2*num_shape_params] ...
3,108
def setup(args): """ Create configs and perform basic setups. """ cfg = get_cfg() add_config(args, cfg) cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) cfg.merge_from_list(['MODEL.BUA.EXTRACT_FEATS',True]) cfg.merge_from_list(switch_extract_mode(args.extract_mode...
3,109
def _earth_distance(time='now'): """ Return the distance between the Sun and the Earth at a specified time. Parameters ---------- time : {parse_time_types} Time to use in a parse_time-compatible format Returns ------- out : `~astropy.coordinates.Distance` The Sun-Earth ...
3,110
def test_pixel_sum_2D(model_class, mode): """ Test if the sum of all pixels corresponds nearly to the integral. """ if model_class == Box2D and mode == "center": pytest.skip("Non integrating mode. Skip integral test.") parameters = models_2D[model_class] model = create_model(model_class...
3,111
async def DELETE_Link(request): """HTTP method to delete a link""" log.request(request) app = request.app group_id = request.match_info.get('id') if not group_id: msg = "Missing group id" log.warn(msg) raise HTTPBadRequest(reason=msg) if not isValidUuid(group_id, obj_cla...
3,112
def addBookRec(title, author, releaseDate, releasePlace, pages, ISBN): """ creates a new record in the database """ con = sqlite3.connect("library.db") cur = con.cursor() cur.execute("INSERT INTO book VALUES (NULL, ?, ?, ?, ?, ?, ?)", (title, author, releaseDate, releasePlace, pages, ISBN)) ...
3,113
def test__additional_sign_plan__create_with_content_id(admin_user): """ Test that AdditionalSignPlan API endpoint POST request raises an error if any of the content instances have a id defined. Pre-existing content instances can not be assigned for newly created additional signs. """ client ...
3,114
def format_image(image): """ Function to format frame """ if len(image.shape) > 2 and image.shape[2] == 3: # determine whether the image is color image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) else: # Image read from buffer image = cv2.imdecode(image, cv2.CV_LOAD_IMA...
3,115
def cpu_stats(): """Return various CPU stats as a named tuple.""" ctx_switches, interrupts, syscalls, traps = cext.cpu_stats() soft_interrupts = 0 return _common.scpustats(ctx_switches, interrupts, soft_interrupts, syscalls)
3,116
def chi_squared(source_frequency, target_frequency): """Calculate the Chi Squared statistic by comparing ``source_frequency`` with ``target_frequency``. Example: >>> chi_squared({'a': 2, 'b': 3}, {'a': 1, 'b': 2}) 0.1 Args: source_frequency (dict): Frequency map of the text you are...
3,117
def has_reacted(comment, user, reaction): """ Returns whether a user has reacted with a particular reaction on a comment or not. """ if user.is_authenticated: reaction_type = getattr(ReactionInstance.ReactionType, reaction.upper(), None) if not reaction_type: raise template.T...
3,118
def u(debug_print: str, debug_from: str = None, end: bool = False): """ Updates the colourised string of the terminal with debug_print. If end is True the line is ended Parameters ---------- debug_print: str Test to be used updated the terminal with. debug_from: str, optional To specify where debug te...
3,119
def structure_query(compound, label='pyclassyfire'): """Submit a compound information to the ClassyFire service for evaluation and receive a id which can be used to used to collect results :param compound: The compound structures as line delimited inchikey or smiles. Optionally a tab-separated id ...
3,120
def test_colored_svg_cache(qtbot): """Make sure we're not recreating icons.""" icon1 = QColoredSVGIcon.from_resources('new_points') icon2 = QColoredSVGIcon.from_resources('new_points') assert icon1 is icon2 assert icon1.colored('red') is icon2.colored('red')
3,121
def ParseExistingMessageIntoMessage(message, existing_message, method): """Sets fields in message based on an existing message. This function is used for get-modify-update pattern. The request type of update requests would be either the same as the response type of get requests or one field inside the request ...
3,122
def disable_logger(name: str): """Disable the logger with the given name.""" null = logging.NullHandler() null.setLevel(logging.DEBUG) logger = logging.getLogger(name) logger.addHandler(null) logger.propagate = False
3,123
def create(*, db_session, ticket_in: TicketCreate) -> Ticket: """Creates a new ticket.""" ticket = Ticket(**ticket_in.dict()) db_session.add(ticket) db_session.commit() return ticket
3,124
def error(msg: str) -> None: """Equivalent to ``log(msg, level=logging.ERROR)``. Args: msg: A message to log. """ log(msg, level=logging.ERROR)
3,125
def ls_volume(path): """Lists you files in a volume. Example: \b roro volume:ls <volume_name> lists all files in volume "volume_name" \b roro volume:ls <volume_name:dir> lists all filies at directory "dir" in volume "volume" """ path = path+':' if ':' n...
3,126
def blur(img): """ :param img: SimpleImage, an original image. :return: img: SimpleImage, image with blurred effect. """ blank_img = SimpleImage.blank(img.width, img.height) for y in range(img.height): for x in range(img.width): blurred = blank_img.get_pixel(x, y) ...
3,127
def trans_pressure(src, dest="bar"): """ >>> """ return trans_basic_unit(src, dest, "pressure")
3,128
def run_cmd(command: list) -> None: """Run `command` using `subprocess.Popen()`.""" show_info(f"Command: {' '.join(command)}") if DRY_RUN: show_info("Dry run mode enabled - won't run") else: try: proc = subprocess.Popen(command, stdout=subprocess.PIPE) stdout = p...
3,129
def test_accelerated_bypass_method_against_old(c_ctrl_rr): """Confirm that my changes to the bypass method maintain the same result as the old method""" OLD_HTCONSTS = dassh.region_rodded.calculate_ht_constants(c_ctrl_rr) def _calc_coolant_byp_temp_old(self, dz): """Calculate the coolant temper...
3,130
def retrieve_config(): # TODO: is this being used? """Retrieve configuration data. Args: None Returns: dict: The dictionary with configuration settings """ config = {} # go 2 layer up util_path = Path(__file__).parents[3] config_path = util_path / 'configuration' / 'c...
3,131
def vraec18(pretrained=False, **kwargs): """Constructs a _ResAE-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = _VRAEC(_VariationalBasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: try: model.load_state_dict(model_zoo.load...
3,132
def encode_zip(data): """Zip-compress data. Implies base64 encoding of zip data.""" zipped = zlib.compress(data) return encode_b64(zipped)
3,133
def create_class_mask(img, color_map, is_normalized_img=True, is_normalized_map=False, show_masks=False): """ Function to create C matrices from the segmented image, where each of the C matrices is for one class with all ones at the pixel positions where that class is present img = The segmented image ...
3,134
def reconstruct_grid(mask, ds_dl): """ Reconstruction of 2d grid. Args: mask (ndarray): land mask used. ds_dl (ndarray): trained model prediction. """ landmask = np.argwhere(np.isnan(mask)) empty = np.zeros((ds_dl.shape[0], mask.shape[0], mask.shape[1])) ...
3,135
def conv_kernel_initializer(shape, dtype=None): """卷积核初始化 和 tf.variance_scaling_initializer最大不同之处就是在于,tf.variance_scaling_initializer 使用的是 truncated norm, 但是却具有未校正的标准偏差,而这里使用正态分布。类似地,tf.initializers.variance_scaling使用带有校正后的标准偏差。 Args: shape: 卷积核的shape dtype: 卷积核的dtype Returns: ...
3,136
def pytest_addoption(parser): """Add support for the RP-related options. :param parser: Object of the Parser class """ group = parser.getgroup('reporting') group.addoption( '--rp-launch', action='store', dest='rp_launch', help='Launch name (overrides rp_launch config...
3,137
def prediction_func(data, g_data, grid_search, param_list): """Function for using dataset to train a model and predicting prices for a generated data. Parameter search is done using RandomizedSearchCV since it is computationally more efficientcompared to GridSearchCV. In param_list, learning_rate,...
3,138
def unfreeze_params(module, frozen_params): """Unfreeze params Args: module (torch.nn.Module): frozen_params: a list/tuple of strings, which define all the patterns of interests """ for name, params in module.named_parameters(): for pattern in frozen_params: assert ...
3,139
def thv_to_zxy(theta, h): """Convert coordinates from (theta, h, v) to (z, x, y) space.""" cos_p = np.cos(theta) sin_p = np.sin(theta) srcx = +RADIUS * cos_p - h * sin_p srcy = +RADIUS * sin_p + h * cos_p detx = -RADIUS * cos_p - h * sin_p dety = -RADIUS * sin_p + h * cos_p return srcx, ...
3,140
def get_most_stale_file(logpath=DEFAULT_PATH): """ returns the filename of the file in the fileset that was least recently backed up and the time of the last backup """ oldest_name = "" oldest_date = datetime.max for fstat in get_fileset_statlist(): last_backup = datetime.strptime( ...
3,141
def add_user_tweets(username,tweets_qty=LIGHT_QTY): """Add a new user and their Tweets, or else error""" try: twitter_user=TWITTER.get_user(username) db_user= User(id=twitter_user.id, name=username) DB.session.add(db_user) tweets = twitter_user.timeline(count=tweets_qty,include_r...
3,142
def get_instances(context: models.Context) -> Mapping[str, Instance]: """Get a list of Instance matching the given context, indexed by instance id.""" instances: Dict[str, Instance] = {} if not apis.is_enabled(context.project_id, 'compute'): return instances gce_api = apis.get_api('compute', 'v1', context....
3,143
def UploadChanges(): """Upload changes, don't prompt.""" # TODO(jfb) Using the commit queue and avoiding git try + manual commit # would be much nicer. See '--use-commit-queue' return ExecCommand(['git', 'cl', 'upload', '--send-mail', '-f'])
3,144
def svn_fs_delete_fs(*args): """svn_fs_delete_fs(char const * path, apr_pool_t pool) -> svn_error_t""" return _fs.svn_fs_delete_fs(*args)
3,145
def translate_output(_output, n_classes, is_binary_classification=False): """ Gets matrix with one hot encoding where the 1 represent index of class. Parameters ---------- _output : theano.tensor.matrix Output sample. n_classes : int Number of classes (or size of one hot encoding r...
3,146
def get_agent_config_vars(): """ Read and parse config.ini """ if os.path.exists(os.path.abspath(os.path.join(__file__, os.pardir, 'config.ini'))): config_parser = ConfigParser.SafeConfigParser() config_parser.read(os.path.abspath(os.path.join(__file__, os.pardir, 'config.ini'))) try: ...
3,147
def test_product_weight(self): """Test new product weight being 20.""" prod = Product('Test Product') self.assertEqual(prod.weight, 20)
3,148
def _sphere_point_to_uv(point: Point) -> Vec2d: """Convert a 3D point on the surface of the unit sphere into a (u, v) 2D point""" u = atan2(point.y, point.x) / (2.0 * pi) return Vec2d( u=u if u >= 0.0 else u + 1.0, v=acos(point.z) / pi, )
3,149
def generate_formula_dict(materials_store, query=None): """ Function that generates a nested dictionary of structures keyed first by formula and then by task_id using mongo aggregation pipelines Args: materials_store (Store): store of materials Returns: Nested dictionary keyed ...
3,150
def default_config(): """Provides a default configuration file location.""" return os.path.expanduser('~/.config/discogstagger/discogs_tagger.conf')
3,151
def truncate(wirevector_or_integer, bitwidth): """ Returns a wirevector or integer truncated to the specified bitwidth :param wirevector_or_integer: Either a wirevector or and integer to be truncated :param bitwidth: The length to which the first argument should be truncated. :return: Returns a tuncate...
3,152
def async_add_entities_config(hass, config, async_add_entities): """Set up light for KNX platform configured within platform.""" import xknx group_address_tunable_white = None group_address_tunable_white_state = None group_address_color_temp = None group_address_color_temp_state = None if c...
3,153
def save_spectra_model(spectra_model,element = None,name = None,filepath = None): """Save a SpectraModel object to .hdf5 Parameters ---------- spectra_model : SpectraModel instance SpectraModel to be saved. element: str Element that is being modeled. For example: 'C' or 'Nb' or 'O'. ...
3,154
def pcoef(xte, yte, rle, x_cre, y_cre, d2ydx2_cre, th_cre, surface): # Docstrings """evaluate the PARSEC coefficients""" # Initialize coefficients coef = np.zeros(6) # 1st coefficient depends on surface (pressure or suction) if surface.startswith('p'): coef[0] = -sqrt(2*rle) e...
3,155
def adjust_learning_rate(optimizer, org_lr, epoch, schedule=[20, 40], decay_rate=0.1): """Decay the learning rate based on schedule""" lr = org_lr for milestone in schedule: lr *= decay_rate if epoch >= milestone else 1. print("---> learning rate is set to {}".format(lr)) for param_group in optimizer.p...
3,156
def cpu_usage(self, max_cpu_percentage=80): """Limit max cpu usage """ if psutil.cpu_percent() < max_cpu_percentage: hevlog.logging.debug('[cpu usage] {}%'.format(psutil.cpu_percent())) return True else: hevlog.logging.debug('[cpu usage] {}%'.format(psutil.cpu_percent())) ...
3,157
def search_fromCSV(Data,holy_array, bookmark = 0): """ holy array: array of words that is going to be compared with Twitter's text data """ print("Initializing crawler") WINDOW_SIZE = "1920,1080" chrome_options = Options() chrome_options.add_argument("--headless") chrome_option...
3,158
def iscircular(linked_list): """ Determine whether the Linked List is circular or not Args: linked_list(obj): Linked List to be checked Returns: bool: Return True if the linked list is circular, return False otherwise """ slow_runner = linked_list.head fast_runner = linked_lis...
3,159
def show_board(grid): """ Prints the whole board. Joins rows together with dashed lines before printing. """ bar = ["-" * (len(grid) * 4 - 1)] board = concat(interleave(bar, [show_row(row) for row in grid])) print("\n".join(board))
3,160
def shape_extent_to_header(shape, extent, nan_value=-9999): """ Create a header dict with shape and extent of an array """ ncols = shape[1] nrows = shape[0] xllcorner = extent[0] yllcorner = extent[2] cellsize_x = (extent[1]-extent[0])/ncols cellsize_y = (extent[3]-extent[2])/nrows i...
3,161
def build_encoder(opt, embeddings): """ Various encoder dispatcher function. Args: opt: the option in current environment. embeddings (Embeddings): vocab embeddings for this encoder. """ if opt.encoder_type == "transformer": return TransformerEncoder(opt.enc_layers, opt.rnn_...
3,162
def load_rendered_images_object_type(resources_path, n_channels, mode="render"): """ Import images from the resources dir with certain number of channels :param resources_path: Dir path from were images are fetched :param n_channels: Number of colors for the images :return: """ path_list = l...
3,163
def efficientnet_b3b(in_size=(300, 300), **kwargs): """ EfficientNet-B3-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (300, 300) ...
3,164
def logged(class_): """Class-level decorator to insert logging. This assures that a class has a ``.log`` member. :: @logged class Something: def __init__(self, args): self.log(f"init with {args}") """ class_.log= logging.getLogger(class_.__q...
3,165
def makeDBTable (filepath, title, fields, values, kvpairs=None): """Create a spreadsheet containing the supplied data, rather as it would be stored in a database table. However, there is also a title line and there can be key-value lines at the head of the table, before the line with the field names. ...
3,166
def TableInFirstNSStart(builder): """This method is deprecated. Please switch to Start.""" return Start(builder)
3,167
def dicom_to_nifti(dicom_input, output_file=None): """ This is the main dicom to nifti conversion function for ge images. As input ge images are required. It will then determine the type of images and do the correct conversion :param output_file: filepath to the output nifti :param dicom_input: dir...
3,168
def testd3(): """Test method""" primitives = get_d3m_primitives() planner = LevelOnePlannerOld(primitives=primitives) pipelines = planner.generate_pipelines(20) for pipeline in pipelines: print(pipeline)
3,169
def remove_php_pool(domain): """This function removes the php pool of the domain""" filename = '/etc/php/7.0/fpm/pool.d/'+domain+'.conf' if os.path.isfile(filename): os.unlink(filename)
3,170
def lot_vectors_dense_internal( sample_vectors, sample_distributions, reference_vectors, reference_distribution, metric=cosine, max_distribution_size=256, chunk_size=256, spherical_vectors=True, ): """Efficiently compute linear optimal transport vectors for a block of data provid...
3,171
def _make_message(request, level, msg): """ Just add the message once """ if msg not in [m.message for m in get_messages(request)]: messages.add_message(request, level, msg)
3,172
def load( filename, rsc_file=None, rows=None, cols=None, band=1, **kwargs, ): """Load a file, either using numpy or rasterio""" if rsc_file: rsc_data = load_rsc(rsc_file) return load_stacked_img(filename, rsc_data=rsc_data, rows=rows, cols=cols) else: try: ...
3,173
def simple_scan_network(): """ Do a simple network scan, which only works if your network configuration is 192.168.1.x """ base_ip = "192.168.1." addresses = ['127.0.0.1'] for index in range(1, 255): addresses.extend([base_ip + str(index)]) return addresses
3,174
def check_valid_file_or_folder(value): """verifies filename exists and isn't a link""" if value is not None: if not os.path.isfile(value) and not os.path.isdir(value): raise argparse.ArgumentTypeError("{} does not exist or is not a file/folder.". format(va...
3,175
def fake_message_source(empty_zodb): """Fake message source to be not user dependent.""" UserSpecificRAMMessageSource = ( icemac.addressbook.browser.messages.messages .UserSpecificRAMMessageSource) with patch.object(UserSpecificRAMMessageSource, '_get_storage') as storage: storage.re...
3,176
def channel_lvlv_2jet(): """ Mostly based on table 8 of the combination paper for the uncertainties and table 9 for the event counts. """ channel = ROOT.RooStats.HistFactory.Channel( "HWWlvlv2Jet" ) container.append(channel) channel.SetData(55) background = ROOT.RooStats.HistFactory.Sample("background") backgr...
3,177
def vtkVariantStrictEquality(s1, s2): """ Check two variants for strict equality of type and value. """ s1 = vtk.vtkVariant(s1) s2 = vtk.vtkVariant(s2) t1 = s1.GetType() t2 = s2.GetType() # check based on type if t1 != t2: return False v1 = s1.IsValid() v2 = s2.IsV...
3,178
def is_network_failure(error): """Returns True when error is a network failure.""" return ((isinstance(error, RETRY_URLLIB_EXCEPTIONS) and error.code in RETRY_HTTP_CODES) or isinstance(error, RETRY_HTTPLIB_EXCEPTIONS) or isinstance(error, RETRY_SOCKET_EXCEPTIONS) or ...
3,179
def predict(model, X, threshold=0.5): """Generate NumPy output predictions on a dataset using a given model. Args: model (torch model): A Pytroch model X (dataloader): A dataframe-based gene dataset to predict on """ X_tensor, _ = convert_dataframe_to_tensor(X, []) model.eval() ...
3,180
def test_series_info(): """test generation of infos DataFrame.""" series.load_info('External_File_Info.txt') info = series.info assert round(info.at[4, 'time (unix)']) == 1599832405
3,181
def view_mphn_pkl(infile, N=10, viruses=False): """ Reading in metaphlan database pkl file and printing # Sequence formatting: (NCBI_taxid)(UniRef90_cluster)(CDS_name) # Note that the UniRef90 clusterID does NOT include "Uniref90_" """ logging.info('Reading in: {}'.format(infile)) db = pic...
3,182
def color_image( img: np.ndarray, unique_colors=True, threshold=100, approximation_accuracy=150 ) -> np.ndarray: """ This function detects simple shapes in the image and colors them. Detected figures will be also subscribed in the final image. The function can detect triangles, quadrilateral, and c...
3,183
def restore_model(pb_path): """Restore the latest model from the given path.""" subdirs = [x for x in Path(pb_path).iterdir() if x.is_dir() and 'temp' not in str(x)] latest_model = str(sorted(subdirs)[-1]) predict_fn = predictor.from_saved_model(latest_model) return predict_fn
3,184
def _generate_resolution_shells(low, high): """Generate 9 evenly spaced in reciprocal space resolution shells from low to high resolution, e.g. in 1/d^2.""" dmin = (1.0 / high) * (1.0 / high) dmax = (1.0 / low) * (1.0 / low) diff = (dmin - dmax) / 8.0 shells = [1.0 / math.sqrt(dmax)] for ...
3,185
def add_ports_from_markers_square( component: Component, pin_layer: Layer = (69, 0), port_layer: Optional[Layer] = None, orientation: Optional[int] = 90, min_pin_area_um2: float = 0, max_pin_area_um2: float = 150 * 150, pin_extra_width: float = 0.0, port_names: Optional[Tuple[str, ...]] ...
3,186
def P(Document, *fields, **kw): """Generate a MongoDB projection dictionary using the Django ORM style.""" __always__ = kw.pop('__always__', set()) projected = set() omitted = set() for field in fields: if field[0] in ('-', '!'): omitted.add(field[1:]) elif field[0] == '+': projected.add(field[1:]) ...
3,187
def test_decision_tree(): """Check the interface to the Decisiontree class.""" model = "decision_tree" run_test(model) run_prediction(model)
3,188
def generate_txt(url, split_, number=None, version="3.0.0"): """ generate txt file of cnn_dailymail dataset Args: url (str): directory of dataset txt file. split_ (str): test or train. number (int): top-n number of samples from dataset version (str): "3.0.0" by default ...
3,189
async def new_scope( *, deadline: Optional[float] = None, timeout: Optional[float] = None ) -> AsyncIterator["Scope"]: """Creates a scope in which asynchronous tasks can be launched. This is inspired by the concept of "nurseries" in trio: https://trio.readthedocs.io/en/latest/reference-core.html#n...
3,190
def get_page_url(skin_name, page_mappings, page_id): """ Returns the page_url for the given page_id and skin_name """ fallback = '/' if page_id is not None: return page_mappings[page_id].get('path', '/') return fallback
3,191
def get_paragraph_head(source, maxlength, bullet_num=-1, bullet=False): """Return the paragraph text of specific length, optionally prefix a bullet. Args: source(str, PreProcessed, etree._Element) maxlength(int) Kwargs: bullet(bool): False by default, otherwise prefix paragraph text...
3,192
def manual_edit(filepath, xy, find = (0,0,0)): """ Offers a manual method through which sections of input images can be silenced. Parameters ---------- filepath : string A filepath for images to be selected from. Must be a path to a file, not a directory or other ``glob`` parseable stru...
3,193
def create_form(erroneous_form=None): """Show a form to create a guest server.""" party_id = _get_current_party_id_or_404() setting = guest_server_service.get_setting_for_party(party_id) form = erroneous_form if erroneous_form else CreateForm() return { 'form': form, 'domain': set...
3,194
async def record_responses(cassette, vcr_request, response): """Because aiohttp follows redirects by default, we must support them by default. This method is used to write individual request-response chains that were implicitly followed to get to the final destination. """ for i, past_response ...
3,195
def apply(task, args, kwargs, **options): """Apply the task locally. This will block until the task completes, and returns a :class:`celery.result.EagerResult` instance. """ args = args or [] kwargs = kwargs or {} task_id = options.get("task_id", gen_unique_id()) retries = options.get(...
3,196
def exp_post_expansion_function(expansion: Expansion) -> Optional[Callable]: """Return the specified post-expansion function, or None if unspecified""" return exp_opt(expansion, 'post')
3,197
def test_allclose_perm(_): """Test allclose_perm accurately detected permutation""" one, two = np.random.random((2, 10, 4)) three = one.copy() np.random.shuffle(three) assert utils.allclose_perm(one, three) assert not utils.allclose_perm(one, two)
3,198
def return_(x): """Implement `return_`.""" return x
3,199