content
stringlengths
22
815k
id
int64
0
4.91M
def videopost(request): """Renders the about page.""" assert isinstance(request, HttpRequest) return render( request, 'app/videopost.html', { 'title':'О Нас', 'message':'Сведения о нашей компании', 'year':datetime.now().year, } )
5,287,600
def save_thunder(obj, path, filename='thunder.d'): """ save a thunder object to a path using the dill package :param obj: :param path: :param filename: :return: """ logging.debug(f'saving using dill {filename}') d_dump(obj, open(abspath(join(path, filename)), 'wb'))
5,287,601
def generic_5v5_log_graph_title(figtype, **kwargs): """ Generates a figure title incorporating parameters from kwargs: [Fig type] for [player, or multiple players, or team] [date range] [rolling window, if applicable] [TOI range, if applicable] [TOI60 range, if applicable] Methods for ...
5,287,602
def test_yamlrepresenter_dumps(temp_file_creator): """Yaml Representer dumps.""" payload = { 'key1': 'value1', 'key2': 'value2', 'key3': [0, 1, 2] } representer = filesystem.YamlRepresenter() file_path = temp_file_creator() with open(file_path, 'w') as file: repre...
5,287,603
def _move_official_local_data(): """move "official" archives folder to the generic standardized location once and for all""" src = os.path.join(cocopp_home, 'data-archive') dest = _url_to_folder_name(coco_url) if os.path.exists(src): if not os.path.exists(os.path.join(dest, 'data-archive')): ...
5,287,604
def print_issues(issue_files): """ print a lint of all the file and issues Args: issue_files ([(file, PylintIssues)]) """ if issue_files: for (file, issues) in issue_files: print(f"File {file}: {total_issues(issues)} issues") print(f" {len(issues.e...
5,287,605
def not_in(a, b): """Evalutes a not in b""" result = False if a in b else True return result
5,287,606
def _is_list(arg): """Checks if arg is list-like. This excludes strings and dicts.""" if isinstance(arg, dict): return False if isinstance(arg, str): # Python 3-only, as str has __iter__ return False return (not _has_method(arg, "strip") and _has_method(arg, "__getitem__") ...
5,287,607
def calculate_ssd(desc1: list, desc2: list) -> float: """ This function is responsible of: - Calculating the Sum Square Distance between two feature vectors. - Matching a feature in the first image with the closest feature in the second image. Note: - Multiple features from the firs...
5,287,608
def encode_imsi(imsi): """ Convert a IMSI string to a uint + length. IMSI strings can contain two prefix zeros for test MCC and maximum fifteen digits. Bit 1 of the compacted uint is always 1, so that we can match on it set. Bits 2-3 the compacted uint contain how many leading 0's are in the IMSI. F...
5,287,609
def find_by_type_or_id(type_or_id, prs): """ :param type_or_id: Type of the data to process or ID of the processor class :param prs: A list of :class:`anyconfig.models.processor.Processor` classes :return: A list of processor classes to process files of given data type or processor 'type...
5,287,610
def registerNormalPackages( sitPath, dryRun=False ): """ Searches the SIT for RTMaps packages and invokes registerHondaPackage() for each of them. """ Any.requireIsDir( sitPath ) Any.requireIsBool( dryRun ) sitProxyPath = SIT.getPath() ProxyDir.requireIsProxyDir( sitProxyPath ) ...
5,287,611
def test_install_assistive_error(): """ Test installing a bundle ID as being allowed to run with assistive access """ mock_ret = MagicMock(return_value={"retcode": 1}) with patch.dict(assistive.__salt__, {"cmd.run_all": mock_ret}): with patch.dict(assistive.__grains__, {"osrelease": "10.11.3...
5,287,612
def parse_content(content): """Parse the content of a file into a dictionary mapping words to word""" words = {} for line in content.split('\n'): word, frequency = line.split() words[word] = int(frequency) return words
5,287,613
def list_resources(resourceOwner=None, principal=None, resourceType=None, resourceArns=None, resourceShareArns=None, nextToken=None, maxResults=None): """ Lists the resources that you added to a resource shares or the resources that are shared with you. See also: AWS API Documentation Exceptions ...
5,287,614
def log(output,level=LogLevel.INFO): """ Log message. :param output: message :param level: LogLevel """ sys.stderr.write(level) sys.stderr.write(str(output)) sys.stderr.write(LogLevel.ENDC) sys.stderr.write("\n") sys.stderr.flush()
5,287,615
def test_dict1_with_missing_version_attribute_is_not_valid(): """require the version attribute to have starting value""" setup_dict = setup() amidict = AMIDict.create_dict_from_path(Path(setup_dict[DICTFILE1])) version = amidict.get_version() assert version == STARTING_VERSION
5,287,616
def start_engine(data): """ Start the tk-desktop engine given a data dictionary like the one passed to the launch_python hook. """ engine = Bootstrap(data).start_engine() # Import Toolkit locally. We need to capture this Python path so we can use it to bootstrap. # inside another process. ...
5,287,617
def extract_frequency(im, pixel_value = 255): """ Extract frequency of non-zero entries across bands for each pixel. NOTE: The result is indexed from one rather than zero, to distinguish a signal from the case where all bands are zero. A frequency of 1 indicates one count from across all bands ...
5,287,618
def NaiveBayesSmsSpamCollection(): """Apply Naive Bayes to SMS Spam Collection """ def convert(x): ret = [] for i in x: ret.append(1) if i == 'spam' else ret.append(0) return ret df = read_lines_and_convert_to_df('SMSSpamCollection/SMSSpamCollection') #df = read...
5,287,619
def EffectiveProxyInfo(): """Returns ProxyInfo effective in gcloud and if it is from gloud properties. Returns: A tuple of two elements in which the first element is an httplib2.ProxyInfo object and the second is a bool that is True if the proxy info came from previously set Cloud SDK proxy propert...
5,287,620
def reply(threaded=False): """Plugin reply decorator.""" def wrapper(func): func._is_reply = True func._is_threaded = threaded return func return wrapper
5,287,621
def PAvgArr (in1, in2, out): """ Average nonblanked elements of two arrays. out = (in1 + in2)/2 or whichever is not blanked * in1 = first input Python FArray * in2 = second input Python FArray * out = output Python FArray """ ################################################################ # Checks ...
5,287,622
def create_mask_from_vector(vector_data_path, cols, rows, geo_transform, projection, target_value=1): """Rasterize the given vector (wrapper for gdal.RasterizeLayer).""" data_source = gdal.OpenEx(vector_data_path, gdal.OF_VECTOR) layer = data_source.GetLayer(0) driver = gdal....
5,287,623
def egcd(a: int, b: int) -> Tuple[int, int, int]: """Euler's extended algorithm for GCD""" if a == 0: return b, 0, 1 else: g, y, x = egcd(b % a, a) return g, x - (b // a) * y, y
5,287,624
def test_list(): """ Given a list of points, parse_parameters should return the same list. """ assert parse_parameters(mylist) == mylist
5,287,625
def json2py(json_obj): """ Converts the inputted JSON object to a python value. :param json_obj | <variant> """ for key, value in json_obj.items(): if type(value) not in (str, unicode): continue # restore a datetime if re.match('^\d{4}-\d{2}-\d{2} \d{2}...
5,287,626
def load_epoch_as_lists(session_name, epoch, trialtypes=None, SNRthresh=0, verbose=False): """ Load SUA spike trains of specific session and epoch from Lilou's data. * The output is a dictionary, with SUA ids as keys. * Each SUA id is associated to a list of spike trains, one pe...
5,287,627
def generate_fixed_permutations( base_name: str, locations: typing.List[str], perm_length: int, ) -> typing.List[typing.List[str]]: """ Generate path permutations of a specified length which always start and end at base_name. :param base_name: Name of base to begin from. :param l...
5,287,628
def scorer_from_spec(language, approach): """Create scorer from language and approach. Args: language (str): Name of language to use. approach (str): Approach to use. Returns: An instance of :class:`subsclu.scorers.base.Scorer`. """ logger.info("creating scorer from spec w...
5,287,629
def parse_managed_variant_lines(csv_lines): """Parse managed variant csv lines into managed variant info dicts. Shares implementation structure with panel csv parsing. Could be generalised. Args: csv_lines(iterable(str)) Returns: list(managed_variant_info(dict)): A list of variant i...
5,287,630
def cleanEngText(eng_raw_string, customize_stop_words=[]): """ Args: eng_raw_string: str - customize_stop_words: list - all stopwords to remove Returns: refined_doc: str - curated string of eng text """ # Remove dates # 1 or 2 digit number followed by back slash follow...
5,287,631
def insertKeyframe(curves, time): """ Insert a keyframe on the given curves at the given time. :type curves: list[str] :type time: (int, int) """ startTime, endTime = time for curve in curves: insertStaticKeyframe(curve, time) firstFrame = maya.cmds.findKeyframe(curves, time=(...
5,287,632
def get_experiment(flags): """ Get experiments class from dir_data flag. """ if flags.dataset == 'celeba': return CelebaExperiment(flags) if Path(flags.dir_data).name in ['PolyMNIST', 'polymnist']: return PolymnistExperiment(flags) elif Path(flags.dir_data).name.startswith('mimic...
5,287,633
def PydroVersionType(): """ Return "Developer" or "Release" to indicate if the repository is from trunk or tag """ install_type = "Developer" if PydroVersionIsDev() else "Release" return install_type
5,287,634
def dlqr(a, b, q, r, gamma=None): """Solve the discrete time lqr controller. x[k+1] = a @ x[k] + b @ u[k] with instantaneous cost x[k].T @ q @ x[k] + u[k].T @ r @ u[k] Parameters ---------- a: state transition matrix. b: input matrix. q: state cost matrix (semi-positive definite)....
5,287,635
def sqrt(a): """square root of a"""
5,287,636
def run_dmc(task: tasks.Task, seed: int, num_samples: int, batch_size: Optional[int] = None, logger: Optional[logger_lib.Logger] = None): """Run the Direct Monte Carlo (DMC) baseline. Args: task: `Task` for performing probabilistic program analysis. seed: ran...
5,287,637
def md5(p: typing.Union[pathlib.Path, str], bufsize: int = 32768) -> str: """ Compute md5 sum of the content of a file. """ hash_md5 = hashlib.md5() with Path(p).open('rb') as fp: for chunk in iter(lambda: fp.read(bufsize), b''): hash_md5.update(chunk) return hash_md5.hexdige...
5,287,638
def pck_coverage(path, date_format="infomod2", system="UTC"): """Returns the coverage of a PCK file. The function assumes that the appropriate kernels have already been loaded. :param path: File path :type path: str :param date_format: Date format, the default is the one pr...
5,287,639
def cv(temp,dflu,chkbnd=False): """Calculate fluid water isochoric heat capacity. Calculate the isochoric (constant volume) heat capacity of fluid water from temperature and fluid density. :arg float temp: Temperature in K. :arg float dflu: Fluid water density in kg/m3. :arg bool chkbn...
5,287,640
def load_dict_genomic_annotations(parameters, cell_line): """ Function loads dict of lists indicating the number of annotations of specific genomic annotations in each genomic bin for each chromsome. :param parameters: dictionary with parameters set in parameters.json file :param cell_line: Cell li...
5,287,641
def get_authorize_url(client_id, client_secret, redirect_uri, scope): """ Get a spotify oauth authorization url. Redirect user here and read response at redirect_uri. """ auth = ExtendedOAuth( client_id, client_secret, redirect_uri, scope=scope) auth_url = auth.get_authorize_url() ...
5,287,642
def book_genres(book_info: tuple) -> set: """ Returns the genres of the book by its title and writer. >>> book_genres(('Through the looking-glass. Sambahsa', 'Lewis Carroll')) \ == {"Children's fiction", 'Fantasy'} True >>> book_genres(('Through the looking-glass', 'Lewis Carroll')) == {'Illus...
5,287,643
def food(request): """ Food view Displays the database of food items. """ foods = Food.objects.all() context = { 'foods': foods, 'foods_total_count': len(foods), } return render(request, 'tracker_app/food.html', context=context)
5,287,644
def test_callback_compiling_args_or_kwargs(): """Test compiling callbacks with routed positional (args) or keyword (kwargs) arguments. """ def get_clf() -> keras.Model: model = keras.models.Sequential() model.add(keras.layers.InputLayer((1,))) model.add(keras.layers.Dense(1, activat...
5,287,645
def myexecute(inputs_cfg): """ Primary function that handles fake signal injection. Parameters ---------- inputs_cfg : str configuration script of inputs """ # Profile code execution. prog_start_time = time.time() # Read inputs from config file and set default parameter va...
5,287,646
def get_file_mod_time(pth): """ Safely get last modification time for a file. Prevents situation when file is deleted between file existence check and last file modification check. :param str pth: file path to check :return float: number of seconds since Jan 1, 1970 00:00:00 """ try: ...
5,287,647
def csv_to_json(label_array, image_dir, label_json_dir, coord_type="xmin_ymin_w_h", store_score=False): """ Convert csv format to labelme json format. Args: label_array (list[list] or np.ndarray): annotations in [[file_name, error_type, xmin, ymin, xmax, ymax, score], ...] format. ...
5,287,648
def sync_bucket(bucket_name: str, static_dir: str) -> None: # pragma: no cover """ Sync a bucket with a local static file directory. """ storage = S3Storage(bucket_name=bucket_name, static_dir=static_dir) storage.sync()
5,287,649
def auth_user(self): """ Authenticates visitor as logged-in user, returns data about user :param self: :return: {'authorized', 'user_id', 'penname'} or {'authorized: false'} """ try: user_hash = self.request.cookies.get('user-id', 'None') except AttributeError: user_hash = ...
5,287,650
def convert_linear_parameters(parameters: ndarray) -> ndarray: """ Convert all A1, A2 parameters of sum of sines function to amplitudes and phases. For more info see approximate_sines_sum function. Parameters ---------- parameters : ndarray An array with all parameters of sum of sines fu...
5,287,651
def get_int(name, default): """ Get an environment variable as an int. Args: name (str): An environment variable name default (int): The default value to use if the environment variable doesn't exist. Returns: int: The environment variable value parsed as an int ...
5,287,652
def mock_is_file_false(monkeypatch): """Confirm file does not exist.""" mock_is_file = mock.Mock() mock_is_file.return_value = False monkeypatch.setattr("version_hunter.versioner.os.path.isfile", mock_is_file)
5,287,653
def parse_sml(response): """Parse the json for a SML Hue motion sensor and return the data.""" if response.type == "ZLLLightLevel": lightlevel = response.state['lightlevel'] if lightlevel is not None: lux = round(float(10**((lightlevel-1)/10000)), 2) dark = response.state...
5,287,654
def init_config(): """ Loads the configuration from the json file under /conf and saves it under utils.CONF :returns: None :rtype: None """ global CONF pth = path.dirname(path.abspath(__file__)) pth = path.split(pth)[0] fpth = path.join(pth, 'conf/config.json') with ...
5,287,655
def printProgressBar (iteration, total, prefix = 'Progress:', suffix = 'Complete', decimals = 1, length = 50, fill = '▒', printEnd = "\r"): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations...
5,287,656
def setup_process(opts, rank, world_size, master_port, backend='gloo'): """ Initialize the distributed environment (for each process). gloo: is a collective communications library (https://github.com/facebookincubator/gloo). My understanding is that it's a library/API for process to communicate/coordin...
5,287,657
async def test_diagnostics( hass: HomeAssistant, hass_client: ClientSession, ) -> None: """Test diagnostic information.""" config_entry = await setup_version_integration(hass) diagnostics = await get_diagnostics_for_config_entry( hass, hass_client, config_entry ) assert diagnostics[...
5,287,658
def fetch_typeform(typeform_creds, last_successful_runtime): """Fetches data from Typeform.""" logging.info('Fetching data from Typeform') header_dict = {'Authorization': 'Bearer {token}'.format(token=typeform_creds['typeform_api_key']), # noqa: E501 } params = {} if last_succes...
5,287,659
def lematize(words): """Lematizes words (need to be preprocessed first) Parameters ---------- words : list of str Returns ------- list of str """ lemmatizer = WordNetLemmatizer() doc = [lemmatizer.lemmatize(x[0], wordnet_tags(x[1])) for x in pos_tag(words)] return ' '.join(...
5,287,660
def resize_image_with_padding(img_bgr, desired_size=224): """ padding resize 方法 """ import cv2 old_size = img_bgr.shape[:2] # old_size is in (height, width) format ratio = float(desired_size) / max(old_size) new_size = tuple([int(x * ratio) for x in old_size]) # new_size should be in...
5,287,661
def setup_logging(): """ setup the logging system """ base_log = logging.getLogger() handler = logging.StreamHandler(sys.stdout) handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s")) base_log.addHandler(handler) base_log.setLevel(logging....
5,287,662
def load_module(name): """load a module Args: name: python dotted namespace path of the module to import Returns: imported module Raises: FailedImport if importing fails """ m = __import__(name) # __import__('foo.bar') returns foo, so... for bit in name.split('.')[1:]: m = getattr(m, ...
5,287,663
def make_predictions_dominant_v2( damage_probs: np.ndarray, min_size=32, assign_dominant=True, max_building_area=4096, min_solidity=0.9 ): """ Combines floodfill and dominant postprocessing :param damage_probs: :param min_size: :param assign_dominant: :param max_building_area: :param min...
5,287,664
def draw_rectangle(image, corner_A, corner_B, color, thickness): """ Draws a filled rectangle from ``corner_A`` to ``corner_B``. # Arguments image: Numpy array of shape ``[H, W, 3]``. corner_A: List of length two indicating ``(y, x)`` openCV coordinates. corner_B: List of length two ind...
5,287,665
def parse(inFile): """Parse the tomtom output file Args: tomtom.txt output file Returns: A dict between motif Ids and list of matched motif Ids """ #dict between query and target Ids matchDict = {} #read the tomtom.txt file and see if any known are found with open(inFile, 'rb') as handler: for line in ha...
5,287,666
def _get_listeners(alb_id): """ """ host, port = get_etcd_addr() client = etcd.Client(host=host, port=int(port)) listeners = {} try: listeners_prefix = '/alb/{name}/listeners'.format(name=alb_id) for i in client.read(listeners_prefix).children: listener_id = i.key[1:...
5,287,667
def read_extra_stats2169(fp, fh, wl=None): """ These structures appear optionally, but always in this order. """ total_read = 0 if fh.sa_proc: c_read = 0 for i in range(fh.sa_proc): cpu_stats = StatsOneCpu2169() ret = fp.readinto(cpu_stats) check_r...
5,287,668
def project_simplex(v, z=1.0): """Project a vector v onto the simplex. That is, return argmin_w ||w - v||^2 where w >= 0 elementwise and sum(w) = z. Parameters: v: Tensor of shape (batch_size, n) z: real number Return: Projection of v on the simplex, along the last dimension: (ba...
5,287,669
def test_main_single_instance_with_other_tag_no_name_tag_stop(ec2_instance_with_tag): """ GIVEN Single instance with assigned tags other than Name tag. WHEN main() is called. THEN The stop action has been performed on given instance. """ ec2_instance_with_tag.start() main(aws_region='eu-west...
5,287,670
def uniquify(iterable): """ Make unique list while preserving order. """ unique = [] for entry in iterable: if entry not in unique: unique.append(entry) return unique
5,287,671
def test_a(): """Test reading N3 from a unicode objects as data""" g = Graph() g.parse(data=rdf, format='n3') v = g.value(subject=URIRef("http://www.test.org/#CI"), predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) assert v==u"C\u00f4te d'Ivoire"
5,287,672
def execute_paasta_cluster_boost_on_remote_master( clusters, system_paasta_config, action, pool, duration=None, override=None, boost=None, verbose=0, ): """Returns a string containing an error message if an error occurred. Otherwise returns the output of run_paasta_cluster_boost(...
5,287,673
def as_bytes(data) -> bytes: """Converts the input into bytes. Input data should be a Payload, string, bytes, dict, list, or a file-like object. Args: data: input data Returns: bytes: bytes representation of the input data """ bytes_data = None if isinstance(data, str): ...
5,287,674
def get_selection_for_new_device(selection, insert_left=False): """ Returns a device, depending on the type of object that is selected at this moment. For drum pads, it returns the last device in the pads chain. If the selected object is no device, it returns the selected deviec. """ selected = ...
5,287,675
async def updateDestinyDefinition(connection, definition_name: str, referenceId: int, **kwargs): """Insert Rows. Input vars depend on which definition is called""" insert_sql = f""" INSERT INTO {definition_name} (referenceId, {", ".join([str(x) for x in kwargs.keys()])}) ...
5,287,676
def rook_attack(board): """ Question 22.7: Given 2D array of 1s and 0s, where 0s encode positions of rooks on n x m chessboard, update array to contain 0s at all positions which can be attacked by rooks """ num_rows = len(board) num_cols = len(board[0]) first_row_attacked = False ...
5,287,677
def repr2(val, **kwargs): """ Makes a pretty and easy-to-doctest string representation! This is an alternative to repr, and `pprint.pformat` that attempts to be both more configurable and generate output that is consistent between python versions. Args: val (object): an arbitrary pytho...
5,287,678
def test_state_with_unit(hass): """Test the state_with_unit property helper.""" hass.states.async_set("sensor.test", "23", {ATTR_UNIT_OF_MEASUREMENT: "beers"}) hass.states.async_set("sensor.test2", "wow") tpl = template.Template("{{ states.sensor.test.state_with_unit }}", hass) assert tpl.async_re...
5,287,679
def exec_code(*, source=None, path=None, include=None, lang=None): """This uses check_syntax to see if the code is valid and, if so, executes it into a globals dict containing only ``{"__name__": "__main__"}``. If no ``SyntaxError`` exception is raised, this dict is returned; otherwise, an empty dic...
5,287,680
def read_config(): """Read the config file for cenv from the users-home path if it exists. If there is no user-config-file the default one is used. Returns: the content of the read config file. """ user_config_path = Path.home() / '.config/cenv/cenv.yml' default_config_path = Path(__f...
5,287,681
def test_get_zg_fix(): """Test whether the right fix gets found again, for zg as well.""" fix = Fix.get_fixes('native6', 'ERA5', 'Amon', 'zg') assert fix == [Zg(None), AllVars(None)]
5,287,682
def test_message_sending_error( config, ): """Test handling of status codes other than 200 and 302.""" with requests_mock.Mocker() as m: sms = YesssSMS.YesssSMS("0000000000", "2d4faa0ea6f55813") m.register_uri( "POST", # pylint: disable=protected-access sm...
5,287,683
def create_default_metadata() -> Dict[str, Any]: """Creates a dictionary with the default metadata.""" return { 'title': 'Default title', 'base_url': 'https://example.org', 'description': 'Default description', 'language': 'en-US', 'copyright': 'Licensed under the ' ...
5,287,684
def unpin_object_data(object_id): """Unpin an object pinned by pin_object_id. Examples: >>> x_id = f.remote() >>> pin_object_id(x_id) >>> unpin_object_id(x_id) # as if the pin didn't happen """ object_id.set_buffer_ref(None)
5,287,685
def remove_dtaf(): """ A pytest fixture that stores the collection of DataTransformerAbstractFactory names before the test is run, then deletes any DataTransformerAbstractFactory that were created for the test when the test ends. """ s_before = set(DataTransformerAbstractFactory._transformer_fac...
5,287,686
def _is_fingerprint_valid(fingerprint): """Validate that a fingerprint is in the right format""" if len(fingerprint) != 40: return False elif set(fingerprint).difference(ALLOWED_FINGERPRINT_CHARACTERS): return False else: return True
5,287,687
def exec_command(doit, logger, cmd, msg): """ Execute given command and return its output. Exit the program on failure. """ cmd = Command(cmd, logger=logger, redirect_stderr=False) if not doit: logger.info(cmd) return cmd.execute() if cmd.getstate() is not Command.FINISHE...
5,287,688
def ga_service_account_private_key()-> t.Optional[str]: """Google Service Account private_key used to download the Google Analytics Data""" return None
5,287,689
def paths_differ(path1,path2): """Check whether two paths differ.""" if os.path.isdir(path1): if not os.path.isdir(path2): return True for nm in os.listdir(path1): if paths_differ(os.path.join(path1,nm),os.path.join(path2,nm)): return True for nm i...
5,287,690
def get_doppler(csi, rate=1000): """get_doppler_spectrum Args: csi: csidata.csi[:, :, :, :1] rate: sample rate """ # Filter Configuration half_rate = rate / 2 upper_order, upper_stop = 6, 60 lower_order, lower_stop = 3, 2 lb, la = signal.butter(upper_order, upper_stop / ...
5,287,691
def print_conjunction(conjunction, nr_of_elements): """ Display the conjunction. Parameters ---------- conjunction nr_of_elements : int """ title_line = " * ||" for i in range(nr_of_elements): title_line += " " + str(i) + " |" print(title_line) print("-"*len(title_li...
5,287,692
def HideArea(start, end, description, header, footer, color): """ Hide an area Hidden areas - address ranges which can be replaced by their descriptions @param start: area start @param end: area end @param description: description to display if the area is collapsed ...
5,287,693
def var_asymmetry ( a , b , name = '' , title = '' ) : """``Asymmetry'' f(x) = (a-b)/(a+b) >>> a = ... >>> b = ... >>> e = var_asymmetry ( a , b ) """ f1 = isinstance ( v1 , num_types ) f2 = isinstance ( v2 , num_types ) if f1 and f2 : r = ( float ( v1 ) - float ( v2 ) )...
5,287,694
def test_extract_max_empty(): """ GIVEN empty heap WHEN extract_max is called THEN IndexError is raised. """ test_heap = heap.Heap() with pytest.raises(IndexError): test_heap.extract_max()
5,287,695
def run_doctests(module, flags=FLAGS): """ Runs doctests with our default flags """ return doctest.testmod(module, optionflags=flags)
5,287,696
def posterize(image, bits): """ Reduce the number of bits for each color channel. :param image: The image to posterize. :param bits: The number of bits to keep for each channel (1-8). :return: An image. """ lut = [] mask = ~(2 ** (8 - bits) - 1) for i in range(256): lut.appe...
5,287,697
def early_downsample_count(nyquist, filter_cutoff, hop_length, n_octaves): """Compute the number of early downsampling operations""" downsample_count1 = max( 0, int(np.ceil(np.log2(0.85 * nyquist / filter_cutoff)) - 1) - 1 ) # print("downsample_count1 = ", downsample_count1) num_twos = next...
5,287,698
def listusers(l, b, i): """ !d List all users who have files !r user """ b.l_say('Users:', i, 0) for f in os.listdir(os.path.join('..', 'files', 'users')): b.l_say(' %s' % (_random() + f.replace('.json', '')), i, 0) return True
5,287,699