content
stringlengths
22
815k
id
int64
0
4.91M
def test_exact_enumeration(): """ Testing the Exact Enumeration class. """ solver = ExactEnumeration() W = np.random.uniform(0, 1, (100, 7)) solver.solve_game(W, q=2.5) Phi = solver.get_solution() Phi_tilde = solver.get_average_shapley() entropy = solver.get_shapley_entropy() ...
11,400
def soup_from_name(username): """ Grabs bs4 object from html page """ # html_source = urlopen('https://www.instagram.com/'+ str(username) + '/') url = 'https://www.instagram.com/'+ str(username) + '/' headers = {"User-Agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0)" \ "AppleWebK...
11,401
def test_parse_single_mark_en() -> None: """Testing a single bookmark in English.""" raw_string = """Book 2 (Spanish Edition) (Author 2) - Your Bookmark on Location 1012 | Added on Saturday, February 9, 2013 10:40:33 """ clipping = Clipping.parse_single_highlight(raw_string) assert clipping is not No...
11,402
def iface_down(ifname): """Flush all ip addresses belonging to the interface. """ if ifname is None: return ipr = IPRoute() try: ipr.flush_addr(label=ifname) x = ipr.link_lookup(ifname=ifname)[0] ipr.link('set', index=x, state='down') except Exception: pa...
11,403
def SectionMenu(rating_key, title=None, base_title=None, section_title=None, ignore_options=True, section_items_key="all"): """ displays the contents of a section :param section_items_key: :param rating_key: :param title: :param base_title: :param section_title: :param ig...
11,404
def round_floats_for_json(obj, ndigits=2, key_ndigits=None): """ Tries to round all floats in obj in order to reduce json size. ndigits is the default number of digits to round to, key_ndigits allows you to override this for specific dictionary keys, though there is no concept of nested keys. It...
11,405
def visualize(**images): """PLot images in one row.""" n = len(images) plt.figure(figsize=(16, 5)) for i, (name, image) in enumerate(images.items()): plt.subplot(1, n, i + 1) plt.xticks([]) plt.yticks([]) plt.title(' '.join(name.split('_')).title()) plt.i...
11,406
def read_shared(function_name, verb, request, local_variables=None): """all the shared code for each of thse read functions""" command = function_name.split('_')[1] # assumes fn name is query_<command> command_args, verb_args = create_filters(function_name, command, request, ...
11,407
def http_put_request( portia_config: dict, endpoint: str, payload: dict, params: dict=None, optional_headers: dict=None ) -> object: """Makes an HTTP PUT request. Arguments: portia_config {dict} -- Portia's configuration arguments endpoint {str} -- endpoint to make the...
11,408
def construct_SN_default_rows(timestamps, ants, nif, gain=1.0): """ Construct list of ants dicts for each timestamp with REAL, IMAG, WEIGHT = gains """ default_nif = [gain] * nif rows = [] for ts in timestamps: rows += [{'TIME': [ts], 'TIME INTERVAL': [0.1], ...
11,409
def test_is_matching(load_email): """it should be able to match a deposit email""" html = load_email(EMAIL_PATH) assert deposit_email.is_matching(html)
11,410
async def test_disable(aresponses): """Test disabling AdGuard Home query log.""" async def response_handler(request): data = await request.json() assert data == {"enabled": False, "interval": 1} return aresponses.Response(status=200) aresponses.add( "example.com:3000", ...
11,411
def load_checkpoint(path: str, device: torch.device = None, logger: logging.Logger = None) -> MoleculeModel: """ Loads a model checkpoint. :param path: Path where checkpoint is saved. :param device: Device where the model will be moved. :param logger: A logge...
11,412
def kron_diag(*lts): """Compute diagonal of a KroneckerProductLazyTensor from the diagonals of the constituiting tensors""" lead_diag = lts[0].diag() if len(lts) == 1: # base case: return lead_diag trail_diag = kron_diag(*lts[1:]) diag = lead_diag.unsqueeze(-2) * trail_diag.unsqueeze(-1) ...
11,413
def makeBundleObj(config_fname, getPackage, getPackageLength): """Given a description of a thandy bundle in config_fname, return a new unsigned bundle object. getPackage must be a function returning a package object for every package the bundle requires when given the package's name as input....
11,414
async def test_availability_without_topic(hass, mqtt_mock): """Test availability without defined availability topic.""" await help_test_availability_without_topic( hass, mqtt_mock, fan.DOMAIN, DEFAULT_CONFIG )
11,415
def find_English_term(term: list) -> tuple: """ Find the English and numbers from a term list and remove the English and numbers from the term :param term: the term list :return term: the term removed the English and numbers :return Eng_terms: the removed English """ temp_terms = [] ...
11,416
def run(argv=None): """Build and run the pipeline.""" parser = argparse.ArgumentParser() parser.add_argument( '--output', required=True, help=('Output file to write to')) parser.add_argument( '--input', required=True, help=('Input PubSub topic of the form ' '"projects/<PROJEC...
11,417
def listplaylists(context): """ *musicpd.org, stored playlists section:* ``listplaylists`` Prints a list of the playlist directory. After each playlist name the server sends its last modification time as attribute ``Last-Modified`` in ISO 8601 format. To avoid problems...
11,418
def add_target_variable(df: pd.DataFrame) -> pd.DataFrame: """Add column with the target variable to the given dataframe.""" return df.assign(y=df.rent + df.admin_fee)
11,419
def extension_list(filepath): """Show list of extensions.""" path = pathlib.Path.cwd()/pathlib.Path(filepath) file_extensions = [FileExtension(p.relative_to(p.cwd())) for p in path.iterdir() if p.is_dir() and not p.name.startswith(('.', '__'))] py_extensions = [PyExtension(p.rela...
11,420
def get_address_from_public_key(public_key): """ Get bytes from public key object and call method that expect bytes :param public_key: Public key object :param public_key: ec.EllipticCurvePublicKey :return: address in bytes :rtype: bytes """ public_key_bytes = get_public_ke...
11,421
def test_that_we_dont_revert_finalized_cp(db): """ This tests that the chain is the chain is """ test_string = 'B J0 J1 J2 B B B S0 B V0 V1 V2 B V0 V1 V2 B S1 R0 B B B B B B B B V0 V1 V2 B1 H1' test = TestLangHybrid(5, 100, 0.02, 0.002) test.parse(test_string)
11,422
def generate_validation() -> 'Pickle File': """Generates the validation set of Qualtrics Codes from surveys library""" url = 'https://{}.qualtrics.com/API/v3/surveys/'.format(qualtrics_settings['Data Center']) Qualtrics_Codes = {} """Sets the Years""" years = [time.localtime().tm_year...
11,423
def setup(bot: ModmailBot) -> None: """Add the paginator cleaner to the bot.""" bot.add_cog(PaginatorManager(bot))
11,424
def main() -> None: """Times the given command. TODO: consider ways of making this fancier. - Print memory usage? - Recurrent? """ ...
11,425
def read_ORIGEN_gamma_spectrum(output_filename, cooling_time_string): """ Function for reading a gamma spectrum from an ORIGEN output file. """ #Too long text may cause problems, so check for it. if len(cooling_time_string) >= 10: print("The cooling time could not be found in the...
11,426
def process_cases(list_): """Process cases and determine whether group flag or empty line.""" # Get information is_empty = (len(list_) == 0) if not is_empty: is_group = list_[0].isupper() is_comment = list_[0][0] == '#' else: is_group = False is_comment = False ...
11,427
def updateNestedDicts(d1, d2): """Updates two dictionaries, assuming they have the same entries""" finalDict = createDictionary() for key in d1: #print(key) newDict = updateDicts(d1[key], d2[key]) finalDict[key] = newDict return finalDict
11,428
def process_data(window): """ clean and save data ... previous executed manually with submit button """ # try: clean_code, char_cnt, code_stats = clean_data(window) save_data(clean_code, code_stats, window) display_charts(char_cnt, window) display_stats(code_stats, window) window["-TAB RAW-"...
11,429
def page_not_found(e): """error handler for page not found""" flash(e.description, 'danger') return render_template('main/404.html'), 404
11,430
def get_cifar10_raw_data(): """ Gets raw CIFAR10 data from http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz. Returns: X_train: CIFAR10 train data in numpy array with shape (50000, 32, 32, 3). Y_train: CIFAR10 train labels in numpy array with shape (50000, ). X_test: CIFAR10 test data in numpy a...
11,431
def random_first_file(rootpath: Union[str, Path]) -> Path: """Donne un fichier aléatoire d'une arborescence, en descendant en profondeur d'abord. Args: rootpath (Union[str, Path]): chemin racine de recherche Returns: Path: Un chemin vers le fichier """ iterator = os.walk(rootpath)...
11,432
def MovieMaker(images, dpath, site, scheck, coords, bandlist, datelist, bands): """ Function to build the movie """ failed = 0 while failed <2: spath = dpath + "UoL/FIREFLIES/VideoExports/%s" % coords["name"] # for bands in bandcombo: print("\n starting %s at:" % bands, pd.Timestamp.now()) # ========...
11,433
def test_list_blocks_233(): """ Test case 233: (part 1) Here are some examples showing how far content must be indented to be put under the list item: Note: The tokens are correct. The blank line on line 2 forces the paragraph closed. As it is still allowed inside of the list, only affecting th...
11,434
def transform(args, argv): """ Usage: {0} transform [--regulate] <sourceconfig> FILE ... {0} transform [--regulate] <sourceconfig> --directory=DIR {0} transform [--regulate] --ids <raw_data_ids>... Options: -r, --regulate Run the Regulator on the transformed graph ...
11,435
def TypeUrlToMessage(type_url): """Returns a message instance corresponding to a given type URL.""" if not type_url.startswith(TYPE_URL_PREFIX): raise ValueError("Type URL has to start with a prefix %s: %s" % (TYPE_URL_PREFIX, type_url)) full_name = type_url[len(TYPE_URL_PREFIX):] try...
11,436
def encode_sentence(tokenized_sentence, max_word_len): """ Encode sentence as one-hot tensor of shape [None, MAX_WORD_LENGTH, CHARSET_SIZE]. """ encoded_sentence = [] sentence_len = len(tokenized_sentence) for word in tokenized_sentence: # Encode every word as matrix of shape [MAX_WO...
11,437
def main(unused_argv): """训练入口""" global total_feature_columns, label_feature_columns dense_feature_columns, category_feature_columns, label_feature_columns = create_feature_columns() total_feature_columns = dense_feature_columns + category_feature_columns params = { "dens...
11,438
def footnote_ref(key, index): """Renders a footnote :returns: list of `urwid Text markup <http://urwid.org/manual/displayattributes.html#text-markup>`_ tuples. """ return render_no_change(key)
11,439
def calendar(rating): """ Generate the calendar for a given rating. """ cal = rating["cal"] garages = set() dates = set() services = {} for record in cal: if not isinstance(record, CalendarDate): continue garages.add(record.garage) dates.add(record.dat...
11,440
def mconcat(*args): """ Apply monoidal concat operation in arguments. This function infers the monoid from value, hence it requires at least one argument to operate. """ values = args[0] if len(args) == 1 else args instance = semigroup[type(values[0])] return instance(*values)
11,441
def parallelMeasurements(filename='CCD204_05325-03-02_Hopkinson_EPER_data_200kHz_one-output-mode_1.6e10-50MeV.txt', datafolder='/Users/sammy/EUCLID/CTItesting/data/', gain1=1.17, limit=105, returnScale=False): """ :param filename: :param datafolder: :param gain1: :param lim...
11,442
def _parse_env(name, default=None, dtype=None): """Parse input variable from `os.environ`. Parameters ---------- name : str Name of the variable to parse from env. default : any, optional Set default value of variable. If None (default), parameter is considered required and ...
11,443
def get_all_urls(the_json: str) -> list: """ Extract all URLs and title from Bookmark files Args: the_json (str): All Bookmarks read from file Returns: list(tuble): List of tublle with Bookmarks url and title """ def extract_data(data: dict): if isinstance(data, dict) a...
11,444
def draw_camera_wireframe(ax: plt.Axes, wireframe: Wireframe) -> None: """Draws a camera wireframe onto the axes.""" ax.add_collection( mc.LineCollection( segments=[[l.start, l.end] for l in wireframe.lines], colors=[l.color for l in wireframe.lines], linewidths=[l.width for l in...
11,445
def _goertzel( block_size: int, sample_rate: float, freq: float ) -> Callable[[Iterable[float]], float]: """ Goertzel algorithm info: https://www.ti.com/lit/an/spra066/spra066.pdf """ k = round(block_size * (freq / sample_rate)) omega = (2 * pi * k) / block_size cos_omega = 2 * ...
11,446
def SetFrames(windowID): """ Querys start and end frames and set thems for the window given by windowID """ start = cmds.playbackOptions(minTime=True, query=True) end = cmds.playbackOptions(maxTime=True, query=True) # Query start and end froms. cmds.intField(OBJECT_NAMES[windowID][0] + "_FrameS...
11,447
def rotate_xyz(x,y,z,angles=None,inverse=False): """ Rotate a set of vectors pointing in the direction x,y,z angles is a list of longitude and latitude angles to rotate by. First the longitude rotation is applied (about z axis), then the latitude angle (about y axis). """ if angles==None: ...
11,448
def indented_open(Filename, Indentation = 3): """Opens a file but indents all the lines in it. In fact, a temporary file is created with all lines of the original file indented. The filehandle returned points to the temporary file.""" IndentString = " " * Indentation try: fh = open...
11,449
def gan_loss( gan_model: tfgan.GANModel, generator_loss_fn=tfgan.losses.modified_generator_loss, discriminator_loss_fn=tfgan.losses.modified_discriminator_loss, gradient_penalty_weight=None, gradient_penalty_epsilon=1e-10, gradient_penalty_target=1.0, feature_matc...
11,450
def precip_workflow(data, valid, xtile, ytile, tile_bounds): """Drive the precipitation workflow""" load_stage4(data, valid, xtile, ytile) # We have MRMS a2m RASTER files prior to 1 Jan 2015, but these files used # a very poor choice of data interval of 0.1mm, which is not large enough # to capture ...
11,451
def list_subjects(): """ List all subjects """ check_admin() subjects = Subject.query.all() return render_template('admin/subjects/subjects.html', subjects=subjects, title="Subjects")
11,452
async def async_setup(opp, config): """Set up the Tibber component.""" opp.data[DATA_OPP_CONFIG] = config if DOMAIN not in config: return True opp.async_create_task( opp.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, ...
11,453
def beautifyValue(v): """ Converts an object to a better version for printing, in particular: - if the object converts to float, then its float value is used - if the object can be rounded to int, then the int value is preferred Parameters ---------- v : object the object to ...
11,454
def english_to_french(english_text): """ A function written using ibm api to translate from english to french""" translation = LT.translate(text=english_text, model_id='en-fr').get_result() french_text = translation['translations'][0]['translation'] return french_text
11,455
def get_responsibilities(): """Returns a list of the rooms in the approvers responsibility.""" email = get_jwt_identity() # Checks if the reader is an approver approver = Approver.query.filter_by(email=email).first() if not approver: return bad_request("This user does not have the approver role!") room_list =...
11,456
def test_country_code_field(result, country_code_list): """Check that a value of 'countryCode' is present in the list of country codes.""" assert result.json()['countryCode'] in country_code_list, \ "The value of field 'countryCode' not present in the list of country codes."
11,457
def get_test_loader(dataset): """ Get test dataloader of source domain or target domain :return: dataloader """ if dataset == 'MNIST': transform = transforms.Compose([ transforms.ToTensor(), transforms.Lambda(lambda x: x.repeat(3, 1, 1)), transforms.Normal...
11,458
def get_wem_facility_intervals(from_date: Optional[datetime] = None) -> WEMFacilityIntervalSet: """Obtains WEM facility intervals from NEM web. Will default to most recent date @TODO not yet smart enough to know if it should check current or archive """ content = wem_downloader(_AEMO_WEM_SCADA_URL, fro...
11,459
def push( message, user: str = None, api_token: str = None, device: str = None, title: str = None, url: str = None, url_title: str = None, priority: str = None, timestamp: str = None, sound: str = None, ) -> typing.Union[http.client.HTTPResponse, typing.BinaryIO]: """Pushes t...
11,460
def _get_static_predicate(pred): """Helper function for statically evaluating predicates in `cond`.""" if pred in {0, 1}: # Accept 1/0 as valid boolean values pred_value = bool(pred) elif isinstance(pred, bool): pred_value = pred elif isinstance(pred, tf.Tensor): pred_value = tf.get_static_value(pr...
11,461
async def test_webhook_platform_init(hass, webhook_platform): """Test initialization of the webhooks platform.""" assert hass.services.has_service(DOMAIN, SERVICE_SEND_MESSAGE) is True
11,462
def add_init_or_construct(template, variable_slot, new_data, scope, add_location=-1): """Add init or construct statement.""" if isinstance(new_data, list): template[variable_slot][scope].extend(new_data) return template if add_location < 0: template[variable_slot][scope].append(new_d...
11,463
def im2col_indices(x, field_height, field_width, padding=1, stride=1): """ An implementation of im2col based on some fancy indexing """ # Zero-pad the input p = padding x_padded = np.pad(x, ((0, 0), (0, 0), (p, p), (p, p)), mode='constant') k, i, j = get_im2col_indices(x.shape, field_height, field_width, padd...
11,464
def guesses_left(): """ Displays remaining number of guesses """ print "Number of remaining guesses is", GUESSES
11,465
def get_subdirs(dir): """Get the sub-directories of a given directory.""" return [os.path.join(dir,entry) for entry in os.listdir(dir) \ if os.path.isdir(os.path.join(dir,entry))]
11,466
def nms_1d(src, win_size, file_duration): """1D Non maximum suppression src: vector of length N """ pos = [] src_cnt = 0 max_ind = 0 ii = 0 ee = 0 width = src.shape[0]-1 while ii <= width: if max_ind < (ii - win_size): max_ind = ii - win_size ee ...
11,467
def tensor_text_to_canvas(image, text=None, col=8, scale=False): """ :param image: Tensor / numpy in shape of (N, C, H, W) :param text: [str, ] * N :param col: :return: uint8 numpy of (H, W, C), in scale [0, 255] """ if scale: image = image / 2 + 0.5 if torch.is_tensor(image): ...
11,468
def camera_loop(app): """ Check if camera is in use or not and free resources :param app: tornado application instance """ if app.camera: if app.config.CAMERA["ffmpeg"]: diff = datetime.datetime.now() - handlers.VideoHandler.last_packet else: diff = datetime.d...
11,469
def is_sequence(input): """Return a bool indicating whether input is a sequence. Parameters ---------- input The input object. Returns ------- bool ``True`` if input is a sequence otherwise ``False``. """ return (isinstance(input, six.collections_abc.Sequence) and ...
11,470
def extract_filename(path): """Parse out the file name from a file path Parameters ---------- path : string input path to parse filename from Returns ------- file_name : string file name (last part of path), empty string if none found """ # get last group of a path if path: file_name = os.path...
11,471
def auto_prefetch_relationship(name, prepare_related_queryset=noop, to_attr=None): """ Given the name of a relationship, return a prepare function which introspects the relationship to discover its type and generates the correct set of `select_related` and `include_fields` calls to apply to efficiently ...
11,472
def no_conjugate_member(magic_flag): """should not raise E1101 on something.conjugate""" if magic_flag: something = 1.0 else: something = 1.0j if isinstance(something, float): return something return something.conjugate()
11,473
def sub_ntt(f_ntt, g_ntt): """Substraction of two polynomials (NTT representation).""" return sub_zq(f_ntt, g_ntt)
11,474
def is_pareto_efficient(costs): """ Find the pareto-efficient points given an array of costs. Parameters ---------- costs : np.ndarray Array of shape (n_points, n_costs). Returns ------- is_efficient_maek : np.ndarray (dtype:bool) Array of which elements in costs are ...
11,475
def merge_dict(base, delta, merge_lists=False, skip_empty=False, no_dupes=True, new_only=False): """ Recursively merges two dictionaries including dictionaries within dictionaries. Args: base: Target for merge delta: Dictionary to merge into base ...
11,476
def database_names(): """ Display database names """ click.echo(neohelper.get_database_names())
11,477
def test_nullable( dtype: pandas_engine.DataType, data: st.DataObject, ): """Test nullable checks on koalas dataframes.""" checks = None if dtypes.is_datetime(type(dtype)) and MIN_TIMESTAMP is not None: checks = [pa.Check.gt(MIN_TIMESTAMP)] nullable_schema = pa.DataFrameSchema( {...
11,478
def redirect_or_error(opt, key, override=''): """ Tests if a redirect URL is available and redirects, or raises a MissingRequiredSetting exception. """ r = (override or opt) if r: return redirect(r) raise MissingRequiredSetting('%s.%s' % ( options.KEY_DATA_DICT, key))
11,479
def extract(struc, calc): """ Extract & write electrostatic potential and densities. Arg: struc: an internal molecular structure object calc: internal calculation object """ # Extract the ESP esp = calc.get_electrostatic_potential() # Convert units esp_hartree = esp / Hartree write('esp.cube', struc, d...
11,480
def stdev(df): """Calculate standard deviation of a dataframe.""" return np.std(df['rate'] - df['w1_rate'])
11,481
def add_to_cart(listing_id): """Adds listing to cart with specified quantity""" listing = Listing.query.filter_by(id=listing_id, available=True).first() if not listing: abort(404) if not request.json: abort(400) if ('quantity' not in request.json or type(request.json['qua...
11,482
def get_zip_code_prefixes(df_geolocation : pd.DataFrame) -> pd.DataFrame: """ Gets the first three and four first digits of zip codes. """ df = df_geolocation.copy() df['geolocation_zip_code_prefix_1_digits'] = df['geolocation_zip_code_prefix'].str[0:1] df['geolocation_zip_code_prefix_2_digits'...
11,483
def elina_scalar_infty(scalar): """ Return -1 if an ElinaScalar is -infinity, 0 if it is finite and 1 if it is +infinity. Parameters ----------- scalar : ElinaScalarPtr Pointer to the ElinaScalar that needs to be tested for infinity. Returns ------- result : c_int ...
11,484
def _package_dmg(paths, dist, config): """Packages a Chrome application bundle into a DMG. Args: paths: A |model.Paths| object. dist: The |model.Distribution| for which the product was customized. config: The |config.CodeSignConfig| object. Returns: A path to the produced D...
11,485
def get_target_grid(return_type, **kwargs): """ Function: get polar or cartasian coordinates of targets Inputs: - return_type: str. "cart" for cartasian coordinates; "polar" for polar coordinates. - kwargs: additional params. - rel_points: dictionary. relative length for target positions and heel positions Outp...
11,486
def test_oracle_cdc_offset_chain(sdc_builder, sdc_executor, database, buffer_locally): """ Test to check that offset between pipeline re-starts is tracked properly, especially focusing on JSON-based offsets. "...
11,487
def s2_filename_to_md(filename): """ This function converts the S2 filename into a small dict of metadata :param filename: :return: dict """ basename = system.basename(filename) metadata = dict() splits = basename.split("_") if len(splits) < 4: raise Exception("{} might not b...
11,488
def remove_freshman_sig(packet_id, freshman): """ Removes the given freshman's signature from the given packet. :param freshman: The freshman's RIT username """ remove_sig(packet_id, freshman, False)
11,489
def parse_command_line_args(): """Parses command line arguments.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( '--service_account_json', default=os.environ.get("GOOGLE_APPLICATION_CREDENT...
11,490
def realtime_performance_sector(raw: bool, export: str): """Display Real-Time Performance sector. [Source: AlphaVantage] Parameters ---------- raw : bool Output only raw data export : str Export dataframe data to csv,json,xlsx file """ df_sectors = alphavantage_model.get_sec...
11,491
def get_rest_api(id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRestApiResult: """ Resource Type definition for AWS::ApiGateway::RestApi """ __args__ = dict() __args__['id'] = id if opts is None: opts = pulumi.InvokeOptions() if...
11,492
def test_subfunc(): """Test subfunction 'my_subfunc' """ a = 'a' b = 'b' res = my_subfunc(a,b) assert res == 'a and b'
11,493
def _uframe_post_instrument_driver_set(reference_designator, command, data): """ Execute set parameters for instrument driver using command and data; return uframe response. (POST) """ debug = False try: uframe_url, timeout, timeout_read = get_c2_uframe_info() if 'CAMDS' in reference_des...
11,494
def do_infra_show(cc, args): """Show infrastructure network attributes.""" iinfras = cc.iinfra.list() if not iinfras: print("Infrastructure network not configured") return iinfra = iinfras[0] _print_iinfra_show(iinfra)
11,495
def regroup_if_changed(group, op_list, name=None): """Creates a new group for op_list if it has changed. Args: group: The current group. It is returned if op_list is unchanged. op_list: The list of operations to check. name: The name to use if a new group is created. Returns: Either group or a ne...
11,496
def spike_train_order_profile(*args, **kwargs): """ Computes the spike train order profile :math:`E(t)` of the given spike trains. Returns the profile as a DiscreteFunction object. Valid call structures:: spike_train_order_profile(st1, st2) # returns the bi-variate profile spike_train_or...
11,497
def home(): """Home page.""" form = LoginForm(request.form) with open("POSCAR", "r") as samplefile: sample_input = samplefile.read() inputs = InputForm() current_app.logger.info("Hello from the home page!") # Handle logging in if request.method == "POST": if form.validate_on...
11,498
def isUniqueSeq(objlist): """Check that list contains items only once""" return len(set(objlist)) == len(objlist)
11,499