content
stringlengths
22
815k
id
int64
0
4.91M
def range_ngram_distrib(text, n, top_most=-1): """ List n-grams with theis probabilities from the most popular to the smaller ones :param text: text :param n: n of n-gram :param top_most: count of most popular n-grams to be returned, or -1 to return all :return: list of ngrams, list of probs ...
26,100
def extract_group_ids(caps_directory): """Extract list of group IDs (e.g. ['group-AD', 'group-HC']) based on `caps_directory`/groups folder.""" import os try: group_ids = os.listdir(os.path.join(caps_directory, "groups")) except FileNotFoundError: group_ids = [""] return group_ids
26,101
def process_dataset(rcp, var, model, year, target_bucket): """ Download a NetCDF file from s3, extract and convert its contents to json, and upload the json to a target bucket. """ s3path = generate_s3_path(rcp, var, model, year) (s3key, path) = read_from_s3(s3path) s3basename = os.path.spli...
26,102
def require_methods(*methods): """Returns a decorator which produces an error unless request.method is one of |methods|. """ def decorator(func): @functools.wraps(func) def wrapped(request, *args, **kwds): if request.method not in methods: allowed = ', '.join(methods) rsp = HttpTex...
26,103
def getUnit3d(prompt, default=None): """ Read a Unit3d for the termial with checking. This will accapt and directon in any format accepted by Unit3d().parseAngle() Allowed formats * x,y,z or [x,y,z] three floats * theta,psi or [theta,psi], in radians (quoted in "" for degrees) * theta in...
26,104
def checkOverlap(ra, rb): """ check the overlap of two anchors,ra=[chr,left_start,left_end,chr,right_start,right_end] """ if checkOneEndOverlap(ra[1], ra[2], rb[1], rb[2]) and checkOneEndOverlap( ra[4], ra[5], rb[4], rb[5]): return True return False
26,105
def test_memoryview_supports_deepcopy(valid_bytes_128): """ Assert that instances of :class:`~ulid.ulid.MemoryView` can be copied using :func:`~copy.deepcopy`. """ mv = ulid.MemoryView(valid_bytes_128) data = dict(a=dict(b=dict(c=mv))) copied = copy.deepcopy(data) assert copied == data
26,106
def saveable(item: praw.models.reddit.base.RedditBase) -> dict[str, typing.Any]: """Generate a saveable dict from an instance""" result = {k: legalize(v) for k, v in item.__dict__.items() if not k.startswith("_")} return _parent_ids_interpreted(result)
26,107
def decode_Tex_accents(in_str): """Converts a string containing LaTex accents (i.e. "{\\`{O}}") to ASCII (i.e. "O"). Useful for correcting author names when bib entries were queried from web via doi :param in_str: input str to decode :type in_str: str :return: corrected string :rtype: str ...
26,108
def tensor_dict_eq(dict1: Mapping, dict2: Mapping) -> bool: """Checks the equivalence between 2 dictionaries, that can contain torch Tensors as value. The dictionary can be nested with other dictionaries or lists, they will be checked recursively. :param dict1: Dictionary to compare. :param dict2: Dict...
26,109
def calculate_stability(derivatives): """ Calculate the stability-axis derivatives with the body-axis derivatives. """ d = derivatives if 'stability' not in d: d['stability'] = {} slat = calculate_stability_lateral(d['body'], np.deg2rad(d['alpha0'])) slong = calculate_stability_longi...
26,110
def main(infile): """Main code block""" # variables n = 0 i = 0 sd = 0 seq = '' # open file f = open(infile, 'r') # interate through file line by line for line in f: if (re.match('>',line)): # count the number of fasta entries n = n...
26,111
def apply_config(keys, options, path=None): # type: (Any, optparse.Values, Optional[str]) -> Dict[str, str] """ Read setup.cfg from path or current working directory and apply it to the parsed options Parameters ---------- keys options : optparse.Values parsed options path :...
26,112
def func_call_compile(): # function: Compile the generated LaTeX file. """Compile the generated LaTeX file.""" print("-" * 80) print("* Info: Compilation") for e in [".aux", ".idx", ".ind", ".log", ".ilg", ".pdf", ".out"]: remove_LaTeX_file...
26,113
def convert_v1_to_v2(v1, max, asm, v2=None, first=0): """Converts a given v1 timecodes file to v2 timecodes. Original idea from tritical's tcConv. """ ts = fn1 = fn2 = last = 0 asm = correct_to_ntsc(asm, True) o = [] ap = o.append en = str.encode for line in v1: ovr...
26,114
def read_malmipsdetect(file_detect): """ This function is used to read the MALMI detection file which contains detection information, that is for each detected event how many stations are triggered, how many phases are triggered. Those information can be used for quality control. Parameters ---...
26,115
def GeneratePermissionUrl(client_id, scope='https://mail.google.com/'): """Generates the URL for authorizing access. This uses the "OAuth2 for Installed Applications" flow described at https://developers.google.com/accounts/docs/OAuth2InstalledApp Args: client_id: Client ID obtained by registe...
26,116
def download(request): """Download images as .zip file. """ def make_archive(source, destination): print(source, destination) base = os.path.basename(destination) name = base.split('.')[0] format = base.split('.')[1] archive_from = os.path.dirname(source) ar...
26,117
def get_scorekeeper_details(): """Retrieve a list of scorekeeper and their corresponding appearances""" return scorekeepers.get_scorekeeper_details(database_connection)
26,118
def audio_from_video(src_video: str, dst_audio: str): """Pull audio from source mp4 to destination wav. to compress the audio into mp3 add the "-map 0:a" before the destination file name. The Args: src_video (str): Path to src video dst_audio (str): Path to dst audio """ ensure...
26,119
def _process_seq(seq, strict): """Adds info to seq, and to Aligned object if seq is hidden.""" if hasattr(seq, 'data'): real_seq = seq.data else: real_seq = seq if seq.Info and 'Name' in seq.Info: seq.Name = seq.Info.Name if seq is not real_seq: real_seq.Name = seq.N...
26,120
def layer_norm(input_tensor, axis): """Run layer normalization on the axis dimension of the tensor.""" layer_norma = tf.keras.layers.LayerNormalization(axis = axis) return layer_norma(input_tensor)
26,121
def compute_depth(disparity, focal_length, distance_between_cameras): """ Computes depth in meters Input: -Disparity in pixels -Focal Length in pixels -Distance between cameras in meters Output: -Depth in meters """ with np.errstate(divide='ignore'): #ignore division by 0 ...
26,122
def lecture(source=None,target=None,fseed=100,fpercent=100): """ Create conversion of the source file and the target file Shuffle method is used, base on the seed (default 100) """ seed(fseed) try: copysource = [] copytarget = [] if(source!=None and target!=None)...
26,123
def getScale(im, scale, max_scale=None): """ 获得图片的放缩比例 :param im: :param scale: :param max_scale: :return: """ f = float(scale) / min(im.shape[0], im.shape[1]) if max_scale != None and f * max(im.shape[0], im.shape[1]) > max_scale: f = float(max_scale) / max(im.shape[0], im.s...
26,124
def load_swc(path): """Load swc morphology from file Used for sKCSD Parameters ---------- path : str Returns ------- morphology : np.array """ morphology = np.loadtxt(path) return morphology
26,125
def getFileName(in_path, with_extension=False): """Return the file name with the file extension appended. Args: in_path (str): the file path to extract the filename from. with_extension=False (Bool): flag denoting whether to return the filename with or without the extension. Re...
26,126
def post_space_message(space_name, message): """ This function will post the {message} to the Webex Teams space with the {space_name} Call to function get_space_id(space_name) to find the space_id Followed by API call /messages :param space_name: the Webex Teams space name :param message: the te...
26,127
def generate_simple_csv(user_dict, outfile=None, limit=0.0, month=None, year=None): """ output account-based spends to a CSV. can create a new file, or append to an existing one. the CSV header is defined in CSV_HEADER and can be used to customize the field names you want to output. ...
26,128
def quintic_extrap((y1,y2,y3,y4,y5,y6), (x1,x2,x3,x4,x5,x6)): """ Quintic extrapolate from three x,y pairs to x = 0. y1,y2...: y values from x,y pairs. Note that these can be arrays of values. x1,x2...: x values from x,y pairs. These should be scalars. Returns extrapolated y at x=0. """ # ...
26,129
def test_handle_merge_csv(): """Tests merging CSV files algorithm""" # pylint: disable=import-outside-toplevel import workflow_docker as wd # Load the result with open(WORKFLOW_MERGECSV_RESULT, 'r', encoding='utf8') as in_file: compare_json = json.load(in_file) # Setup fields for test ...
26,130
def answer_question_interactively(question): """Returns True or False for t yes/no question to the user""" while True: answer = input(question + '? [Y or N]: ') if answer.lower() == 'y': return True elif answer.lower() == 'n': return False
26,131
def connect( instance_id, database_id, project=None, credentials=None, pool=None, user_agent=None, ): """Creates a connection to a Google Cloud Spanner database. :type instance_id: str :param instance_id: The ID of the instance to connect to. :type database_id: str :param d...
26,132
def intersect(linked_list_1: List, linked_list_2: List): """Intersection point of two linked list.""" length_diff = len(linked_list_1) - len(linked_list_2) enum1 = list(enumerate(linked_list_1)) enum2 = list(enumerate(linked_list_2)) if length_diff < 0: enum2 = _helper(length_diff=length_di...
26,133
def _enable_check(proxy, check, group, suite): """ Enable a check for a given group/suite debile-remote enable-check <check> <group> <suite> """ print(proxy.enable_check(check, group, suite))
26,134
def recognize_package_manifests(location): """ Return a list of Package objects if any package_manifests were recognized for this `location`, or None if there were no Packages found. Raises Exceptions on errors. """ if not filetype.is_file(location): return T = contenttype.get_type(loc...
26,135
def test_cleared_rat_request(test_client, test_rat_request_nonadmin,test_login_ll3,test_delete_request_db_contents): """ Clears the single rat request by Manuel (lightserv-test, a nonadmin) (with clearer='ll3') """ print('----------Setup test_cleared_request_ahoag fixture ----------') now = datetime.now() data ...
26,136
def run_pinch_and_spread(use_case): """Run script to test multi finger tap.""" def zoom(element_id): use_case.driver.execute_script( 'mobile: pinch', {'id': element_id, 'scale': '2', 'velocity': 1} ) def pinch(element_id): use_case.driver.execute_script( 'mob...
26,137
def content_loss(sharp_images, deblur_images, cont_net): """ Computes the Content Loss to compare the reconstructed (deblurred) and the original(sharp) images Takes the output feature maps of the relu4_3 layer of pretrained VGG19 to compare the content between images as proposed in : Johnson ...
26,138
def generate_cashflow_diagram( cashflows, d=None, net=False, scale=None, color=None, title=None, **kwargs): """ Generates a barplot showing cashflows over time Given a set of cashflows, produces a stacked barplot with bars at each period. The height of each bar is set by the amount of cash produced...
26,139
def test_is_unique_file_valid_in_set(pack): """ Given - pack with pack_metadata file. When - is_unique_file_valid_in_set is called Then - Ensure it is valid and no error is returned. """ pack_metadata_data = { "VMware": { "name": "VMware", ...
26,140
def is_iterable(obj): # type: (Any) -> bool """ Returns True if obj is a non-string iterable """ if is_str(obj) is True or isinstance(obj, collections.Iterable) is False: return False else: return True
26,141
def other_players(me, r): """Return a list of all players but me, in turn order starting after me""" return list(range(me+1, r.nPlayers)) + list(range(0, me))
26,142
def mock_dd_slo_history(*args, **kwargs): """Mock Datadog response for datadog.api.ServiceLevelObjective.history.""" return load_fixture('dd_slo_history.json')
26,143
def check_joints2d_visibility_torch(joints2d, img_wh): """ Checks if 2D joints are within the image dimensions. """ vis = torch.ones(joints2d.shape[:2], device=joints2d.device, dtype=torch.bool) vis[joints2d[:, :, 0] > img_wh] = 0 vis[joints2d[:, :, 1] > img_wh] = 0 vis[joints2d[:, :, 0] < 0...
26,144
def getIntervalIntersectionLength(aa, bb, wrapAt=360): """Returns the length of the intersection between two intervals.""" intersection = getIntervalIntersection(aa, bb, wrapAt=wrapAt) if intersection is False: return 0.0 else: if wrapAt is None: return (intersection[1] - i...
26,145
def test_condition_is_can_have_target_type_object(if_statement_validator): """When condition is `is` target can be object.""" test = { 'condition': 'is', 'target': {'test': 'bob'}, 'then': ['test'], } assert is_successful(if_statement_validator(test))
26,146
def test_jvp_construct_single_input_single_output_default_v_graph(): """ Features: Function jvp Description: Test jvp with Cell construct, single input, single output and default v in graph mode. Expectation: No exception. """ x = Tensor(np.array([[1, 2], [3, 4]]).astype(np.float32)) v = Ten...
26,147
def get_environment() -> Environment: """ Parses environment variables and sets their defaults if they do not exist. """ return Environment( permission_url=get_endpoint("PERMISSION"), media_url=get_endpoint("MEDIA"), datastore_reader_url=get_endpoint("DATASTORE_READER"), ...
26,148
def test_cwd_with_absolute_paths(): """ cd() should append arg if non-absolute or overwrite otherwise """ existing = '/some/existing/path' additional = 'another' absolute = '/absolute/path' with settings(cwd=existing): with cd(absolute): eq_(env.cwd, absolute) wi...
26,149
def get_kubernetes_cluster(name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetKubernetesClusterResult: """ Use this data source to access information about an existing Managed Ku...
26,150
def gene_expression_conv_base(): """Hparams for GeneExpressionConv model.""" hparams = common_hparams.basic_params1() batch_size = 10 output_length = 2048 inputs_per_output = 128 chunk_size = 4 input_length = output_length * inputs_per_output // chunk_size hparams.batch_size = input_length * batch_size...
26,151
def is_callable(type_def, allow_callable_class: bool = False) -> bool: """ Checks whether the ``type_def`` is a callable according to the following rules: 1. Functions are callable. 2. ``typing.Callable`` types are callable. 3. Generic aliases of types which are ``is_callable`` are callable. 4....
26,152
def vgg19(pretrained=False, **kwargs): """VGG 19-layer model (configuration "E") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = VGG(make_layers(cfg['E']), **kwargs) if pretrained: model.load_pretrained_model(model_zoo.load_url(model_urls['vgg19...
26,153
def get_formats(input_f, input_case="cased", is_default=True): """ Adds various abbreviation format options to the list of acceptable input forms """ multiple_formats = load_labels(input_f) additional_options = [] for x, y in multiple_formats: if input_case == "lower_cased": ...
26,154
def db_select_entry(c, bibkey): """ Select entry from database :argument c: sqlite3 cursor :returns entry_dict: dict """ fields = ['bibkey', 'author', 'genre', 'thesis', 'hypothesis', 'method', 'finding', 'comment', 'img_linkstr'] sql = "SELECT {:s} FROM note WHERE ...
26,155
def to_bytes(obj, encoding='utf-8', errors='strict'): """Makes sure that a string is a byte string. Args: obj: An object to make sure is a byte string. encoding: The encoding to use to transform from a text string to a byte string. Defaults to using 'utf-8'. errors: The error handler to use if ...
26,156
def generate_data(model, count): """ Generate random data :param model: Django model :param count: Number of objects :return: """ for i in range(count): obj = model( boolean_field=random.choice([True, False]), null_boolean_field=random.choice([True, False, Non...
26,157
def login() -> Response: """ Login to Afterglow GET|POST /auth/login - login to Afterglow; authentication required using any of the methods defined in USER_AUTH :return: empty response with "afterglow_core_access_token" cookie if successfully logged in """ # TODO Ensu...
26,158
def compact(number, strip_check_digit=True): """Convert the MEID number to the minimal (hexadecimal) representation. This strips grouping information, removes surrounding whitespace and converts to hexadecimal if needed. If the check digit is to be preserved and conversion is done a new check digit is r...
26,159
def hashtag_getter(doc: Doc) -> List[str]: """ Extract hashtags from text Args: doc (Doc): A SpaCy document Returns: List[str]: A list of hashtags Example: >>> from spacy.tokens import Doc >>> Doc.set_extension("hashtag", getter=dacy.utilities.twitter.hashtags) ...
26,160
def options(): """Stub version of the parsed command line options.""" class StubOptions(object): profile = None return StubOptions()
26,161
def get_surface(shifts, orig_text, item, text, unit_shortening=0): """ Extract surface from regex hit. """ # handle cut end span = (item.start(), item.end() - unit_shortening) logging.debug('\tInitial span: %s ("%s")', span, text[span[0]:span[1]]) real_span = (span[0] - shifts[span[0]], s...
26,162
def serve_game_states(playerIdentifier: PlayerIdentifier) -> Generator[GameStateBuffer, None, None]: """ A generator for game state :return: an iterator over game states """ with get_transactional_server_stub() as game_master_stub: game_state_iterator = game_master_stub.stream_game_state(pla...
26,163
def plot_bootstrap_delta_grp(dfboot, df, grp, force_xlim=None, title_add=''): """Plot delta between boostrap results, grouped""" count_txt_h_kws, mean_txt_kws, pest_mean_point_kws, mean_point_kws = _get_kws_styling() if dfboot[grp].dtypes != 'object': dfboot = dfboot.copy() ...
26,164
def inception_inspired_reservoir_model( input_shape: Tuple[int, int, int], reservoir_weight: np.ndarray, num_output_channels: int, seed: Optional[int] = None, num_filters: int = 32, reservoir_base: str = 'DenseReservoir', reservoir_params: Optional[Dict[str, Any]] = None, final_activatio...
26,165
def midnight(date): """Returns a copy of a date with the hour, minute, second, and millisecond fields set to zero. Args: date (Date): The starting date. Returns: Date: A new date, set to midnight of the day provided. """ return date.replace(hour=0, minute=0, second=0, microseco...
26,166
async def api_call(method, data=None): """Slack API call.""" with aiohttp.ClientSession() as session: token = os.environ.get('TOKEN') if not token.startswith('xoxb-'): return 'Define the token please' form = aiohttp.FormData(data or {}) form.add_field('token', token) ...
26,167
def main(): """ this project plays breakout """ global NUM_LIVES graphics = BreakoutGraphics() score = 0 # the score you have score2 = 0 delay = 0 # the speed you have win = 1000 # Add animation loop here! while NUM_LIVES > 0: # if your lives > 0 you die if graphic...
26,168
def foldr(fun: Callable[[Any, Any], Any], acc: Any, seq: Sequence[Any]) -> Any: """Implementation of foldr in Python3. This is an implementation of the right-handed fold function from functional programming. If the list is empty, we return the accumulator value. Otherwise, we recurse by applying t...
26,169
def packages_list(ctx, sort_by): """Display a list of all WHDLoad Packages in the iGameLister WHDLoad Package data file (packages.dat). The list of WHDLoad Packages can be sorted by the following criteria: \b id: The ID number of the WHDLoad Packages. (default) date: The release date of the WHDL...
26,170
def p_meta_description(p): """meta_description_stmt : DESCRIPTION_ID COLON MULTILINES_STRING """ p[0] = Node("description", value=p[3])
26,171
def test_simple(): """The most simple case; a single rectangle.""" B = 100 H = 20 E = 210000 sections = ((B, H, 0, E),) EI, top, bot = bm.EI(sections, E) EIc = E * B * (H ** 3) / 12 assert 0.99 < EI / EIc < 1.01 assert top == H / 2 assert bot == -H / 2
26,172
def nose(window): """ :param window:window """ nose_up = GOval(50, 20) nose_up.filled = True window.add(nose_up, x=window.width / 2-nose_up.width//2, y=245+40)
26,173
def tj_dom_dem(x): """ Real Name: b'Tj Dom Dem' Original Eqn: b'( [(1,0.08)-(365,0.09)],(1,0.08333),(2,0.08333),(3,0.08333),(4,0.08333),(5,0.08333),(6\\\\ ,0.08333),(7,0.08333),(8,0.08333),(9,0.08333),(10,0.08333),(11,0.08333),(12,0.08333\\\\ ),(13,0.08333),(14,0.08333),(15,0.08333),(16,0.08333),(17,0.08333...
26,174
def filter_chants_without_volpiano(chants, logger=None): """Exclude all chants with an empty volpiano field""" has_volpiano = chants.volpiano.isnull() == False return chants[has_volpiano]
26,175
def split_trainer_ops_pass(program, config, default_device="cpu"): """ split cpu-trainer program from origin-program 1. find heter op (located on different device) 2. find input&output of every heter-block 3. create cpu-trainer program, add send&recv op """ # Todo: support user define defau...
26,176
def get_builtin_templates_path() -> pathlib.Path: """Return the pathlib.Path to the package's builtin templates :return: template pathlib.Path """ return pathlib.Path( os.path.dirname(os.path.realpath(__file__)) ) / 'templates'
26,177
def sample_input(): """Return the puzzle input and expected result for the part 1 example problem. """ lines = split_nonblank_lines(""" position=< 9, 1> velocity=< 0, 2> position=< 7, 0> velocity=<-1, 0> position=< 3, -2> velocity=<-1, 1> position=< 6, 10> velocity=<-2, -1> position=< 2, -4> veloci...
26,178
def vector_angle(v): """Angle between v and the positive x axis. Only works with 2-D vectors. returns: angle in radians """ assert len(v) == 2 x, y = v return np.arctan2(y, x)
26,179
def get_user_record_tuple(param) -> (): """ Internal method for retrieving the user registration record from the DB. :return: """ conn = mariadb.connect(host=DB_URI, user=DB_USERNAME, password=DB_PASSWORD, database=DB_NAME) db = conn.cursor() # discord_id provided if isinstance(param, ...
26,180
def A_weighting(x, Fs): """A-weighting filter represented as polynomial transfer function. :returns: Tuple of `num` and `den`. See equation E.6 of the standard. """ f1 = _POLE_FREQUENCIES[1] f2 = _POLE_FREQUENCIES[2] f3 = _POLE_FREQUENCIES[3] f4 = _POLE_FREQUENCIES[4] offset = _NO...
26,181
def register(class_=None, **kwargs): """Registers a dataset with segment specific hyperparameters. When passing keyword arguments to `register`, they are checked to be valid keyword arguments for the registered Dataset class constructor and are saved in the registry. Registered keyword arguments can be...
26,182
def random_population(pop_size, tune_params, tuning_options, max_threads): """create a random population of pop_size unique members""" population = [] option_space = np.prod([len(v) for v in tune_params.values()]) assert pop_size < option_space while len(population) < pop_size: dna = [random...
26,183
def check_genome(genome): """Check if genome is a valid FASTA file or genomepy genome genome. Parameters ---------- genome : str Genome name or file to check. Returns ------- is_genome : bool """ try: Genome(genome) return True except Exception: ...
26,184
def test_hbase_get_empty_key_to_error(sdc_builder, sdc_executor, cluster): """Check record is sent to error when there is no key in the record and ignore row missing field is set to false dev_raw_data_source >> hbase_lookup >> wiretap """ data = {'columnField': 'cf1:column'} json_data = json.dumps(...
26,185
def prepare(hass): """ Prepares the loading of components. """ # Load the built-in components import homeassistant.components as components AVAILABLE_COMPONENTS.clear() AVAILABLE_COMPONENTS.extend( item[1] for item in pkgutil.iter_modules(components.__path__, 'homeassistant.compone...
26,186
def extract_row_loaded(): """extract_row as it should appear in memory""" result = {} result['classification_id'] = '91178981' result['user_name'] = 'MikeWalmsley' result['user_id'] = '290475' result['user_ip'] = '2c61707e96c97a759840' result['workflow_id'] = '6122' result['workflow_name...
26,187
def getb_reginsn(*args): """ getb_reginsn(ins) -> minsn_t Skip assertions backward. @param ins (C++: const minsn_t *) """ return _ida_hexrays.getb_reginsn(*args)
26,188
def convolve_nk(myk, nkm, gfunc, klim, nk, kmin=0.02, kmax=1.5): """Convolve n(k) by going to J(p); apply resolution; and back. Args: myk (np.array): k nkm (np.array): n(k) gfunc (callable): resolution function klim (float): maxmimum kvalue to include in convolution nk (nk): number of points on...
26,189
def _builder_inited(app: sphinx.application.Sphinx) -> None: """Generates the rST files for API members.""" _write_member_documentation_pages( _create_documenter(env=app.env, documenter_cls=sphinx.ext.autodoc.ModuleDocumenter, name='tensorstore'))
26,190
def label_connected_components(label_images, start_label=1, is_3d=False): """Label connected components in a label image. Create new label images where labels are changed so that each \ connected componnent has a diffetent label. \ To find the connected components, it is used a 8-neighborhood. Par...
26,191
def passed_hardfailure_detector(elb_data): """ Checks for hard failures """ if debug: logger.debug("Checking hard failure detector") # 1. Verify the Classic Load Balancer does not have HTTP, HTTPS or SSL # listeners for listener in elb_data['LoadBalancerDescriptions'][0]['ListenerDe...
26,192
def setup_pgbackup(): """ Copies postgresql backup script to host and adds to crontab """ sudo('mkdir -p /backups/postgres') sudo('chown -R postgres:postgres /backups') put('etc/pgbkup.sh', '/backups/postgres', use_sudo=True) sudo('chmod +x /backups/postgres/pgbkup.sh') sudo('echo "0 3 *...
26,193
def _watchdog(): """ Thread worker to maintain nornir proxy process and it's children liveability. """ child_processes = {} while nornir_data["initialized"]: nornir_data["stats"]["watchdog_runs"] += 1 # run FD limit checks try: if HAS_RESOURCE_LIB: ...
26,194
def load(name, data_dir='data'): """ Opens a saved `.npz` file containing 'dm' and 'z' arrays. Parameters ---------- name : str The name of the file to load. data_dir : str, optional The directory containing the data. The whole path must be specified except if :attr:`da...
26,195
def save_changes(_id, data): """commit the candidate details to the database Args: _id (integer): office id from the endpoint url data ([object]): candidate instance """ query, values = Candidate.add_candidate(data, office_id=_id) db().commit_changes(query, values)
26,196
def set_user_agent(user_agent: str, ini_path: str = None) -> None: """设置user agent \n :param user_agent: user agent文本 :param ini_path: 要修改的ini文件路径 :return: None """ set_argument('user-agent', user_agent, ini_path)
26,197
def metadataAbstractElementEmptyValuesTest1(): """ No empty values. >>> doctestMetadataAbstractElementFunction( ... testMetadataAbstractElementEmptyValue, ... metadataAbstractElementEmptyValuesTest1(), ... requiredAttributes=["required1"], ... optionalAttributes=["optional1"...
26,198
def test_get_missing_resource(app): """If we GET a resource with an ID that doesn't exist, do we get a 404?""" with app.test_client() as client: response = client.get('/machine/31337') assert response.status_code == 404
26,199