content
stringlengths
22
815k
id
int64
0
4.91M
def find_matches(descriptors, filter_matches=True): """Match descriptors to themselves Parameters ---------- descriptors: array_like, shape=[n_keypoints, n_features] The array of descriptors Returns ------- matches: list of cv2.Match The found matches """ print(f"Nu...
66,000
def run(): """ run function which is the start point of program """ file_name = os.path.basename(sys.stdin.name) for line_num, line in enumerate(sys.stdin, start=1): line = line.rstrip('\r\n') if not WORD_ID_PTN.match(line): print(line) continue word =...
66,001
def grade_generic(grader_data, numeric_features, textual_features): """ Grades a set of numeric and textual features using a generic model grader_data -- dictionary containing: { 'algorithm' - Type of algorithm to use to score } numeric_features - list of numeric features to predict on ...
66,002
def add_rule(**kwargs): """ Create a Rule Object from information passed by user, and return a TypeObject who contain the new rule Object. Keyword Args: type (list of one str): rule's type (same as type yaml file) passed by user desc (list of one str): rule's description passed by u...
66,003
def polygon_from_xywh(xywh): """Construct polygon coordinates in numeric list representation from numeric dict representing a bounding box.""" return polygon_from_bbox(*bbox_from_xywh(xywh))
66,004
def cargar_datos(): """ Funcion para cargar los datos de la base de datos """ # Cargar datos de la base de datos path_archivos = "./Data/" data_CF = pd.read_csv(path_archivos + "mmm.csv") return data_CF
66,005
def bestIndividual(hof, X, y): """ Get the best individual """ _individual = None minAccurcy = 2.0 for individual in hof: # if (individual.fitness.values > maxAccurcy): if individual.fitness.values[0] < minAccurcy: minAccurcy = individual.fitness.values[0] ...
66,006
def clean_phone(phone_number, drop_invalid=False, area_code='406'): """Standardizes phone number formatting for American numbers""" # Removes non-digit characters clean_number = digit_only(phone_number) # Removes US country code if present if len(clean_number) == 11 and clean_number[0] == '1':...
66,007
def create_person(person_dto): """ Create a new user from provided data transfer object. :param person_dto: Data transfer object to convert from. :type person_dto: PersonDto :returns: (PersonDto, id) """ # TODO: implement duplicate check -- need another unique identifier for people pr...
66,008
def show_user_status(): """Return True if the application is configured to use the user_status block""" return _django_status_enabled() or _ceda_status_enabled()
66,009
def split_dataset(df, train_proportion, valid_proportion): """Split a dataframe into a train, validation, and test set. The size of the test set will be 1.0 minus the given train and valid proportion. Parameters df - pandas.core.frame.DataFrame The dataframe to split train_propo...
66,010
def get_crawl_rate(): """Get the rate used to crawl Parameters ---------- None Returns ------- float The current web crawling rate """ return GLContainer.get_crawl_rate()
66,011
def and_(*validation_func # type: ValidationFuncs ): # type: (...) -> Callable """ An 'and' validator: it returns `True` if all of the provided validators return `True`, or raises a `AtLeastOneFailed` failure on the first `False` received or `Exception` caught. Note that an implicit `and_...
66,012
def config_get_state_power_on(config): """Get command/result on.""" return config[CONF_STATE][STATE_ON]
66,013
def addr_entry(key): """querries the user for address data, cleans it""" # getting the input rawline = input( 'please enter ' + key + ': ' ) # get rid of trailing whitespace line = rawline.strip() # replace tabs line = line.replace('\t', ' ') # remove forbidden strings ...
66,014
def process_validate_module(event_obj: Event, step_execution_id: Union[int, Type[int]]) -> bool: """ Process validate_cryton_module :param event_obj: Event object :param step_execution_id: Step execution ID :return: True or False, depending on validity of module """ logger.logger.debug("Proc...
66,015
def extract_neighborhood_sets( o1: torch.Tensor, o2: torch.Tensor, s1: torch.Tensor, s2: torch.Tensor, dist1: torch.Tensor, im1seeds: torch.Tensor, im2seeds: torch.Tensor, k1: torch.Tensor, k2: torch.Tensor, R1: float, R2: float, fnn12: torch.Tensor, ORIENTATION_THR: float, SCALE_RATE_TH...
66,016
def parse_arguments(): """ Read in the config file specifying all of the parameters """ parser = argparse.ArgumentParser(description="Learn subgraph embeddings") parser.add_argument("-config_path", type=str, default=None, help="Load config file") args = parser.parse_args() return args
66,017
def main(): """ Runs data processing scripts to turn raw data from (../raw) into cleaned data ready to be analyzed (saved in ../processed). """ logger = logging.getLogger(__name__) logger.info('Checking data-folder') if not os.path.exists('data'): create_data_directory() url = ...
66,018
def calculate_l2r_matrix(left_extrinsics: np.ndarray, right_extrinsics: np.ndarray) -> np.ndarray: """ Return the left to right transformation matrix: l2r = R * L^-1 """ l2r = np.matmul(right_extrinsics, np.linalg.inv(left_extrinsics)) return l2r
66,019
def load_data(messages_filepath, categories_filepath): """ Load messages and categories from dataset Args: message_filepath(string): the file path of messages.csv categories_filepath(string): the file path of categories.csv Return: df(Dataframe): merged dataframe of message...
66,020
def test_url_validation_with_none(): """ Test with invalid None URL""" schema = Schema({"url": Url()}) try: schema({"url": None}) except MultipleInvalid as e: assert_equal(str(e), "expected a URL for dictionary value @ data['url']") else: assert False, "D...
66,021
def at_exit_callback(pending: int, timeout: float) -> None: """Don't be loud about sentry, our customer doesn't care about it.""" def echo(msg): # type: (str) -> None sys.stderr.write(msg + "\n") if pending > 0: echo("Sentry is attempting to send %i pending error messages" % pendin...
66,022
def total_units_given(type_, value, start, end): """ Find total units given for a dose """ if type_ in [DoseType.bolus, DoseType.suspend]: return value return value * hours(end, start)
66,023
def process_season_matches(season_matches_df): """Processes raw season match data into parsable match and table data. :param season_matches_df: Dataframe as returned by get_season_matches function :return: 3 dataframes: expanded_df with match info, table_df with match outcome info, and grouped_table_df ...
66,024
def decode_argument_value(name, value): """ Decodes the value of an argument. The value is assumed to be Base64 encoded :param name: The name of the argument that is being decoded :param value: The encoded value of the argument. It is assumed to be Base64 encoded :return: The decoded value of the ...
66,025
def learn(env, sess, episodes, buffer_size, reward_discount, dis, dis_copy, gen, learning_rate=0.0005, optimizer=tf.train.RMSPropOptimizer, n_dis=1, n_gen=1, lambda_=0, batch_size=64, ...
66,026
def _lr(k, x, size): """Helper function to fit one gene""" ashr = rpy2.robjects.packages.importr('ashr') lam = x / size if np.isclose(lam.min(), lam.max()): return k, 0 else: res0 = scmodes.ebpm.ebpm_unimodal(x, size) res1 = scmodes.ebpm.ebpm_npmle(x, size) return k, np.array(res1.rx2('loglik'...
66,027
def email_notification_handler(sender, instance, created, **kwargs): """ notification handler for emails """ user = instance.recipient recipient = User.objects.get(email=user) if recipient.email_notification_subscription is False: return description = instance.description token =...
66,028
def get_text_from_image(input_file: str, lang: str = "eng", tessdata_prefix: str = "") -> str: """ Get text from image using Tesseract OCR. Parameters ---------- input_file : str lang : str | Language which will Tesseract use for OCR. Avai...
66,029
def create_msms_dataframe(df): """ create a dataframe organized into spectra from a raw dataframe of points """ #removed polarity and hdf5_file if 'precursor_MZ' in df.columns: grouped = df.groupby(['precursor_MZ','rt','precursor_intensity','collision_energy']).aggregate(lambda x: tuple(x)) ...
66,030
def penn_to_wn(tag): """ Convert PENN to WordNet Format Args: tag (str): PENN Tag Returns: str: Wordent Representation """ try: if tag.startswith('J'): return wn.ADJ elif tag.startswith('N'): return wn.NOUN elif tag.startswith('...
66,031
def add_landingpage_on_nav_page(sender, request=None, **kwargs): """ Receive the 'nav_organizer' signal which triggers when controlling an organization.\n If this signal occurs, the 'Landing Page' tab will be added to the menu bar on the left side.\n With the added tab you'll have access to the Landi...
66,032
def process_code_blocks(filestr, code_style, format): """Process a filestr with code blocks Loop through a file and process the code it contains. :param str filestr: text string :param str code_style: optional typesetting of code blocks :param str format: output formatting, one of ['html', 'latex',...
66,033
def vgg_net(): """ https://arxiv.org/pdf/1409.1556.pdf """ _log.info('Building the model') model = Sequential() _mult_conv_max(model, nb_conv=2, nb_filter=64) _mult_conv_max(model, nb_conv=2, nb_filter=128) _mult_conv_max(model, nb_conv=3, nb_filter=256) _mult_conv_max(model, nb_conv...
66,034
def grayscale(im, amount=1): """Converts image to grayscale. A grayscale operation is equivalent to the following matrix operation: | R' | |0.2126+0.7874g 0.7152-0.7152g 0.0722-0.0722g 0 0 | | R | | G' | |0.2126-0.2126g 0.7152+0.2848g 0.0722-0.0722g 0 0 | | G | | B' | = |0.2126...
66,035
def bar_chart(**kwargs): """ An example of a bar chart Args **kwargs lets you pass arguments into this function """ years = [str(year) for year in range(2010, 2021)] visitors = [1241, 50927, 162242, 222093, 665004, 2071987, 2460407, 3799215, ...
66,036
def test_for_outputs(edgelists): """ Test that, within the output directory on this subject, there is a graph. """ assert edgelists
66,037
def splitname(name, strict_mode=True): """ Break a name into its constituent parts: First, von, Last, and Jr. :param string name: a string containing a single name :param Boolean strict_mode: whether to use strict mode :returns: dictionary of constituent parts :raises `customization.InvalidName...
66,038
def _gen_image(num_per_item, _list, is_covers=True, _min=None, images_list=None): """ Generate n image for each item in _list or random between _min and num_per_item, because url images are unique, it accepts list of image object (return from SQLAlchemy query) to avoid duplicate with existed images ...
66,039
def parse_line(line, create_organizations=False, broker=None, using='default'): """ Parse an (organization, account, amount) triplet. """ unit = None amount = 0 look = re.match(r'\s+(?P<tags>\w(\w|:)+)(\s+(?P<amount>.+))?', line) if look: organization_slug = broker account_pa...
66,040
def arikan_gen(n): """ The n-th kronecker product of [[1, 1], [0, 1]], commonly referred to as Arikan's kernel. Parameters ---------- n: int log2(N), where N is the block length Returns ---------- ndarray<int> polar code generator matrix """ F = np.array([[1, ...
66,041
def check_user_answer(user_answer, calculated_answer): """ This method checks the user's answer with the calculated answer. Args: user_answer (Union[str, int, float, List[Union[int, float]]]): The user's answer. calculated_answer (Union[str, int, float, List[Union[int, float]]]): ...
66,042
def remove_dir(dir_path): """remove dir""" if os.path.exists(dir_path) and os.path.isdir(dir_path): # 如果文件夹存在 shutil.rmtree(dir_path) logger.info("delete file {}".format(dir_path)) return True else: return False
66,043
def segment_sentence(bestprecodetree,roottree,bestsuffcodetree,bestpostcodetree,bestendcodetree,bestvocab, sentence,marker1,marker2,mode=0,generateroots=False,optmode=1,extramode=0,nentnums=[],nentsegs=[],verbose=False): """ Segment line of words (whitespace-tokenized string) with PRP encoding ...
66,044
def make_consensus( inpath: str, outpath: str, tag: str="um", max_distance: int=20, discard: bool=False, nworkers: int=8, queue_size: int=1000): """Run make consensus alignments.""" # prepare the queues to_workers = Queue(maxsize=queue_size) to_writer = Queue(maxsize=queue_size) ...
66,045
def feat_upsampling_nearest_neighbor(input_feat, up_shape, name='feat_upsampling'): """ nearest neighborhood upsampling Args: up_shape (list of length 2): upsampled shape """ with tf.name_scope(name): up_feat = tf.image.resize_nearest_neighbor( input_feat, (up_shape...
66,046
def open_url(url: str) -> StringIO: """Fetches a given URL synchronously. The download of binary files is not supported. To download binary files use :func:`pyodide.http.pyfetch` which is asynchronous. Parameters ---------- url : str URL to fetch Returns ------- io.StringIO...
66,047
def snapshot(topmost_frame, stack_method="direct"): """ Snapshots the frame stack starting from the frame provided. Parameters ---------- topmost_frame : FrameObject Topmost frame. stack_method : {None, "direct", "predict"} Method to use for the stack: * "direct": ma...
66,048
def get_replaced_all_jokers_hands(hand): """ Заменяем обоих джокеров и возвращаем общий список замен :param hand: исходная рука :return: """ replaced_joker_hands = [] replaced_black_joker_hands = get_replaced_joker_hands( hand, LIST_BLACK_CARD, '?B' ) for replaced_black_joke...
66,049
def walk_azure(base_path, azure_data_store, token, include_regexp=".*", exclude_regexp="a^"): """Walks azure datalake "azure_data_store" in a depth-first fashion from base_path, yielding files which match include_re AND not match exclude_re""" logger.debug("Starting a azure walk with base_path: {} on data...
66,050
def clear_all_submissions(): """ Removes all submissions from the database. """ db = api.common.get_conn() db.submissions.remove()
66,051
def test_proxy_arp(proxy_arp_enabled, ip_and_intf_info, ptfadapter, packets_for_test): """ Send an ARP request or neighbor solicitation (NS) to the DUT for an IP address within the subnet of the DUT's VLAN. DUT should reply with an ARP reply or neighbor advertisement (NA) containing the DUT's own MAC "...
66,052
def plot_hist( data, bins: int = None, density: bool = True, kde: bool = False, title: str = None, ylabel: str = None, xlabel: str = None, save: str = None, show: bool = False, ): """Plot a histogram and optionally a KDE of given data.""" _, x, _ = plt.hist(data, bins=bins, d...
66,053
def create_test_file(): """Create a file containing all the tests we need to run for the CI""" branches = run_git_command("git branch") branch_name_reg = re.search("\* (.*)", branches) branch_name = branch_name_reg.group(1) print("Getting changed files from the branch: {0}".format(branch_name)) ...
66,054
def step(t, n, initial, after, seed=1, dt=0.05): """Simulates for n generators for t ms. Step at t/2.""" nest.ResetKernel() nest.SetStatus([0], [{"resolution": dt}]) nest.SetStatus([0], [{"grng_seed": 256 * seed + 1}]) nest.SetStatus([0], [{"rng_seeds": [256 * seed + 2]}]) g = nest.Create('sin...
66,055
def harmonic_epmi_score(pdict, wlist1, wlist2): """ Calculate harmonic mean of exponentiated PMI over all word pairs in two word lists, given pre-computed PMI dictionary - If harmonic ePMI is undefined, return -inf """ total_recip_epmi = None # Number of pairs for which PMI exists N...
66,056
def datafiles(request, tmpdir): """ pytest fixture to define a 'tmpdir' containing files or directories specified with a 'datafiles' mark. """ entry_list = [] options = { 'keep_top_dir': False, 'on_duplicate': 'exception', # ignore, overwrite } for mark in request.no...
66,057
def _mc_data_config(H, psi0, h_stuff, c_ops, c_stuff, args, e_ops, options, config): """Creates the appropriate data structures for the monte carlo solver based on the given time-dependent, or indepdendent, format. """ if debug: print(inspect.stack()[0][3]) config.soft_...
66,058
def get_paramvals_percentile(mcmc_table, pctl, chi2, randints_df=None): """ Isolates 68th percentile lowest chi^2 values and takes random 100 sample Parameters ---------- mcmc_table: pandas.DataFrame Mcmc chain dataframe pctl: int Percentile to use chi2: array Arra...
66,059
def parse_origin(url): """ Return the origin of a URL or None if empty or invalid. Per https://tools.ietf.org/html/rfc6454#section-7 : Return ``<scheme> + '://' + <host> + <port>`` for a URL. :param url: URL string :rtype: str or None """ if url is None: return None pa...
66,060
def _load_data(): """Loads allomorphic particles and number words from :file:`data.json`.""" import json import os with open(os.path.join(os.path.dirname(__file__), 'data.json')) as f: data = json.load(f) # register allomorphic particles for forms in data['allomorphic_particles'].iterval...
66,061
def main(): """ Main execution """ # Set up connection to Postgres DB # engine = create_engine("postgresql://postgres:dfdk#418!@@34.74.173.183/postgres") # c = engine.connect() # conn = c.connection # Read data into memory - Add SQL pulls if driver.PULL_SQL: print("Not hooke...
66,062
def optional_apply(f, value): """ If `value` is not None, return `f(value)`, otherwise return None. >>> optional_apply(int, None) is None True >>> optional_apply(int, '123') 123 Args: f: The function to apply on `value`. value: The value, maybe None. """ if value is...
66,063
def scatter(xdata, ydata, backend=None, data=None, **kwargs): """ Plot the provided data as a scatter plot. Varying size and color are possible. Multiple data sets are possible :param xdata: data for the x-axis :param xdata: data for the y-axis :param data: source for the data of the plot (opti...
66,064
def repl_func(m): """process regular expression match groups for word upper-casing problem""" return m.group(1) + m.group(2).upper()
66,065
def build(data): """Build a binary tree using the leetcode data format. TODO Add description for leetcode data format. :param str|list data: :return: root node of the binary tree. """ values = json.loads(data) if isinstance(data, str) else data if not values: return None root ...
66,066
def make_email(to, cc=None, bcc=None, subject=None, body=None): """\ Encodes either a simple e-mail address or a complete message with (blind) carbon copies and a subject and a body. :param to: The email address (recipient). Multiple values are allowed. :type to: str or iterable of strings :par...
66,067
def invoke_gate(a, b): """Function modelling one input (a) invoking a second input (b). If the invoking is at either -1,0,1 the output is also at that value. The second input can only modify the output between those values. Args: a (float): invoking input b (float): second input ...
66,068
def plotGuitarShape(): """ Plots the Les Paul guitar shape with matplotlib """ with open('guitarShape.pkl','rb') as inFile: guitarShape = pickle.load(inFile) for index, row in enumerate(guitarShape): print(list(row).count(1)) if index == 10: print('====...
66,069
def cosine_similarity( X, Y=None, dense_output=True, use_float=False, approx_size=1.0, compression_rate=1.0, blas="default", ): """Compute cosine similarity between samples in X and Y. Cosine similarity, or the cosine kernel, computes similarity as the normalized dot product of X...
66,070
def test_dichotomous_scores(dichotomous_Contingency_1d, method, expected): """Test score for simple 2x2 contingency table against hand-computed values Scores are for H/TP: 2, M/FN: 2, FA/FP: 1, CN/TN: 2 """ xs_score = getattr(dichotomous_Contingency_1d, method)().item() npt.assert_almost_equal(xs_sc...
66,071
def cdlhikkakemod(opn, high, low, close): """Modified Hikkake Pattern: The modified hikkake pattern is a less frequent variant of the basic hikkake pattern and is viewed as a reversal pattern. The concept of the modified version is similar to the basic version, except that a "context bar" is used prior...
66,072
def create_c2pc_data(fovs, pixel_consensus_path, cell_table_path, pixel_cluster_col='pixel_meta_cluster_rename'): """Create a matrix with each fov-cell label pair and their SOM pixel/meta cluster counts Args: fovs (list): The list of fovs to subset on pixel_cons...
66,073
def coffee(): """About page.""" return render_template('public/coffee.html')
66,074
def main(): """Make a jazz noise here""" args = get_args() players = ['X', 'O'] initial_state = {'cells': list('-' * 9), 'player': players[0]} wins = {'X': 0, 'O': 0, 'Draw': 0} state = copy.deepcopy(initial_state) print_board(state['cells']) while (True): move = input('Player {...
66,075
def after_request(response): """log details on the request and its served response""" __log__.info('%s - "%s %s %s" %s -', request.remote_addr, request.method, request.full_path, request.environ.get('SERVER_PROTOCOL'), response.status_code) return response
66,076
def test_assert_against_cache(test_data, assert_against_cache): """Test edge cases for assert_against_cache.""" assert_against_cache(test_data)
66,077
def average_infid_set(U_dict: dict, index, dims, eval, proj=True): """ Mean average fidelity over all gates in U_dict. Parameters ---------- U_dict : dict Contains unitary representations of the gates, identified by a key. index : int Index of the qubit(s) in the Hilbert space t...
66,078
async def read(id: int, auth_data: dict = Depends(get_auth_data)): """ 读取组织数据详情 :param id: 组织id :return: 组织详情结构 """ resp = OrgRespDetailSchema() resp.detail = OrgService(auth_data).read(id) return resp
66,079
def RAND(*args) -> Function: """ Returns a random number between 0 inclusive and 1 exclusive. Learn more: https//support.google.com/docs/answer/3093438 """ return Function("RAND", args)
66,080
def get_channel_status_bulk(request): """ Create the channel node """ data = json.loads(request.body) try: statuses = {cid: get_status(cid) for cid in data['channel_ids']} return HttpResponse(json.dumps({ "success": True, 'statuses': statuses, })) except...
66,081
def ebay_invoice_export(config_file): """ Export eBay invoice transactions from a downloaded CSV to a format that can be imported into GnuCash. The downloaded CSV is renamed with the end date of the applicable month and filed in the eBay folder in Finance. The file for export to GnuCash is save to invo...
66,082
def test_list_decimal_white_space_nistxml_sv_iv_list_decimal_white_space_1_2(mode, save_output, output_format): """ Type list/decimal is restricted by facet whiteSpace with value collapse. """ assert_bindings( schema="nistData/list/decimal/Schema+Instance/NISTSchema-SV-IV-list-decimal-whiteS...
66,083
def GetChainAloneResidueTypesStatus(FileIndex, ChainID): """Get status of residue types for chain alone object.""" Status = OptionsInfo["InfilesInfo"]["SpecifiedChainsAndLigandsInfo"][FileIndex]["ResidueTypesChain"][ChainID] return Status
66,084
def build_stubs(): """ Build the stubs for the .NET "System" package. """ # System system_stubs_dir = PathPlus("System-stubs") system_stubs_dir.maybe_make() make_package( "System", System, [ "TypeCode", "Predicate", "TimeSpan", "ModuleHandle", "Delegate", "IAsyncResult", ...
66,085
def run_3gpp_tests( setup, key_filename=DEFAULT_KEY_FILENAME, test_files=NG40_TEST_FILES ): """ Run teravm s6a and gxgy test cases. Usage: 'fab run_3gpp_tests:' for default key filename and default test files. key_filename: path to where the private key is for authorized-key based ssh. The ...
66,086
def setup_startup_scripts(): """Manages installation of avalon's TB_sceneOpened.js for Harmony launch. If a studio already has defined "TOONBOOM_GLOBAL_SCRIPT_LOCATION", copies the TB_sceneOpened.js to that location if the file is different. Otherwise, will set the env var to point to the avalon/harmon...
66,087
def test_db_dns(): """Verify we get IP for DB server.""" # getaddrinfo works for IPv4 and v6 try: gai = socket.getaddrinfo("db", "5000") except: pytest.fail('getaddrinfo() failed for db', pytrace=False) assert len(gai) > 0
66,088
def save_expression_data(analysis_name, expression_data): """ Save expression data to results/expression-data.csv. :param analysis_name: :param expression_data: :return: """ analysis_expression_data_path = utils.get_path(f"analyses/{analysis_name}/results/expression-data.csv") with open(analysis_expression_data...
66,089
def iter_rows(node, style, extra=()): """ Create rows from children of given node. """ yield Row.from_node(node, style, extra) children = node.children if children: last_idx = len(children) - 1 for idx, child in enumerate(children): yield from iter_rows(child, style, ...
66,090
def gameOver(currentBoard,typeCurrentPlayer): """ Function that checks if the game is over in the current board Parameters : -currentBoard : the current board -typeCurrentPlayer : type of the current player Returns : - [True, game over message] if the game is over - [Fals...
66,091
def task_table(request): """ ProductionTask table :return: table page or data for it """ last_task_submit_time = ProductionTask.objects.order_by('-submit_time')[0].submit_time return TemplateResponse(request, 'prodtask/_task_table.html', { 'title': 'Production Tasks Table', ...
66,092
def user_files(): """ This route renders a file-upload page for users. Not logged-in users (anonymous): > request that they login logged-in users (anonymous): > list files they own > show file-upload box The file-upload and download API uses has...
66,093
def update_meta_sheet_feeders(self, puzzle_id) -> None: """ Updates the input meta puzzle's spreadsheet with the latest feeder puzzle info """ meta_puzzle = Puzzle.objects.get(pk=puzzle_id) if not meta_puzzle.is_meta or not meta_puzzle.sheet: return logger.info( "Starting up...
66,094
def prod(F, E): """Check that the factorization of P-1 is correct. F is the list of factors of P-1, E lists the number of occurrences of each factor.""" x = 1 for y, z in zip(F, E): x *= y**z return x
66,095
def blackbox_c(a_qc): """Constant function""" #a_qc.iden(0) if random.random() > 0.5: print("Constant function: returns always 0") a_qc.iden(1) else: print("Constant function: returns always 1") a_qc.iden(1)
66,096
def _parse_common(raw_object: RawObject) -> TiledObject: """Create an Object containing all the attributes common to all types of objects. Args: raw_object: Raw object to get common attributes from Returns: Object: The attributes in common of all types of objects """ common = Tile...
66,097
def load_file(fname, force_reload=False, **kwargs): """Load a file Parameters: fnames (list): single file name, or list of files that are part of the same time series. Glob patterns and slices are accepted, see :doc:`/tips_and_tricks` for more info. fname (str): a file n...
66,098
def handle_user_input(loop, client): """reads from stdin in separate thread if user inputs 'quit' stops the event loop otherwise just echos user input """ # When new/unknown user joins while not client.is_logged_in: # Set up JSON login message with dictionary login_data = {"USER...
66,099