content
stringlengths
22
815k
id
int64
0
4.91M
def xml_ind(content): """Translate a individual expression or variable to MathCAD XML. :param content: str, math expression or variable name. :return: str, formatted MathCAD XML. """ ns = ''' xmlns:ml="http://schemas.mathsoft.com/math30">''' # name space as initial head sub_statement = xml_sta...
9,500
def run_game(): """Inicializa o jogo e cria um objeto para a tela - 1200/700""" pygame.init() ai_settings = Settings() screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) # Definindo Telas pygame.display.set_caption(f'Alien-Invasion') pygame.display.set_i...
9,501
def p_q_STRING(p): """q_STRING : "'" STRING "'" """ p[0] = p[2]
9,502
def now_playing(update, context): """Information about the current song.""" with mpdclient() as c: song = c.currentsong() # TODO(shoeffner): Handle properly update.message.reply_text(song)
9,503
def CheckPortFree(port): """Check the availablity of the tcp port. Args: Integer, a port number. Raises: PortOccupied: This port is not available. """ tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: tcp_socket.bind(("", port)) except socket.error...
9,504
def test_communicator(url): """Test the instantiation of a ``kiwipy.rmq.RmqThreadCommunicator``. This class is used by all runners to communicate with the RabbitMQ server. """ RmqThreadCommunicator.connect(connection_params={'url': url})
9,505
def read_slug(slug: str, db: Session = Depends(get_db)) -> Any: """ Get a post by slug """ db_slug = get_post(db, slug) if db_slug is None: raise HTTPException(status_code=404, detail="Post not found") return db_slug
9,506
def left_join_predictions(anno_gold: pd.DataFrame, anno_predicted: pd.DataFrame, columns_keep_gold: List[str], columns_keep_system: List[str]) -> pd.DataFrame: """ Given gold mention annotations and predicted mention annotations, this method returns the gold annotations with additi...
9,507
def get_users_data(filter): """ Returns users in db based on submitted filter :param filter: :return: """ # presets - filter must be in one of the lists filter_presets = {"RegistrationStatus": ["Pending", "Verified"], "userTypeName": ["Administrator", "Event Manager", "Alumni"]} if filte...
9,508
def test_graph_diffusion() -> None: """ 1) Provide both labelled and unlabelled data points. 2) Run label propagation, collect diffused labels for the unlabelled data 3) Verify the match between true and diffused labels """ # Create labelled and unlabelled data points noisy_circles, labels ...
9,509
def calAdjCCTTFromTrace(nt,dt,tStartIn,tEndIn,dataIn, synthIn): """ calculate the cross correlation traveltime adjoint sources for one seismogram IN: nt : number of timesteps in each seismogram dt : timestep of seismograms tStartIn : float starting time for trac...
9,510
def get_par_idx_update_pars_dict(pars_dict, cmd, params=None, rev_pars_dict=None): """Get par_idx representing index into pars tuples dict. This is used internally in updating the commands H5 and commands PARS_DICT pickle files. The ``pars_dict`` input is updated in place. This code was factored out v...
9,511
def profile(function, *args, **kwargs): """ Log the runtime of a function call. Args: function: The callable to profile. args: Additional positional arguments to ``function``. kwargs: Additional keyword arguments to ``function``. Returns: The result of applying ``functi...
9,512
def get_parser(): """Define the command line interface""" from argparse import ArgumentParser from argparse import RawTextHelpFormatter from .. import __version__ as _vstr parser = ArgumentParser(description='SDC Workflows', formatter_class=RawTextHelpFormatter) par...
9,513
def COSTR(LR, R, W, S): """ COSTR one value of cosine transform of two-sided function p. 90 """ COSNW = 1. SINNW = 0. COSW = COS(W) SINW = SIN(W) S = R[0] for I in range(1, LR): T = COSW * COSNW - SINW * SINNW COSNW = T S += 2 * R[I] * COSNW re...
9,514
def CV_SIGN(*args): """CV_SIGN(int a)""" return _cv.CV_SIGN(*args)
9,515
def import_config_data(config_path): """ Parameters ---------- config_path : str path to the experimental configuration file Returns ------- config data : dict dict containing experimental metadata for a given session config file """ data = get_config(config_path) ...
9,516
def evaluate_agent(agent, environment, num_episodes, max_steps, render=True): """Evaluate an agent in an environment. Parameters ---------- agent: AbstractAgent environment: AbstractEnvironment num_episodes: int max_steps: int render: bool """ with Evaluate(agent): rollo...
9,517
def sigmaLabel(ax, xlabel, ylabel, sigma=None): """Label the axes on a figure with some uncertainty.""" confStr = r'$\pm{} \sigma$'.format(sigma) if sigma is not None else '' ax.set_xlabel(xlabel + confStr) ax.set_ylabel(ylabel + confStr) return ax
9,518
def startswith(x, prefix): """Determines if entries of x start with prefix Args: x: A vector of strings or a string prefix: The prefix to test against Returns: A bool vector for each element in x if element startswith the prefix """ x = regcall(as_character, x) return x...
9,519
def create_estimator(est_cls, const_kwargs, node, child_list): """ Creates an estimator. :param est_cls: Function that creates the estimator. :param const_kwargs: Keyword arguments which do not change during the evolution. :param child_list: List of converted child nodes - should me empty. :par...
9,520
def exists(hub_id): """Check for existance of hub in local state. Args: hub_id(str): Id of hub to query. The id is a string of hexadecimal sections used internally to represent a hub. """ if 'Hubs.{0}'.format(hub_id) in config.state: return True else: return False
9,521
def train_one(): """ train an agent """ print("==============Start Fetching Data===========") df = YahooDownloader(start_date = config.START_DATE, end_date = config.END_DATE, ticker_list = config.DOW_30_TICKER).fetch_data() print("==============S...
9,522
def query_by_date_after(**kwargs): """ 根据发布的时间查询,之后的记录: 2020-06-03之后,即2020-06-03, 2020-06-04, ...... :param kwargs: {'date': date} :return: """ session = None try: date = kwargs['date'].strip() + config.BEGIN_DAY_TIME session = get_session() ret = session.query(Play)....
9,523
def get_artifact_path(name): """Получение пути для сохранения артефакта. Side-эффект: Создание директории @param name: Название артефакта @return Путь для сохранения """ if not os.path.exists('../artifacts/'): os.makedirs('../artifacts/') path = f'../artifacts/{name}.png' print(f'N...
9,524
def _step_4_find_peaks( aligned_composite_bg_removed_im, aligned_roi_rect, raw_mask_rects, border_size, field_df, sigproc_params, ): """ Find peaks on the composite image TASK: Remove the mask rect checks and replace with the same masking logic that is now implemented in the ali...
9,525
def get_reverse_host(): """Return the reverse hostname of the IP address to the calling function.""" try: return socket.gethostbyaddr(get_ipaddress())[0] except: return "Unable to resolve IP address to reverse hostname"
9,526
def trans_stop(value) -> TransformerResult: """ A transformer that simply returns TransformerResult.RETURN. """ return TransformerResult.RETURN
9,527
def generator(n, mode): """ Returns a data generator object. Args: mode: One of 'training' or 'validation' """ flip_cams = False if FLAGS.regularization == 'GRU': flip_cams = True gen = ClusterGenerator(FLAGS.train_data_root, FLAGS.view_num, FLAGS.max_w, FLAGS.max_h, ...
9,528
def AddAppProfileResourceArg(parser, verb): """Add app profile positional resource argument to the parser.""" concept_parsers.ConceptParser.ForResource( 'app_profile', GetAppProfileResourceSpec(), 'The app profile {}.'.format(verb), required=True).AddToParser(parser)
9,529
def remove_multispaces(text): """ Replace multiple spaces with only 1 space """ return [re.sub(r' +', " ",word) for word in text]
9,530
def empirical_ci(arr: np.ndarray, alpha: float = 95.0) -> np.ndarray: """Computes percentile range in an array of values. Args: arr: An array. alpha: Percentile confidence interval. Returns: A triple of the lower bound, median and upper bound of the confidence interval with...
9,531
def euclidean(a,b): """Calculate GCD(a,b) with the Euclidean algorithm. Args: a (Integer): an integer > 0. b (Integer): an integer > 0. Returns: Integer: GCD(a,b) = m ∈ ℕ : (m|a ⋀ m|b) ⋀ (∄ n ∈ ℕ : (n|a ⋀ n|b) ⋀ n>m). """ if(a<b): a,b = b,a a, b = abs(a), abs(b) while a != 0: a, b = b % a, a return...
9,532
def check_reserved_pulse_id(pulse: OpInfo) -> Union[str, None]: """ Checks whether the function should be evaluated generically or has special treatment. Parameters ---------- pulse The pulse to check. Returns ------- : A str with a special identifier representing w...
9,533
def test_arr_provided(): """ Test for arrays provided as image and/or mask input. """ an_arr_tup = (2, 3) with pytest.raises(AttributeError): make_apply_mask(an_arr_tup, mask_arr=im_mask, vals=[0, 4]) with pytest.raises(AttributeError): make_apply_mask(im, mask_arr=an_arr_tup, vals=[0, ...
9,534
def figure(*args, **kwargs): """ Returns a new SpectroFigure, a figure extended with features useful for analysis of spectrograms. Compare pyplot.figure. """ kw = { 'FigureClass': SpectroFigure, } kw.update(kwargs) return plt.figure(*args, **kw)
9,535
def test_objects_mutation(token): """ Ensures that mutations objects are compiled correctly. """ tree = Tree('mutation', [token]) expected = {'$OBJECT': 'mutation', 'mutation': token.value, 'arguments': []} assert Objects.mutation(tree) == expected
9,536
def allow_ports(ports, proto="tcp", direction="in"): """ Fully replace the incoming or outgoing ports line in the csf.conf file - e.g. TCP_IN, TCP_OUT, UDP_IN, UDP_OUT, etc. CLI Example: .. code-block:: bash salt '*' csf.allow_ports ports="[22,80,443,4505,4506]" proto='tcp' direction=...
9,537
def add(n1, n2, base=10): """Add two numbers represented as lower-endian digit lists.""" k = max(len(n1), len(n2)) + 1 d1 = n1 + [0 for _ in range(k - len(n1))] d2 = n2 + [0 for _ in range(k - len(n2))] res = [] carry = 0 for i in range(k): if d1[i] + d2[i] + carry < base: ...
9,538
def _Grafik_mit_matplotlib(*args, **kwargs): """Funktion zum Erzeugen von 2D-Grafiken mit matplotlib""" Vektor = importlib.import_module('agla.lib.objekte.vektor').Vektor plt.close('all') mlab.close(all=True) achsen = True if kwargs.get('achsen') is None else kwargs.get('achsen'...
9,539
def client_thread(client_url, context, i): """ Basic request-reply client using REQ socket """ socket = context.socket(zmq.REQ) identity = "Client-%d" % (i) socket.setsockopt(zmq.IDENTITY, identity) #Set client identity. Makes tracing easier socket.connect(client_url) # Send re...
9,540
def test_enumerating_tautomers_apply(): """ Test enumerating tautomers and make sue the input molecule is also returned. """ enumerate_tauts = workflow_components.EnumerateTautomers() enumerate_tauts.max_tautomers = 2 mols = get_tautomers() result = enumerate_tauts.apply(mols, processors=1...
9,541
def test_set_humidity_level(gateway, add_sensor): """Test set humidity level.""" sensor = add_sensor(1) sensor.add_child_sensor(1, gateway.const.Presentation.S_HUM) gateway.logic('1;1;1;0;1;75\n') assert sensor.children[1].values[gateway.const.SetReq.V_HUM] == '75'
9,542
def folder_datetime(foldername, time_infolder_fmt=TIME_INFOLDER_FMT): """Parse UTC datetime from foldername. Foldername e.g.: hive1_rpi1_day-190801/ """ # t_str = folder.name.split("Photos_of_Pi")[-1][2:] # heating!! t_str = foldername.split("day-")[-1] day_naive = datetime.strptime(t_str, ti...
9,543
def get_policy_profile_by_name(name, db_session=None): """ Retrieve policy profile by name. :param name: string representing the name of the policy profile :param db_session: database session :returns: policy profile object """ db_session = db_session or db.get_session() vsm_hosts = con...
9,544
def ecg_hrv_assessment(hrv, age=None, sex=None, position=None): """ Correct HRV features based on normative data from Voss et al. (2015). Parameters ---------- hrv : dict HRV features obtained by :function:`neurokit.ecg_hrv`. age : float Subject's age. sex : str Subj...
9,545
def declared_attr_roles(rw=None, call=None, read=None, write=None): """ Equivalent of :func:`with_roles` for use with ``@declared_attr``:: @declared_attr @declared_attr_roles(read={'all'}) def my_column(cls): return Column(Integer) While :func:`with_roles` is always the...
9,546
def _in_iterating_context(node): """Check if the node is being used as an iterator. Definition is taken from lib2to3.fixer_util.in_special_context(). """ parent = node.parent # Since a call can't be the loop variant we only need to know if the node's # parent is a 'for' loop to know it's being ...
9,547
def to_point(obj): """Convert `obj` to instance of Point.""" if obj is None or isinstance(obj, Point): return obj if isinstance(obj, str): obj = obj.split(",") return Point(*(int(i) for i in obj))
9,548
def writeTable(filename='logs/table.txt', methods={'planenet_normal': 'PlaneNet', 'warping_normal_pair': 'Ours', 'basic_normal_backup': 'Ours (w/o warping loss)', 'warping_normal_none_pair': 'Ours (w/o normal anchors', 'warping_joint_pair': 'Ours (w/o depth map)'}, cols=[20, 19, 21, 32, 38, 44], dataset=''): """Wri...
9,549
def issues(request, project_id): """问题栏""" if request.method == "GET": # 筛选条件 -- 通过get来实现参数筛选 allow_filter_name = ['issues_type', 'status', 'priority', 'assign', 'attention'] condition = {} # 条件 for name in allow_filter_name: value_list = request.GET.getlist(name) ...
9,550
def get_30mhz_rht_data(sensor_id): """ Produces a JSON with the 30MHz RH & T sensor data for a specified sensor. Args: sensor_id - Advanticsys sensor ID Returns: result - JSON string """ dt_from, dt_to = parse_date_range_argument(request.args.get("range")) query = ( ...
9,551
def stock_em_gpzy_industry_data() -> pd.DataFrame: """ 东方财富网-数据中心-特色数据-股权质押-上市公司质押比例-行业数据 http://data.eastmoney.com/gpzy/industryData.aspx :return: pandas.DataFrame """ url = "http://dcfm.eastmoney.com/EM_MutiSvcExpandInterface/api/js/get" page_num = _get_page_num_gpzy_industry_data() te...
9,552
def to_float32(x: tf.Tensor) -> tf.Tensor: """Cast the given tensor to float32. Args: x: The tensor of any type. Returns: The tensor casts to float32. """ return tf.cast(x, tf.float32)
9,553
def _read_and_load_options(): """ Read file and add all settings to dict :return: None """ parser = SimpleConfigParser() parser.read(_config_file) global _settings _settings = {} for item in parser.items(_DEFAULT_SECTION): _settings[item[0]] = item[1]
9,554
def toDerivative( data, derivativeType=2, normalize=-1 ): """ @deprecated function moved to @ref dspUtil """ raise Exception("toDerivative(...) has been moved to the module dspUtil")
9,555
def cli_usage(name=None): """ custom usage message to override `cli.py` """ return """ {logo} usage: signalyze [-h] [-o OUTPUT] [--show-name] [-b | -w | -all] [--show-graph | --show-extra-info] """.format(logo=get_logo())
9,556
def unban_chat_member(chat_id, user_id, **kwargs): """ Use this method to unban a previously kicked user in a supergroup. The user will not return to the group automatically, but will be able to join via link, etc. The bot must be an administrator in the group for this to work :param chat_id: Unique id...
9,557
def parse_progress_line(prefix: str, line: str) -> Optional[float]: """Extract time in seconds from a prefixed string.""" regexp = prefix + r"(?P<hours>\d+):(?P<minutes>\d{2}):(?P<seconds>\d{2}.\d{2})" match = re.search(regexp, line) if not match: return None return ( int(match.group...
9,558
def convert_array_to_df(emission_map): """ This function converts the emission map dict to a DataFrame where - 'emission_map' is a dictionary containing at least 'z_var_ave', 'count_var','std_var','q25_var' and'q75_var """ def reform_df(df, nr): """This subfunction will reform the format of...
9,559
def add_missing_flows(data): """There are some flows not given in ReCiPe that seem like they should be there, given the relatively coarse precision of these CFs.""" new_cfs = { "managed forest": { "amount": 0.3, "flows": [ "occupation, forest, unspecified", ...
9,560
def graph_x(EC1, EM1, EY1, x01, parlist): """ This function serves as an interactive visualization tool showing how material inputs change in sector 1 and 2, in two separate graphs, if we change the elasticities of substitution (EC, EM, EY) Args: x0: initial vector if the guess is poor the ...
9,561
def count_features(sm): """ Counts reads mapped to features such as KOs, PFAMs etc. :param sm: :return: """ feature_sum = sum_to_features(sm.input.abund, sm.input.annot[0]) feature_sum.to_csv(sm.output[0], sep="\t")
9,562
def test_get_config_verbose_parser(fxtr_setup_logger_environment): """Test: get_config_verbose_parser().""" cfg.glob.logger.debug(cfg.glob.LOGGER_START) # ------------------------------------------------------------------------- values_original = pytest.helpers.backup_config_params( cfg.glob.se...
9,563
def repl(): """ REPL: Read-Eval-Print Loop Response based on input from do_action Args: None Return: None """ with open("title_screen.txt", encoding="utf8") as file_descriptor: contents = file_descriptor.read() print(contents) current_room = actio...
9,564
def test_list_parameters(database): """List parameters mapped as expected.""" query = 'query' parameters = [ 'message', 'count', 'nested', 'nested.message', 'unknown', 'nested.unknown', 'message.unknown', 'count.unknown', ] batch = [ ...
9,565
def cglb_conjugate_gradient( K: TensorType, b: TensorType, initial: TensorType, preconditioner: NystromPreconditioner, cg_tolerance: float, max_steps: int, restart_cg_step: int, ) -> tf.Tensor: """ Conjugate gradient algorithm used in CGLB model. The method of conjugate gradient ...
9,566
def crb_ax(n, Ndim=6, vary=['halo', 'bary', 'progenitor'], align=True, fast=False): """Calculate CRB inverse matrix for 3D acceleration at position x in a halo potential""" pid, dp, vlabel = get_varied_pars(vary) if align: alabel = '_align' else: alabel = '' # read in full ...
9,567
def build_docker_build(latest=True): """Create command used to (re)build the container. We store the Dockerfile (as that name) in dir .next or .latest so that we can have various templates and assets and so on in the 'context' directory. """ tmpl = "{} build -t {{tagname}}:{{tagtag}} {{pa...
9,568
def motif_compare(args): """Compare PSSMs of filter motifs.""" # create output directory if not os.path.exists(args.out_dir): os.makedirs(args.out_dir) # load training data to determine background nucleotide content train_samples = np.load(args.train_data, mmap_mode='r') probs = np.mean...
9,569
def iter_local_job_status(s3_scratch_prefix: str, job_id2job: Dict[str, "Job"]) -> Iterator[dict]: """ Returns local Docker jobs grouped by their status. """ running_containers = subprocess.check_output(["docker", "ps", "--no-trunc"]).decode("utf8") for job_id, redun_job in job_id2job.items(): ...
9,570
def show_menu_items(category, items): """Takes a category name and item list and prints them out. input: category (str) input: items (list) returns: none """ # Print category name print(category.title()) print('-' * len(category)) for item in items: # Print each item in titl...
9,571
def scrape_new_thread(thread_name, url): """Scrape data for a thread that isn't already in our database.""" logger.debug(f"Start of scrape_new_thread for {thread_name}, {url}") # URL Validation # TODO: write this function, then hand it off to scrape_existing_thread() logger.debug("Now that the thr...
9,572
def num_fixed_points(permutation): """ Compute the number of fixed points (elements mapping to themselves) of a permutation. :param permutation: Permutation in one-line notation (length n tuple of the numbers 0, 1, ..., n-1). :return: Number of fixed points in the permutation. .. rubric:: Examples...
9,573
def load_messages(path, unique, verbose): """ Loads messages from the corpus and returns them as Message objects """ messages = [] signatures = set() for root, _, files in os.walk(path): if verbose: print("Processing {}".format(root)) for message_file in files: me...
9,574
def backup(project=None, force=False): """Perform pending backups""" if project: name = project project = ProjectsManager.get_project_by_name(name) if not project: click.echo('Project with name "%s" is not installed!' % name) return projects = [project]...
9,575
def mutate(grid): """ Alters the cycle by breaking it into two separate circuits, and then fusing them back together to recreate a (slightly different) cycle. This operation is called "sliding" in 'An Algorithm for Finding Hamiltonian Cycles in Grid Graphs Without Holes', and it's specifically ment...
9,576
def reverse_permute(output_shape: np.array, order: np.array): """ Calculates Transpose op input shape based on output shape and permute order. :param output_shape: Transpose output shape :param order: permute order :return: Transpose input shape corresponding to the specified output shape """ ...
9,577
def recursive_bisection(block, block_queue, epsilon_cut, depth_max, theta, lamb, delta, verbose=False): """Random cut and random converge Args: block_queue (multiprocessing.Queue): Shared queue to store blocks to be executed Returns: [{"range": {int: (int,int)}, "mondrian_budget": float, "...
9,578
def _get_global_step_read(graph=None): """Gets global step read tensor in graph. Args: graph: The graph in which to create the global step read tensor. If missing, use default graph. Returns: Global step read tensor. Raises: RuntimeError: if multiple items found in collection GLOBAL_STEP_RE...
9,579
def light_control() -> LightControl: """Returns the light_control mock object.""" mock_request = Mock() mock_request.return_value = "" return LightControl(mock_request)
9,580
def test_event(): """Test pour la fonction event_handling.""" _, players = main.initialization(False) # Test pour KEY_DOWN cf.STATE = cf.State.ingame for i, P in enumerate(players): event = ut.make_event(ut.KEYDOWN, {'key': plyr.JUMP_KEYS[i]}) players = gml.event_handling(players, e...
9,581
def map_threshold(stat_img=None, mask_img=None, alpha=.001, threshold=3., height_control='fpr', cluster_threshold=0): """ Compute the required threshold level and return the thresholded map Parameters ---------- stat_img : Niimg-like object or None, optional statistical image (...
9,582
def convertError( sourceType: Type[BaseException], targetType: Callable[[], BaseException] ) -> Generator[None, None, None]: """ Convert an error into a different error type. @param sourceType: The type of exception that should be caught and converted. @type sourceType: L{BaseException} ...
9,583
def grab_features(dataframe: pd.DataFrame) -> pd.DataFrame: """ Attempts to assign song features using the get_features function to all songs in given dataframe. This function creates a column that encompasses all features retuerned from Spotify in a json format for each track ID. It then explodes thi...
9,584
def _build_geo_shape_query(field, geom, relation): """Crea una condición de búsqueda por relación con una geometría en formato GeoJSON. Args: field (str): Campo de la condición. geom (dict): Geometría GeoJSON. relation (str): Tipo de búsqueda por geometrías a realizar. Ver la ...
9,585
def load_image(mm_type, images_urls): """加载图片 """ for url in images_urls: path = os.path.join(OUTPUT, mm_type, os.path.split(url)[-1].split('.')[0]) if os.path.exists(path): return os.makedirs(path) content = etree.HTML(get(url,url).text) img_srcs = content.xp...
9,586
def ProcessConfigurationFile(options): """Process configuration file, merge configuration with OptionParser. Args: options: optparse.OptionParser() object Returns: options: optparse.OptionParser() object global_ns: A list of global nameserver tuples. regional_ns: A list of regional nameservers t...
9,587
def lastquote(user, channel, text): """Show the last quote""" callback = partial(_single_quote_callback, channel) run_query("SELECT rowid, quote FROM quote ORDER BY rowid DESC\ LIMIT 1;", [], callback)
9,588
def map_symptom(symptom_name: str) -> Optional[str]: """ Maps a *symptom_name* to current symptom values in ID3C warehouse. There is no official standard for symptoms, we are using the values created by Audere from year 1 (2018-2019). """ symptom_map = { 'feeling feverish': ...
9,589
def check_sbatch(cmd, call=True, num_cpus=1, mem="2G", time=None, partitions=None, dependencies=None, no_output=False, no_error=False, use_slurm=False, mail_type=['FAIL', 'TIME_LIMIT'], mail_user=None, stdout_file=None, stderr_file=None, args=None): """ This function wraps calls t...
9,590
def get_project_details(p): """Extract from the pickle object detailed information about a given project and parse it in a comprehensive dict structure.""" res = {} project = p['projects'][0] fields = {'Owner(s)': 'project_owners', 'Member(s)': 'project_members', 'Colla...
9,591
def get_category(name: str) -> Category: """Returns a category with a given name""" return Category.objects.get(name=name)
9,592
def extract_sentiment_analysis(model): """Runs extraction common for all sentiment analysis models""" model.extract_torchscript() model.extract_onnx()
9,593
def log_report(): """ The log report shows the log file. The user can filter and search the log. """ log_main = open(main_log, 'r').readlines() data_main = [] for line in log_main: split_line = line.split(' ') data_main.append([' '.join(split_line[:2]), ' '.join(split_line[2:])]) ret...
9,594
def register(ctx, repo_path): """Register a report with LSST the Docs. This command only needs to be run once, when you're creating a new report repository. The command creates a new "product" on LSST the Docs where instances of the report are published. **Required arguments** ``REPO_PATH`` ...
9,595
def int_or_none(x) -> int: """Either convert x to an int or return None.""" try: return int(x) except TypeError: return None except ValueError: return None
9,596
def create_parser_for_docs() -> argparse.ArgumentParser: """Create a parser showing all options for the default CLI documentation. Returns: The primary parser, specifically for generating documentation. """ daiquiri.setup(level=logging.FATAL) # load default plugins plugin.initialize...
9,597
def split_into_batches(all_users, batch_size=BATCH_SIZE): """h/t: https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks""" for i in range(0, len(all_users), batch_size): yield all_users[i : i + batch_size]
9,598
def extra_lo_ips(): """Setup IPs that are used for simulating e.g. agent, mesos leader, etc.. """ ips = ['127.0.0.2', '127.0.0.3'] for ip in ips: add_lo_ipaddr(ip, 32) yield for ip in ips: del_lo_ipaddr(ip, 32)
9,599