content
stringlengths
22
815k
id
int64
0
4.91M
def build_get_string_with_null_request( **kwargs # type: Any ): # type: (...) -> HttpRequest """Get string dictionary value {"0": "foo", "1": null, "2": "foo2"}. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code flow. :return: Retur...
5,335,400
def get_db_url(db_host, db_name, db_user, db_pass): """ Helper function for creating the "pyodbc" connection string. @see /etc/freetds.conf @see http://docs.sqlalchemy.org/en/latest/dialects/mssql.html @see https://code.google.com/p/pyodbc/wiki/ConnectionStrings """ params = parse.quote( ...
5,335,401
def do_md_tag_update(gc, args): """Rename a metadata definitions tag inside a namespace.""" name = args.name.strip() if name: fields = {'name': name} new_tag = gc.metadefs_tag.update(args.namespace, args.tag, **fields) _tag_show(new_tag) e...
5,335,402
def boxes_iou3d_cpu(boxes_a, boxes_b, box_mode='wlh', rect=False, need_bev=False): """ Input (torch): boxes_a: (N, 7) [x, y, z, h, w, l, ry], torch tensor with type float32 boxes_b: (M, 7) [x, y, z, h, w, l, ry], torch tensor with type float32 rect: True/False means boxes in camera/velod...
5,335,403
def make_attrstring(attr): """Returns an attribute string in the form key="val" """ attrstring = ' '.join(['%s="%s"' % (k, v) for k, v in attr.items()]) return '%s%s' % (' ' if attrstring != '' else '', attrstring)
5,335,404
def distribute( computation_graph: ComputationGraph, agentsdef: Iterable[AgentDef], hints=None, computation_memory: Callable[[ComputationNode], float] = None, communication_load: Callable[[ComputationNode, str], float] = None, ) -> Distribution: """ gh-cgdp distribution method. Heuristi...
5,335,405
def LinearScaling(pop): """ Linear Scaling scheme .. warning :: Linear Scaling is only for positive raw scores """ logging.debug("Running linear scaling.") pop.statistics() c = Consts.CDefScaleLinearMultiplier a = b = delta = 0.0 pop_rawAve = pop.stats["rawAve"] pop_rawMax = pop.stats["raw...
5,335,406
def depreciated_get_paste(paste_tup): """ This takes a tuple consisting of href from a paste link and a name that identify a pastebin paste. It scrapes the page for the pastes content. :param paste_tup: (string, string) :return: Paste if successful or False """ href, name = paste_tup #...
5,335,407
def delete_nodes_list( nodes: List[str], credentials: HTTPBasicCredentials = Depends( check_credentials ), # pylint: disable=unused-argument ) -> Dict[str, str]: """Deletes a list of nodes (that are discoverables with lldp) to the db. Exple of simplest call : curl -X DELETE --user u:p ...
5,335,408
def index(): """ Application Home page """ module_name = settings.modules[c].get("name_nice") response.title = module_name return {"module_name": module_name, }
5,335,409
def handle_option_error(error): """Raises exception if error in option command found. In tmux 3.0, show-option and show-window-otion return invalid option instead of unknown option. See https://github.com/tmux/tmux/blob/3.0/cmd-show-options.c. In tmux >2.4, there are 3 different types of option errors...
5,335,410
def image_click_xshift(axes = "gca"): """ Takes a starting and ending point, then shifts the image y by this amount """ if axes == "gca": axes = _pylab.gca() try: p1 = ginput() p2 = ginput() xshift = p2[0][0]-p1[0][0] e = axes.images[0].get_extent() e[0] =...
5,335,411
def download_abstruse_goose(program_abs_path, abstruse_page_num): """Downloads latest Abstruse Goose comics.""" # Create/change appropriate comic folder. comic_folder = os.path.join(program_abs_path, "abstruse") if os.path.exists(comic_folder): os.chdir(comic_folder) else: os.mkdir(c...
5,335,412
def is_CW_in_extension(G): """ Returns True if G is 'CW in expansion', otherwise it returns False. G: directed graph of type 'networkx.DiGraph' EXAMPLE >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> G=nx.DiGraph() e_list = [(0,1),(0,2),(0,3),(0,4),(1,2),(1,3),(1,4)] G.add_edges_fro...
5,335,413
def get_index_where(condition: Callable[..., bool], iterable: Iterable) -> List[int]: """Return index values where `condition` is `True`.""" return [idx for idx, item in enumerate(iterable) if condition(item)]
5,335,414
def geom_crossbar(mapping=None, *, data=None, stat=None, position=None, show_legend=None, sampling=None, tooltips=None, fatten=None, **other_args): """ Display bars with horizontal median line. Parameters ---------- mapping : `FeatureSpec` Set of aestheti...
5,335,415
def _save_user_contributions(user_contributions): """Commits a user contributions object to the datastore.""" user_contributions.validate() user_models.UserContributionsModel( id=user_contributions.user_id, created_exploration_ids=user_contributions.created_exploration_ids, edited_e...
5,335,416
def chess_to_coordinate(pos: str) -> Union[Coordinate, Move]: """ Arguments: """ if len(pos) == 2: return Coordinate(int(pos[1]) - 1, file_dict[pos[0]]) else: if len(pos) == 5: if pos[4] == 'n': return Move(Coordinate(int(pos[1]) - 1, file_dict[...
5,335,417
def main(): """ Main entry point for module execution :returns: the result form module invocation """ required_if = [ ("state", "merged", ("config",)), ("state", "replaced", ("config",)), ("state", "rendered", ("config",)), ("state", "overridden", ("config",)), ...
5,335,418
def get_db_session(): """ Get the db session from g. If not exist, create a session and return. :return: """ session = get_g_cache('_flaskz_db_session') if session is None: session = DBSession() set_g_cache('_flaskz_db_session', session) return session
5,335,419
def make_tril_scale( loc=None, scale_tril=None, scale_diag=None, scale_identity_multiplier=None, shape_hint=None, validate_args=False, assert_positive=False, name=None): """Creates a LinOp representing a lower triangular matrix. Args: loc: Floating-point `Tensor`. This is used f...
5,335,420
def remove_punctuation(word): """Remove all punctuation from the word (unicode). Note that the `translate` method is used, and we assume unicode inputs. The str method has a different `translate` method, so if you end up working with strings, you may want to revisit this method. """ return word....
5,335,421
def run_no_arg(): """ runs code without giving any arguments """ print("Welcome to the Pokey Setup Script Interpreter!") print("For easier access to the interpreter, use the command line entry. See github page for details.") print("Anyway, where is your setup script located?") pssFileLocatio...
5,335,422
def test_tag_propagation(pcluster_config_reader, clusters_factory, scheduler, os): """ Verify tags from various sources are propagated to the expected resources. The following resources are checked for tags: - main CFN stack - head node - head node's root EBS volume - compute node (traditio...
5,335,423
def run(args): """Construct an instance of Compare_IsoSeq_Runs and do the comparison.""" with CompareReferenceTranscripts(isoseq_output_fn=args.isoseq_output_fn, reference_transcripts_fn=args.reference_transcripts_fn, output_analysis_fn=a...
5,335,424
def prepare_filter_weights_slice_conv_2d(weights): """Change dimension order of 2d filter weights to the one used in fdeep""" assert len(weights.shape) == 4 return np.moveaxis(weights, [0, 1, 2, 3], [1, 2, 0, 3]).flatten()
5,335,425
async def hello(request): """Hello page containing sarafan node metadata. `version` contains sarafan node version. `content_service_id` — contains service_id of content node :param request: :return: """ return web.json_response(await request.app['sarafan'].hello())
5,335,426
def missing_toolchain(triplet: str) -> bool: """ Checks whether gcc, g++ and binutils are installed and in the path for the current triplet :param triplet: a triplet in the form riscv64-linux-gnu :return: True if some part of the toolchain is missing, False otherwise """ toolchain_expected =...
5,335,427
def load_capabilities( base: str = "docassemble.ALWeaver", minimum_version="1.5", include_playground=False ): """ Load and return a dictionary containing all advertised capabilities matching the specified minimum version, and optionally include capabilities that were advertised from a namespace matc...
5,335,428
def build_graph( config, train_input_fn, test_input_fn, model_preprocess_fn, model): """Builds the training graph. Args: config: Training configuration. train_input_fn: Callable returning the training data as a nest of tensors. test_input_fn: Callable returning the test data as a nest of tensor...
5,335,429
def execli_deco(): """ This is a decorating function to excecute a client side Earth Engine function and retry as many times as needed. Parameters can be set by modifing module's variables `_execli_trace`, `_execli_times` and `_execli_wait` :Example: .. code:: python from geetools.tool...
5,335,430
def on_click_add(event): """Add paper to file cof-papers.csv: botton will turn red if something is missing or paper already present.""" if not (inp_paper_id.value and inp_reference.value and inp_doi.value and inp_title.value) or \ "(already present)" in inp_paper_id.value or \ "ERROR" in inp_paper...
5,335,431
def new_canvas(): """ Creates a new canvas for user """ pass
5,335,432
def lstm_with_backend_selection(inputs, init_h, init_c, kernel, recurrent_kernel, bias, mask, time_major, go_backwards, sequence_lengths, zero_output_for_mask): """Call the LSTM with optimized backend kernel selection. ...
5,335,433
def upgrade(version, verbose): """Upgrade the database to a version""" _sync_migrate(version, downgrade=False, verbose=verbose) click.echo('Upgrade successful! <3')
5,335,434
async def cname(ctx, *, nn : str): """Change the name of the bot""" await bot.edit_profile(username = nn) await bot.say('Done.')
5,335,435
def _build_stack_from_3d(recipe, input_folder, fov=0, nb_r=1, nb_c=1): """Load and stack 3-d tensors. Parameters ---------- recipe : dict Map the images according to their field of view, their round, their channel and their spatial dimensions. Only contain the keys 'fov', 'r', '...
5,335,436
def view_menu(request): """Admin user view all the reservations.""" menus = Menu.objects.all() return render(request, "super/view_menu.html", {'menus': menus})
5,335,437
def _get_hdfs_dirs_by_date(physical_table_name, date): """ 根据日期获取指定日期的hdfs上数据目录列表 :param physical_table_name: 物理表名称 :param date: 日期 :return: hdfs上的数据目录列表 """ return [f"{physical_table_name}/{date[0:4]}/{date[4:6]}/{date[6:8]}/{hour}" for hour in DAY_HOURS]
5,335,438
def InstallDTBO(DTBO): """Install Dtbo using dd cmd DTBO : name of DTBO """ # Build file using mkdir GetCmdReturn('sudo mkdir -p \ /sys/kernel/config/device-tree/overlays/$DTBO') # Install dtbo using dd DTBO_PATH = DTBO + '.dtbo' GetCmdReturn('sudo dd \ of=/sys/kernel/con...
5,335,439
def indeed_jobs(request, category_id): """ Load Indeed jobs via ajax. """ if request.is_ajax() and request.method == 'POST': per_page = 10 page = 1 html = [] if category_id == '0': all_jobs = IndeedJob.objects.all() else: all_jobs = Indee...
5,335,440
def iinsertion_sort(arr, order=ASCENDING): """Iterative implementation of insertion sort. :param arr: input list :param order: sorting order i.e "asc" or "desc" :return: list sorted in the order defined """ operator = SORTING_OPERATORS.get(order.lower(), GREATER_THAN) for i in range(1, len(...
5,335,441
def actor_files_paths(): """ Returns the file paths that are bundled with the actor. (Path to the content of the actor's file directory). """ return current_actor().actor_files_paths
5,335,442
def parse_table(data: bytes, fields: list) -> dict: """Return a Python dictionary created from the bytes *data* of an ISIS cube table (presumably extracted via read_table_data()), and described by the *fields* list and *records*. Please be aware that this does not perform masking of the ISIS specia...
5,335,443
def gridtilts(shape, thismask, slit_cen, coeff2, func2d, spec_order, spat_order, pad_spec=30, pad_spat = 5, method='interp'): """ Parameters ---------- tilt_fit_dict: dict Tilt fit dictioary produced by fit_tilts Returns ------- piximg: ndarray, float Image indicating how sp...
5,335,444
def exp_t(u, t): """Compute exp_t for `u`.""" def _internal_exp_t(u, t): return tf.nn.relu(1.0 + (1.0 - t) * u) ** (1.0 / (1.0 - t)) return tf.cond( tf.math.equal(t, 1.0), lambda: tf.math.exp(u), functools.partial(_internal_exp_t, u, t))
5,335,445
def max_matching(G, method="ilp"): """Return a largest matching in *G*. Parameters ---------- G : NetworkX graph An undirected graph. method: string The method to use for finding the maximum matching. Use 'ilp' for integer linear program or 'bf' for brute force. Def...
5,335,446
def hasEdgeFlux(source, edgeDistance=1): """hasEdgeFlux Determine whether or not a source has flux within `edgeDistance` of the edge. Parameters ---------- source : `scarlet.Component` The source to check for edge flux edgeDistance : int The distance from the edge of the im...
5,335,447
def test_timestamp_rollback(version, intervals): """Test removing versions from a timestamp.""" ts = Timestamp(intervals=[[2, 3], [5, 7], 9, [11, 12]]) assert ts.rollback(version).is_equal(Timestamp(intervals=intervals))
5,335,448
def biswas_robustness(data_scikit, data_mm): """ summary stats on consensus peaks """ CV = find_CV(th=0.0001, ca=0.5, sd=1) CV_th001 = find_CV(th=0.001, ca=0.5, sd=1) CV_th01 = find_CV(th=0.01, ca=0.5, sd=1) CV_th00001 = find_CV(th=0.00001, ca=0.5, sd=1) CV_sd15 = find_CV(th=0.0001, ca=...
5,335,449
def get_click_offset(df): """ df[session_key] return a set of session_key df[session_key].nunique() return the size of session_key set (int) df.groupby(session_key).size() return the size of each session_id df.groupby(session_key).size().cumsum() retunn cumulative sum """ offsets = np.zeros(...
5,335,450
def store_attention_plots(attentions, targets, sources, output_prefix, idx): """ Saves attention plots. :param attentions: :param targets: :param sources: :param output_prefix: :param idx: :return: """ for i in idx: plot_file = "{}.{}.pdf".forma...
5,335,451
def test_agent_context_ledger_apis(): """Test that the ledger apis configurations are loaded correctly.""" private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") wallet = Wallet({'default': private_key_pem_path}) connections = [DummyConnection()] ledger_apis = LedgerApis({"fetchai": ('alp...
5,335,452
def build_crs_table(savepath): """ Build crs table of all equivalent format variations by scraping spatialreference.org. Saves table as tab-delimited text file. NOTE: Might take a while. Arguments: - *savepath*: The absolute or relative filepath to which to save the crs table, including the "....
5,335,453
async def claptext(memereview): """ Praise people! """ textx = await memereview.get_reply_message() message = memereview.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await memereview.edit("`Hah, I don't clap pointlessly!`") return...
5,335,454
def delete_enrichment(): """ Controller to delete all existing GO enrichments :return: Redirect to admin main screen """ CoexpressionCluster.delete_enrichment() flash('Successfully removed GO enrichment for co-expression clusters', 'success') return redirect(url_for('admin.controls.index')...
5,335,455
def get_all_permissions(context=None): """Get the ids of all defined permissions """ for id, permission in get_utilities_for(IPermission, context): if id != 'zope.Public': yield id
5,335,456
def evaluate_agent(agent, env, alpha, num_users=100, deterministic=False, softmax_temperature=1.0, scatter_plot_trajectories=False, figure_file_obj=None, risk_score_extractor=violence_risk, plot_histogram=False, plot_trajectories=True, ...
5,335,457
def argmax(sequence: Sequence) -> int: """Find the argmax of a sequence.""" return max(range(len(sequence)), key=lambda i: sequence[i])
5,335,458
def read_data_from_device(device, location): """ Reads text data from device and returns it as output Args: location ('str'): Path to the text file Raises: FileNotFoundError: File Does not Exist Returns: Data ('str'): Text data read from the device ...
5,335,459
def get_credentials() -> tuple: """Gets bot auth credentials from environment variables defined in the local .env file""" load_dotenv() irc_token = os.environ.get('TWITCH_OAUTH_PASS') client_id = os.environ.get('TWITCH_CLIENT_ID') channel = os.environ.get('TWITCH_CHANNEL') return irc_token, c...
5,335,460
def test_config_file(tmpdir): """Get options from a config file.""" config = str(tmpdir.join('mapbox.ini')) with open(config, 'w') as cfg: cfg.write("[mapbox]\n") cfg.write("access-token = pk.test_config_file\n") cfg.write("verbosity = 11\n") runner = CliRunner() result = run...
5,335,461
def postman_parser(postman_info: dict, environment_vars: Dict = None) -> APITest: """ Get a parser collection, in JSON input format, and parser it :param postman_info: JSON parsed info from Postman :type postman_info: dict :param environment_vars: variables to replace :type ...
5,335,462
def registerFont(faceName, afm, pfb): """ Helvetica BUT AS AFM The below section is NOT equal to:: _baseFontName ='Helvetica' _baseFontNameB ='Helvetica-Bold' _baseFontNameI ='Helvetica-Oblique' _baseFontNameBI='Helvetica-BoldOblique' we will ma...
5,335,463
def test_anti_periodic_bcs(): """test a simulation with anti-periodic BCs""" grid = grids.CartesianGrid([[-10, 10]], 32, periodic=True) field = ScalarField.from_expression(grid, "0.01 * x**2") field -= field.average # test normal periodic BCs eq1 = PDE({"c": "laplace(c) + c - c**3"}, bc="period...
5,335,464
def allOPT2 (routes, dists, maxtime=float("inf")): """ A simpler way to make the 2-OPT optimization on all the provided routes. :param routes: The routes to optimize. :param dists: The matrix of distances. :param maxtime: The maximum time the optimization can go on. :return: The optimised ...
5,335,465
def getScoreByName(name): """ This function will search for the name and will, if found, return the scores """ for idx, val in enumerate(names): if val == name: return scores[idx]
5,335,466
def validate_marginal(marg_type, marg_dict): """ convenience function which validates keys and values of a marginals dict with default kwargs :param marg_type: (str) one of the keys from marginals_template defined inside function :param marg_dict: (dict) dict representing the marginals for a single inde...
5,335,467
def count_dict(dict_): """ Count how many levels the dict has """ if not isinstance(dict_, dict): raise Dict_Exception("dict_ must be a dict") return max(count_dict(v) if isinstance(v, dict) else 0 for v in dict_.values()) + 1
5,335,468
def __draw_tick_labels(scales, chart_height, chart_width): """Draws the numbers in both axes.""" axis_values = [0, 0.25, 0.5, 0.75, 1] axis_df = pd.DataFrame({"main_axis_values": axis_values, "aux_axis_position": 0}) x_tick_labels = ( alt.Chart(axis_df) .mark_text( yOffset...
5,335,469
def HIP_to_HD(name): """Convert an HIP name in *Hipparcos Catalogue* to HD name in *Henry Draper Catalogue*. Args: name (str or int): Name of star in *Hipparcos Catalogue*. """ hip = _get_HIP_number(name) filename = os.path.join(xindex_path, 'HIP-HD.csv') f1 = lambda row: int(row....
5,335,470
def convert_torchscript_module_to_torch_backend_contract_mlir(program: torch.nn.Module): """Perform common lowering from TorchScript to Torch MLIR Returns an MLIR module that satisfies the Torch backend contract. """ mb = ModuleBuilder() scripted = torch.jit.script(program) class_annotator = Cl...
5,335,471
def thread_profile(D,P,inset,internal=True,base_pad=0.1): """ISO thread profile""" H = P*np.sqrt(3)/2 Dm = D - 2*5*H/8 Dp = D - 2*3*H/8 if internal: return np.array([ (-P/2,D/2+H/8+base_pad+inset), (-P/2,D/2+H/8+inset), (-P/8,Dm/2+inset), (P/8,...
5,335,472
def mock_session(monkeypatch, data): """ Mocked out sqlalchemy session """ if data: dirname = os.path.dirname(os.path.realpath(__file__)) filename = os.path.join(dirname, data) with open(filename) as data_file: json_data = json.load(data_file) predictions = json_data...
5,335,473
def plot_eigenvectors(*, obs_names, eigenvecs, fig_size=(8, 6), font_size=12, label_size=16, save_fig=False, write_path=None): """Plot eigenvectors of the covariance matrix of SV residuals. Produces a plot of the eigenvectors corresponding to the n largest eigenvalues of the covarianc...
5,335,474
def get_service(hass, config, discovery_info=None): """Get the HipChat notification service.""" return HipchatNotificationService( config[CONF_TOKEN], config[CONF_ROOM], config[CONF_COLOR], config[CONF_NOTIFY], config[CONF_FORMAT], config[CONF_HOST])
5,335,475
def connect_with_interior_or_edge_bulk( polygon: Polygon, polygon_array: GeometryArray ) -> List[bool]: """ Return boolean array with True iff polys overlap in interior/edge, but not corner. Args: polygon (Polygon): A shapely Polygon polygon_array (GeometryArray): The other shapely Poly...
5,335,476
def get_history(kmodel=None): """ returns a python dict with key = metric_id val = [metric each epoch ] """ # get kmodel object from input str if the input is a string if isinstance(kmodel,str): try: kmodel = KModel.objects.get(id=kmodel) except ObjectDoesNotExist: ...
5,335,477
def get_neighbor_v4_by_search(search=None): """Return a list of NeighborV4's by dict.""" try: objects = NeighborV4.objects.filter() search_dict = search if search else dict() object_map = build_query_to_datatable_v3(objects, search_dict) except FieldError as e: raise api_res...
5,335,478
def load_clean_data(): """funcion that loads tuberculosis file and preprocesses/cleans the dataframe""" df = pd.read_csv('tb.csv') # drop columns 'fu' and 'mu' since they only contain missing values and would mess up the following processing steps df = df.drop(columns = ['fu', 'mu']) # define row an...
5,335,479
def is_anagram_passphrase(phrase): """ Checks whether a phrase contains no words that are anagrams of other words. >>> is_anagram_passphrase(["abcde", "fghij"]) True >>> is_anagram_passphrase(["abcde", "xyz", "ecdab"]) False >>> is_anagram_passphrase(["a", "ab", "abc", "abd", "abf", "abj"]) ...
5,335,480
def _client_ip(client): """Compatibility layer for Flask<0.12.""" return getattr(client, 'environ_base', {}).get('REMOTE_ADDR')
5,335,481
def findtrapezoidfunc( thexvals, theyvals, thetoplength, initguess=None, debug=False, minrise=0.0, maxrise=200.0, minfall=0.0, maxfall=200.0, minstart=-100.0, maxstart=100.0, refine=False, displayplots=False, ): """ Parameters ---------- thexvals ...
5,335,482
def extractRecords(getRecordsResponse): """Returns a list of etrees of the individual records of a getRecords response""" recs = getRecordsResponse.xpath( '/csw:GetRecordsResponse/csw:SearchResults//csw:Record', namespaces={'csw': ns_csw}) return recs
5,335,483
def tagify(tail=u'', head=u'', sep=u'.'): """ Returns namespaced event tag string. Tag generated by joining with sep the head and tail in that order head and tail may be a string or a list, tuple, or Set of strings If head is a list, tuple or Set Then join with sep all elements of head indi...
5,335,484
def run_all(): """ Run all of the tests This function is useful in case we want to run our tests outside of the pytest framework. """ # since we are not running through pytest, we have to grab the inputs to the tests version = get_version() test_version(version) config = get_config() t...
5,335,485
def after_all(context): """ Function saves modified MARC record to file system :param context: behave context object """ marc_filename = open('modified-ybp-dda-for-ebl.mrc','wb') marc_filename.write(context.marc_record.as_marc()) marc_filename.close()
5,335,486
def get_fn_data(src_db, fn_table, year=None): """Get the data and fields from the query in the src database for the fish net table specified by fn_table. Returns list of dictionaries - each element represents a single row returned by the query. Arguments: - `src_db`: full path the source database....
5,335,487
def convert_example_to_feature(example, tokenizer, max_seq_length=512, doc_stride=384, max_query_length=125, is_training=True, cls_token_at_end=False, cls_token='[CLS]', sep_token='[SEP]', pad_token=0, ...
5,335,488
def notify(silent=False, **kwargs): """Helper method to send a notification.""" notification = Notification(**kwargs) # Validate channels for channel_alias in notification.channels: __validate_channel_alias(channel_alias) # If it's a not a silent notification, save the notification if ...
5,335,489
def make_pickle(golfed=False): """Returns the pickle-quine. If "golfed" is true, we return the minimized version; if false we return the one that's easier to understand. """ part_1 = b''.join(PART_1) part_2 = b''.join(GOLFED_PART_2 if golfed else PART_2) # We tack the length onto part 1: ...
5,335,490
def classify_design_space(action: str) -> int: """ The returning index corresponds to the list stored in "count": [sketching, 3D features, mating, visualizing, browsing, other organizing] Formulas for each design space action: sketching = "Add or modify a sketch" + "Copy paste sketch" 3...
5,335,491
def create(name, database=None, auto=False, auto_source=False, directory=None, migratetable=None, verbose=None): """Create a migration.""" router = get_router(directory, database, migratetable, verbose) if auto and auto_source: auto = auto_source router.create(name, auto=auto)
5,335,492
def get_sha256_hash(plaintext): """ Hashes an object using SHA256. Usually used to generate hash of chat ID for lookup Parameters ---------- plaintext: int or str Item to hash Returns ------- str Hash of the item """ hasher = hashlib.sha256() string_to_h...
5,335,493
def annexRepo__enable_remote(self, name, options=None, env=None): """Enables use of an existing special remote Parameters ---------- name: str name, the special remote was created with options: list, optional """ # MIH thinks there should be no `env` argument at all # https://gi...
5,335,494
def get_bit_coords(dtype_size): """Get coordinates for bits assuming float dtypes.""" if dtype_size == 16: coords = ( ["±"] + [f"e{int(i)}" for i in range(1, 6)] + [f"m{int(i-5)}" for i in range(6, 16)] ) elif dtype_size == 32: coords = ( ...
5,335,495
def create_record(user_inputs): """ Create a ObsRecord from the informations gathered from the users. :param user_inputs: Dictionary with all the values (as strings) required to fully populate a ObsRecord object. :type user_inputs: dict :rtype: ObsRecord object """ from klpyastro.ut...
5,335,496
def best_wild_hand(hand): """best_hand но с джокерами""" non_jokers = list(filter(lambda x: x[0] != '?', hand)) jokers = filter(lambda x: x[0] == '?', hand) jokers_variations = itertools.product( *[joker_variations(joker) for joker in jokers] ) best_hands = [] for variations in jok...
5,335,497
def GetTestMetadata(test_metadata_file=FAAS_ROOT+"/synthetic_workload_invoker/test_metadata.out"): """ Returns the test start time from the output log of SWI. """ test_start_time = None with open(test_metadata_file) as f: lines = f.readlines() test_start_time = lines[0] confi...
5,335,498
def addsong(): """Adds a semi-random song to the playlist""" rand = random.uniform(-0.5, 2) cursor.execute("SELECT file, listened, added FROM songs " "WHERE karma>? AND time < ? " "AND NOT duplicate ORDER BY random() LIMIT 1;", (rand, int(time.time()-(60*(flood_delay-trigger*3))))) songdata = ...
5,335,499