content
stringlengths
22
815k
id
int64
0
4.91M
def train_model_if_possible(data_df:pd.DataFrame): """ add knowledge to skimind :retrn: bool """ if not list(data_df.values): # aucune nouvelle donnee a apprendre return True print(f"preprocessing build") # train (learning) request object request_train = preproc...
5,292,500
def eq_xtl( Cl, D, F, ): """ eq_xtl calculates the composition of a trace element in the remaining liquid after a certain amount of crystallization has occured from a source melt when the crystal remeains in equilibrium with the melt as described by White (2013) Chapter 7 eq. 7.81. It then calculate...
5,292,501
def quantity_label(quantity): """Returns formatted string of parameter label """ labels = { 'accrate': r'$\dot{m}$', 'alpha': r'$\alpha$', 'd_b': r'$d \sqrt{\xi_\mathrm{b}}$', 'dt': r'$\Delta t$', 'fluence': r'$E_\mathrm{b}$', 'length': 'Burst length', ...
5,292,502
def main(inputs: str): """Run anagram function as a main method.""" text, check = inputs.split(" ") return anagram(text=text, check=check)
5,292,503
def spreadsheet(service, id): """Fetch and return spreadsheet meta data with Google sheets API.""" request = service.spreadsheets().get(spreadsheetId=id) try: response = request.execute() except apiclient.errors.HttpError as e: if e.resp.status == 404: raise KeyError(id) ...
5,292,504
def fix_labels(mnist_label, add_num): """ Args: label: [[int]] arary, class labels n: int, number of add data Returns: [[int]] array """ c_num = len(mnist_label[0]) # add one dimention fixed_label = np.c_[mnist_label, np.zeros(len(mnist_label))] assert len(fixed_label[0])...
5,292,505
def get_global_reach_connection(global_reach_connection_name: Optional[str] = None, private_cloud_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> Awaitab...
5,292,506
async def test_entity_and_device_attributes(hass, thermostat): """Test the attributes of the entries are correct.""" await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat]) entity_registry = await hass.helpers.entity_registry.async_get_registry() device_registry = await hass.helpers.device_regi...
5,292,507
def parseInertial(link_xml): """Parses the URDF xml definition of inertial data. Args: link_xml(ElementTree.Element): xml representation of 'inertial' field of URDF link Returns: : dict -- of inertial data """ inertial_dict = {} inertial_data = link_xml.find('inertial') if ine...
5,292,508
def hexdump(data, start_address=0, compress=True, length=16, sep='.'): """ Return string array in hex-dump format :param data: The data array of bytes :param start_address: Absolute Start Address :param compress: Compressed output (remove duplicated content, rows) :param length: ...
5,292,509
def manager(): """Create a `SerializerManager` with the default config.""" m = SerializerManager() m.register("pickle", PickleSerializer) m.register("json", JSONSerializer) yield m
5,292,510
def precipitation(): """Return the JSON representation of dictionary for the last year.""" # To find the last day: lastday = list(np.ravel(session.query(Measurement.date).order_by(Measurement.date.desc()).first()))[0] lastday = lastday.split("-") year = int(lastday[0]) month = int(lastday[...
5,292,511
def get_all_shared_user_info(user, includeCurrentSite=True): """Queries all nodes (including local node) for projects and groups the user belongs to. Returns two lists of dictionaries but does NOT update the local database. Example of JSON data retrieved from each node: { "users": { ...
5,292,512
def binary_accuracy(output: torch.Tensor, target: torch.Tensor) -> float: """Computes the accuracy for binary classification""" # 传入的output是batch x 1的tensor with torch.no_grad(): batch_size = target.size(0) pred = (output >= 0.5).float().t().view(-1) correct = pred.eq(target.view(-1)...
5,292,513
def update_pg_hba_conf_on_segments(gparr, standby_host, is_hba_hostnames=False): """ Updates the pg_hba.conf on all of the segments present in the array """ logger.debug('Updating pg_hba.conf file on segments...') standby_pg_hba_info = get_standby_pg_hba_info(standby_host, is_hba_hostnames) ...
5,292,514
def list_datasets(): """Get list of available datasets.""" return [ d for d in os.listdir(UEA_UCR_DATA_DIR) if os.path.isdir(os.path.join(UEA_UCR_DATA_DIR, d)) ]
5,292,515
async def healthcheck_task1(): """A healthcheck representing a database check.""" await asyncio.sleep(0.1) return ("database is good!", HTTPStatus.OK)
5,292,516
def get_response(request): """ Fake view-like callback to use in middleware tests. """ return None
5,292,517
def set_proper_dtypes(df): """ forgot to save integers as integers. Only the distances feature columns have true floats. """ potential_integer_cols = df.columns.difference(list(df.filter(regex='distances.*', axis=1))) for col in potential_integer_cols: if str(df[col].dtype) != 'object': ...
5,292,518
def test_simple(tmp_path): """Render a simple template.""" template_path = tmp_path / "template.txt" template_path.write_text(textwrap.dedent(u"""\ TO: to@test.com SUBJECT: Testing mailmerge FROM: from@test.com Hello {{name}}! """)) template_message = TemplateMessage...
5,292,519
def test_error_on_negative_opex_per_capacity(schema: Type[BaseModel], data: Dict[str, Any]): """ Test that a opex per capacity is not negative """ with pytest.raises(ValidationError) as exc_info: schema(opex_per_capacity=-0.5, **data) assert len(exc_info.value.errors()) == 1 assert exc_...
5,292,520
def prepare_single_subexperiment(opts: Namespace): """ Here we add a single sub-experiment to an experiment. """ with open(opts.config_path) as handler: config_data = yaml.load(handler, Loader=yaml.SafeLoader) title = os.path.basename(os.path.normpath(opts.config_path)) if title.endswith("....
5,292,521
def has_prefix(sub_s: str) -> bool: """ :param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid :return: (bool) If there is any words with prefix stored in sub_s """ if len(sub_s) > 1: sub_str = sub_s[:2] else: sub_str = sub_s[0] if s...
5,292,522
def stop(syncplan_name, p5_connection=None): """ Syntax: SyncPlan <name> stop Description: Removes the plan <name> from the scheduler Return Values: -On Success: the string "1" (the plan was successfully removed) the string "0" (the plan was not removed or running) """ ...
5,292,523
def spr(id,x,y,colorkey=-1,scale=1,flip=0,rotate=0,w=1,h=1): """ Usage: print text [x=0 y=0] [color=12] [fixed=False] [scale=1] [smallfont=False] -> text width Parameters: id : index of the sprite (0..511) x : x coordinate where the sprite will be drawn, starting from top...
5,292,524
def _E_from_XY_batch(X, Y, K, W=None, if_normzliedK=False, normalize=True, show_debug=False): # Ref: https://github.com/marktao99/python/blob/master/CVP/samples/sfm.py#L55 """ Normalized Eight Point Algorithom for E: [Manmohan] In practice, one would transform the data points by K^{-1}, then do a Hartley normalizat...
5,292,525
def global_nms(boxes, scores, iou_threshold): # type: (Tensor, Tensor, float) -> Tensor """ Performs non-maximum suppression globally (regardless of category). Parameters ---------- boxes : Tensor[N, 4] boxes where NMS will be performed. They are expected to be in (x1, y1, x2, y...
5,292,526
def mock_display(monkeypatch, specs): """Monkeypatches the display function to return its first argument""" def display(x, *args, **kwargs): specs.extend(x) monkeypatch.setattr(spack.cmd, 'display_specs', display)
5,292,527
def print_from_image(filename, option): """Taking in an image, use its RGB values to decide upon an ASCII character to represent it. This ASCII character will be based upon the brightness measure calculated """ try: with Image.open(filename) as image: pixels = get_pixel_matrix(im...
5,292,528
def arg_parser(): """ Parse the command line Arguments and return the values params: None returns: data_type - string returns: train_model - Boolean - Default - Yes returns: log_level - int - Default - 20 - INFO returns: console_logging - Boolean - Default - True """ import argparse...
5,292,529
def calculate_stats(answers, predictions, cm): """ Prints the Stats for a given class label :param answers: an array of answers :param predictions: an array of predictions :param cm: confusion matrix of form [[TP, FN], [FP, TN]] """ # confusion matrix looks like this [[ 23, 63], [ 40, 260]]...
5,292,530
def auto_rotate(img): """ Automatically rotate the given image to put the eyes on top :param img: The image to rotate :type img: 1D numpy array, shape: (1, IMAGE_WIDTH**2) :returns: The rotated image :rtype: 2D numpy array, shape: (IMAGE_WIDTH, IMAGE_WIDTH) """ #Rotate the image in all ...
5,292,531
def test_supported_methods(resolver: KeyDIDResolver): """Test the supported_methods.""" assert resolver.supported_methods == ["key"] assert resolver.supports("key")
5,292,532
def calculo_de_tempo_em_execucao(start: float = time()) -> float: """Método que irá calcular o tempo de execução a partir de um start Args: start (float, optional): tempo decorrido após o start. Defaults to time(). Returns: float: tempo decorrido de execução. """ print ('Tempo gast...
5,292,533
def pointcloud(out, verts, texcoords, color, painter=True): """draw point cloud with optional painter's algorithm""" if painter: # Painter's algo, sort points from back to front # get reverse sorted indices by z (in view-space) # https://gist.github.com/stevenvo/e3dad127598842459b68 ...
5,292,534
def AddInstanceCommunicationNetworkOp(network): """Create an OpCode that adds the instance communication network. This OpCode contains the configuration necessary for the instance communication network. @type network: string @param network: name or UUID of the instance communication network @rtype: L{gan...
5,292,535
def _is_contextvars_broken(): # type: () -> bool """ Returns whether gevent/eventlet have patched the stdlib in a way where thread locals are now more "correct" than contextvars. """ try: import gevent # type: ignore from gevent.monkey import is_object_patched # type: ignore ...
5,292,536
def get_expanding_count(datecol, idcol, targetcol=None): """ expanding counts """ unq_ids, idcol_inv = np.unique(idcol, return_inverse=True) unq_dates, date_cnts = np.unique(datecol, return_counts=True) n = len(idcol) nunq = len(unq_ids) learned_dict = np.zeros((nunq, )) tmp_cnts = ...
5,292,537
def expected_program(ax, ds, **kwargs, ): """ Draws in a subplot the expected availability program of a set of production assets. :param ax: The ax to fill :param ds: The expected availability program :param kwa...
5,292,538
def text_l( content: str, width: Optional[str] = None, visible: Optional[bool] = None, tooltip: Optional[str] = None, commands: Optional[List[Command]] = None, name: Optional[str] = None, ) -> Component: """Create large sized text content. Args: content: ...
5,292,539
def null_hurst_measure(measure): """Hurst computation parameter from some slope fit. Parameters ---------- measure: float the slope of the fit using some method. Returns ------- H: float the Hurst parameter. """ # Compute measure return float(measure)
5,292,540
def natSettings(ctx, mach, nicnum, nat, args): """This command shows/alters NAT settings. usage: nat <vm> <nicnum> settings [<mtu> [[<socsndbuf> <sockrcvbuf> [<tcpsndwnd> <tcprcvwnd>]]]] mtu - set mtu <= 16000 socksndbuf/sockrcvbuf - sets amount of kb for socket sending/receiving buffer tcpsndwnd/tc...
5,292,541
def reduce_loss(loss, reduction): """Reduce loss compute. :param loss: losses :param reduction: reduce funtion :return: loss """ reduction_function = F._Reduction.get_enum(reduction) if reduction_function == 0: return loss elif reduction_function == 1: return loss.mean()...
5,292,542
def get_new_strava_activity_data(): """Primary function to coordinate, requesting new Strava data, cleaning it and uploading to BigQuery""" global STRAVA_TOKEN # Check current token is still valid and update if needed if STRAVA_TOKEN["expires_at"] < time.time(): # Make Strava auth API call with...
5,292,543
def cek_filter(data, bound): """ Check if convergence checks ceke and ceki are within bounds""" ceke = ceke_filter(data, bound) ceki = ceki_filter(data, bound) cek = ceke & ceki return cek
5,292,544
def test_document_remove_keyword(app, testdata): """Test removing keywords from document record.""" document_pid = testdata["documents"][0]["document_pid"] keywords = [ Keyword.get_record_by_pid(kw["keyword_pid"]) for kw in testdata["keywords"] ] document = Document.get_record_by_pid...
5,292,545
def cli(filepaths, use_cache, display_size): """ Compiles the manifest for this project and saves the results back to the manifest. Note that ape automatically recompiles any changed contracts each time a project is loaded. You do not have to manually trigger a recompile. """ # NOTE: Lazy l...
5,292,546
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [p 85]. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [Fig. 3.7]. To get started, you might want to try some of these simple commands to ...
5,292,547
def load_model(dataset): """ Builds/load a model appropriate for the dataset """ retinanet = RetinaNet(num_classes=dataset.get_num_classes()).train().cuda(DEVICE_IDX) logging.info('Model loaded') return retinanet
5,292,548
def SetPlayerSecret(request, callback, customData = None, extraHeaders = None): """ Sets the player's secret if it is not already set. Player secrets are used to sign API requests. To reset a player's secret use the Admin or Server API method SetPlayerSecret. https://docs.microsoft.com/rest/api/playfab/...
5,292,549
def sample(ignition, connection, local_features_path=None): """ Pulls in dataframe of relevant observations and columns from PSQL. Parameters ========== ignition : yaml with all information necessary connection : SQLConn connection class local_features_path : str Path to locally sto...
5,292,550
def check_response(response): """Check the given HTTP response, returning the result if everything went fine""" code, body = response if code != httplib.OK: raise Exception('Received http response code %d' % (code)) data = json.loads(body) if data['error']: raise Exception(data[...
5,292,551
def _strip_value(value, lookup='exact'): """ Helper function to remove the branch and version information from the given value, which could be a single object or a list. """ if lookup == 'in': stripped_value = [_strip_object(el) for el in value] else: stripped_value = _strip_obje...
5,292,552
def process_command_line(argv=None): """ Parse command line arguments `argv` is a list of arguments, or `None` for ``sys.argv[1:]``. Return a Namespace representing the argument list. """ # Create the parser parser = argparse.ArgumentParser(prog='obflow_stat', ...
5,292,553
def refactor_levels( level: Level | list[Level] | None, obj: Index, ) -> list[int]: """ Returns a consistent levels arg for use in ``hide_index`` or ``hide_columns``. Parameters ---------- level : int, str, list Original ``level`` arg supplied to above methods. obj: Eith...
5,292,554
def test_wrong_image_shape_fit(X_wrong_image: ArrayLike) -> None: """ Test that ValueError is raised if image has not 3 or 4 dimensions in fit. """ cumclf = ImageClassifier(X_wrong_image, y_toy_image) cumclf.fit(cumclf.X_calib, cumclf.y_calib) mapie = MapieClassifier( cumclf, met...
5,292,555
def compare_cards(card1, card2): """ Compare the two given cards and return success if successful """ success = False if card1.symbol == card2.symbol: success = True # Success return success
5,292,556
def get_f_sw_C(washbowl_watersaving_C, Theta_wtr_d): """# 洗面水栓の水優先吐水機能における節湯の保温効果係数 Args: washbowl_watersaving_C(bool): 洗面水栓の水優先吐水機能の有無 Theta_wtr_d(ndarray): 日平均給水温度 (℃) Returns: ndarray: 洗面水栓の水優先吐水機能における節湯の効果係数 (-) """ f_sw_C_d = np.ones(365) if washbowl_watersaving_C: ...
5,292,557
def binary(f): """Wraps a function of any arity (including nullary) in a function that accepts exactly 2 parameters. Any extraneous parameters will not be passed to the supplied function""" return n_ary(2, f)
5,292,558
def downloadMedia(mediaItems: list, isVideo: bool) -> list: """ GooglePhotoAPIに接続しphotoもしくはvideoをダウンロードする Parameters ---------- mediaItems : list メディア(photo or video)のリスト isVideo : bool ビデオであるかどうか Returns ---------- ids : list ダウンロードに成功したidのリスト """ s...
5,292,559
def super_copy(original_location, copy_location, folder_name, files, counter): """Uses the copy2 function to copy files and updates the given global variable after each loop to track progress Parameters: original_location (String): the folder containing the files to copy copy_location (String):...
5,292,560
def report_mean_upper(nutrients_mean): """Report mean nutrient intake upper financial-class""" upper_carb_trend.append(nutrients_mean[0]) upper_fiber_trend.append(nutrients_mean[1]) upper_fat_trend.append(nutrients_mean[2]) upper_prot_trend.append(nutrients_mean[3])
5,292,561
def get_maxes_and_argmaxes( data: jnp.array, labels: jnp.array, num_labels: int ) -> Tuple[jnp.ndarray, jnp.ndarray]: """ Given a flattened sequence of elements and their corresponding labels, returns the maxes and argmaxes of each label. Args: data: Array of shape (a_len,) where a_len is a...
5,292,562
def scale_image(img_path, scale, image_ext=IMAGE_EXTENSION, overwrite=False): """ scaling images by given scale factor :param img_path: input image path :param int scale: selected scaling in percents :param str image_ext: image extension used on output :param bool overwrite: whether overwrite exist...
5,292,563
def sftpUpload(localFile, targetDir): """ Just Test connection to host and upload localFile to targetDir """ if os.path.isfile(localFile): print('..Connection to', cinfo['host']) with pysftp.Connection(**cinfo) as sftp: print('..Chg to Dir ', targetDir) with sftp....
5,292,564
def detect(system_abi=False): """Detects host ABI (either process ABI or system ABI, depending on parameters) :param bool system_abi: specified whether system ABI or process ABI should be detected. The two may differ, e.g. when a 64-bit system runs 32-bit Python interpreter. :returns: the host ABI...
5,292,565
def _uuid_inventory() -> str: """Create uuid for inventory.""" return _uuid()
5,292,566
def local_overrides_git(install_req, existing_req): """Check whether we have a local directory and a Git URL :param install_req: The requirement to install :type install_req: pip.req.req_install.InstallRequirement :param existing_req: An existing requirement or constraint :type existing_req: pip.re...
5,292,567
def merge_same_price(df: pd.DataFrame, prec: float=5) -> pd.DataFrame: """ Process a collection of bids by merging in each side (buying or selling) all players with the same price into a new user with their aggregated quantity Parameters ---------- df Collection of bids to process ...
5,292,568
def normalize_latents(z, epsilon=1e-8): """Pixel norm implementation in NumPy.""" return z / np.sqrt(np.mean(np.square(z), axis=1, keepdims=True) + epsilon)
5,292,569
def analyze_sensitivity(path, column, delimiter, order, name, parallel=False, processors=4): """ Perform the sensitivity analysis after you have run your model with all the parameters from gen_params(). This is done from the command line because it is faster and gives the option...
5,292,570
def test_get_not_implemented_fields_with_str_fallback(): """Get invalid field w/ fallback.""" for ctx, mappings in type_mappers.all_maps.items(): for fieldname, mapping in mappings.items(): if mapping is None: assert type_mappers.get_context_field( fieldna...
5,292,571
def _load_saved_model_from_session_bundle_path(export_dir, target, config): """Load legacy TF Exporter/SessionBundle checkpoint. Args: export_dir: the directory that contains files exported by exporter. target: The execution engine to connect to. See target in tf.Session() config: A ConfigProto proto w...
5,292,572
def get_first_available_file(*paths, file_name): """ gets the first path which a file with given name is resided in it. it returns None if the file is not available in any of given paths. :param str paths: paths to look for file in them. all paths must be absolute. :param st...
5,292,573
def render_doc_file( source_file: Path, doc_file: Path, template_name: str, user_template_dir: str ) -> None: """ Renders a documentation file, `doc_file`, for the provided `source_file`. Args: source_file: The source file to be documented. doc_file: The resultant documentation file tha...
5,292,574
def unite(iterable): """Turns a two dimensional array into a one dimensional.""" return list(chain.from_iterable(iterable))
5,292,575
def reserve_temp_dir(client, bucket, root_dir, empty_file_name='_'): """ Reserves a temp dir on Minio. Normally, Minio does not have directories, only files. That's why we write an empty file in that reserved directory. You can customize its name by setting the empty_file_name variable. """ ...
5,292,576
def s3_path_to_bytes_io(path): """ Example usage: bytes_io = s3_path_to_bytes_io("s3://bucket/file.csv") for line in bytes_io.readlines(): print(line.decode("utf-8")) """ bucket, key = s3_path_to_bucket_key(path) obj = s3_client.get_object(Bucket=bucket, Key=key) return io.BytesI...
5,292,577
def posts_list(request): """Logic to handle requests and return responses.""" queryset = Post.objects.all() context_data = { "title": "Posts", "object_list": queryset } return render(request, "posts_list.html", context_data) #return HttpResponse("<h1>List<h1>")
5,292,578
def initializeANEOS(in_filename = "std::string", out_filename = "std::string", izetl = "std::vector<int>"): """Initialize ANEOS with some rather arcane input. in_filename : The name of the ANEOS input file, initializes the Fortran ANEOS library out_filename : An optional fi...
5,292,579
def verify_already_exists(username): """ verify if user already exists """ if User.by_name(username): return "User already exists"
5,292,580
def parse(fp_or_str): """parse TA98 english web pages into a Python dictionary""" soup = BeautifulSoup(fp_or_str, "html.parser") res = soup.find_all(class_=('SectionTitle', 'SectionContent')) sections = {} found_current_in_hierarchy = False ta_hierarchy = [] for r in res: if 'Secti...
5,292,581
def infer_device(x: Any): """Infer the device of any object (CPU for any non-torch object)""" if isinstance(x, torch.Tensor): return x.device return torch.device("cpu")
5,292,582
def test_ps_info(): """ log information for manual testing """ return SkipTest("only used in manual testing") zones, ps_zones = init_env() realm = get_realm() zonegroup = realm.master_zonegroup() bucket_name = gen_bucket_name() # create bucket on the first of the rados zones bucket = zon...
5,292,583
def _run_finalizer(ref): """Internal weakref callback to run finalizers""" del _finalize_refs[id(ref)] finalizer = ref.finalizer item = ref.item try: finalizer(item) except Exception: # pragma: no cover print("Exception running {}:".format(finalizer), file=sys.stderr) tr...
5,292,584
def fertl(rw, rt, phi, a, m, vsh, alpha): """Estimate water saturation from Fertl [1]_ equation. Parameters ---------- rw : int, float Water resistivity. rt : array_like True resistivity. phi : array_like Porosity (must be effective). a : int, float ...
5,292,585
def mean_agg_func(samples: np.ndarray, num_resamples: int=25_000): """ Computes mean. """ # Point estimation. point_estimate = np.mean(samples) # Confidence interval estimation. resampled = np.random.choice(samples, size=(len(samples), num_resamples), ...
5,292,586
def join_cubes(inputs, output, channels, resume=False, box=None): """Join cubes at specific channels """ if len(channels)!=len(inputs): raise ValueError("Length of channels(%i)!=inputs(%i)" % (len(channels),len(inputs))) # Concatenated image imagename = os.path.expanduser(ou...
5,292,587
def factory_membership_model(user_id, org_id, member_type='OWNER'): """Produce a Membership model.""" membership = Membership(user_id=user_id, org_id=org_id, membership_type_code=member_type) membership.save() return membership
5,292,588
def from_arrays(x,y,u,v,mask): """ from_arrays(x,y,u,v,mask,frame=0) creates an xArray Dataset from 5 two-dimensional Numpy arrays of x,y,u,v and mask Input: x,y,u,v,mask = Numpy floating arrays, all the same size Output: data is a xAarray Dataset, see xarray...
5,292,589
def dup_gf_factor(f, K): """Factor univariate polynomials over finite fields. """ f = dup_convert(f, K, K.dom) coeff, factors = gf_factor(f, K.mod, K.dom) for i, (f, k) in enumerate(factors): factors[i] = (dup_convert(f, K.dom, K), k) return K.convert(coeff, K.dom), factors
5,292,590
def turns_remaining(turns): """returns the number of turns remaining""" if turns == 0: return "You ran out of turns." else: return "You have {} turns remaining.".format(turns)
5,292,591
def cross_ratio(A, B, C, D): """The cross ration of four _colinear_ points is invariant under projective transformation. That means that, for any homography H, cross_ratio(A, B, C, D) == cross_ratio(HA, HB, HC, HD) which can be useful.""" # (u, v, w) is the line orthogonal to (A-D), that...
5,292,592
def find_optimal_route(start_time, expected_time, favorite_route='SBS1K', favorite_option='bus'): """ Find optimal route for me to go from home to office. First two inputs should be datetime instances. """ # Convert to minute...
5,292,593
def log_scheduler(message): """ Process used to log information easily in other modules Gathers number of items in schedule queue """ log.info("Scheduler size: {}".format(len(scheduler.queue))) for index, job in enumerate(scheduler.queue): log.info("JOB {} {}".format((index + 1), job))
5,292,594
def load_fasta_file(filename, name=None, feature='fasta', unique=True): """ Load a fasta file given the filename. Args: filename (str): name of the fasta file. name (str): name for the sequence set (default: None means use 'filename' as 'name') feature (str): name for th...
5,292,595
async def test_push_updates(socket_push: wizlight) -> None: """Test push updates.""" bulb_type = await socket_push.get_bulbtype() assert bulb_type == BulbType( features=Features( color=False, color_tmp=False, effect=False, brightness=False, ...
5,292,596
def collect_info_masters( designspace: designspaceLib.DesignSpaceDocument, axis_bounds: AxisBounds ) -> List[Tuple[Location, FontMathObject]]: """Return master Info objects wrapped by MathInfo.""" locations_and_masters = [] for source in designspace.sources: if source.layerName is not None: ...
5,292,597
def lines_intersect(line1, line2): """ Returns intersection point between line1 and line2, or None if they dont intersect """ (x1, y1), (x2, y2) = line1 (x3, y3), (x4, y4) = line2 # Compute coeficients for line1 # where a1 x + b1 y + c1 = 0 a1 = y2 - y1 b1 = x1 - x2 c1 = x2 * y1 - x...
5,292,598
def get_renewal_config(tmp: str, domain: str) -> configobj.ConfigObj: """return renewal config of certbot""" config = {} tmppath = pathlib.Path(tmp) cfg = configobj.ConfigObj(os.path.join(tmp, 'config-dir', 'renewal', domain + '.conf')) for key in ['archive_dir', 'cert', 'privkey', 'chain', 'fullcha...
5,292,599