content
stringlengths
22
815k
id
int64
0
4.91M
def doOneCase(file1, file2, outfile, sampleSize=1000,nreps=2000, paranoid=1): """Performs analysis for a pair of files""" sample1 = readSample( file1 or sys.stdin ) sample2 = readSample( file2, sample1 ) isDebug = False allResults = {} # I am being extremely paranoid here and using the worst # confidence value o...
41,600
def get_polling_method(meth_name=None): """ Grab a polling-method by string-key Eventually these could be auto-registered somehow; for now we just keep a look-up dict of them. """ methods = dict( poll_game_unknowns=poll_game_unknowns, poll_dan=poll_dan, ) default_method = poll_...
41,601
def get_contour_list(image, preprocessed, MIN_FILTER=3000): """ Given an image and its preprocessed version, returns the cropped image and its contours. The return value is in the format: [(CroppedImage, Contour)] Parameters ---------- image : opencv image The original unprocessed image ...
41,602
def doc_signature(f): """Attempt to parse the signature of a function at the beginning of its documentation. Useful for many numpy functions. """ doc = inspect.getdoc(f) if not doc: # print(f"DD doc_signature: no doc for {qualname(f)}") return None m = re.search(re_parser.doc_si...
41,603
def generate_wav(pattern, tempo=120, loops=1, saveName='audiofile.wav', fs=44100, dynamics=False, customSound=None): """ Generate a .wav file from a pattern. Specify a tempo (in BPM), loops, name of the file, sampling rate, and decide if you want "dynamics". Dynamics adds offsets to the amplitude of the onse...
41,604
def svn_fs_upgrade(*args): """svn_fs_upgrade(char path, apr_pool_t pool) -> svn_error_t""" return _fs.svn_fs_upgrade(*args)
41,605
def api_url(service: str = "IPublishedFileService", function: str = "QueryFiles", version: str = "v1") -> str: """ Builds a steam web API url. :param service: The steam service to attach to. :param function: The function to call. :param version: The API version. :return: ...
41,606
def reg_all_keywords(data): """ 从meta file中提取所有关键词,格式为: ***[:###]*** 提取出### :param data: :return: """ patt = re.compile(r"\[:([^\[\]]+)\]") ret = patt.findall(data) return ret if ret else None
41,607
def send_email(to, msg, subject, use_prefix=True): """ Sends an email to a user. Expects 'to' to be a comma separated string of emails, and for 'msg' and 'subject' to be strings. """ msg = MIMEText(msg) if use_prefix and '[RuddWeb]' not in subject: subject = '[RuddWeb] ' + subject msg['Subject'] = s...
41,608
def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ _focus = windowing.FocusManager() FigureClass = kwargs.pop('FigureClass', Figure) figure = FigureClass(*args, **kwargs) window = Tk.Tk() canvas = FigureCanvasTkAgg(figure, master=window) figMan...
41,609
def init_workers(): """ This method is for starting all worker threads. We are using three workers right now . 1. One for fetching latest instances info and adds to Queue 2. One for fetching from Queue and updating Redis 3. For updating the aggregator app , about this applications info. All ...
41,610
def get_platform(): """Gets the platform (example: azure).""" return get_config_value("platform")
41,611
def transform_command(src, show_diff=True): """Returns the results of firing the precommand handles.""" i = 0 limit = sys.getrecursionlimit() lst = "" raw = src while src != lst: lst = src srcs = events.on_transform_command.fire(cmd=src) for s in srcs: if s !=...
41,612
def main(): """Define parser, collect questions. """ parser = argparse.ArgumentParser( description=__description__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("input", nargs="+", help="Files to parse. Parser will be chosen by filename extension ('gift.txt',...
41,613
def ascii_from_object(space, w_obj): """Implements builtins.ascii()""" # repr is guaranteed to be unicode w_repr = space.repr(w_obj) w_encoded = encode_object(space, w_repr, 'ascii', 'backslashreplace') return decode_object(space, w_encoded, 'ascii', 'strict')
41,614
def project_dir(project_name=None): """ 获取当前项目根路径 :param project_name: :return: 根路径 """ PROJECT_NAME = 'stock-technical-analysis' if project_name is None else project_name project_path = os.path.abspath(os.path.dirname(__file__)) root_path = project_path[:project_path.fin...
41,615
def capture(p): """Return a peg that acts like p, except it adds to the values tuple the text that p matched.""" return _Peg(('capture(%r)', p), lambda s, far, (i, vals): [(i2, vals2 + (s[i:i2],)) for i2, vals2 in p.run(s, far, (i, vals))])
41,616
def html_chart(df, height=1200): """ make interactive chart. param df: inpute dataframe param height: optional plot height returns: plotly chart """ fig = make_subplots(rows=(len(df.columns)), cols=1, subplot_titles=df.columns, ...
41,617
def build_0565_color_lookup(): """Build the lookup table for the ARGB_0565 color format""" bdG = 6 bdB = 5 redColorOffset = bdG + bdB greenColorOffset = bdB val_lookup_5 = BITDEPTH_VALUE_LOOKUPS[5] val_lookup_6 = BITDEPTH_VALUE_LOOKUPS[6] conversion_table = [None] * 65536 for r_sho...
41,618
def build_que_input_from_segments(context, answer, question, tokenizer, max_input_length=1000, with_eos=True, with_labels=True): """ Build a sequence of input from 3 segments: context, answer, question """ bos, eos, ctx, ans, que, pad, ...
41,619
def add_record(task_name): """ Handles the `add_record` command. Syntax: `add_record <task_name>` Function: add an untracked record (more prompts to further collection info) Precondition on argument `message`: - `message` is an non-empty string as the the input validation has already been handled ...
41,620
def default_logging_config(logger): """Set up the default handler and formatter on the given logger.""" default_handler = logging.StreamHandler(stream=sys.stdout) default_handler.formatter = ColorFormatter() logger.handlers = [default_handler] logger.propagate = True return logger
41,621
def verify_preload(upload_id, language=None): """ Continue the verification process by counting the number of geounits in the uploaded file and compare it to the number of geounits in the basest geolevel. After this step completes, the copy_to_characteristics method is called. Parameters: ...
41,622
def transition(field, source='*', target=None, conditions=[], custom={}): """ Method decorator for mark allowed transitions Set target to None if current state needs to be validated and has not changed after the function call """ def inner_transition(func): fsm_meta = getattr(func, '_d...
41,623
def snow(self,k): """ - snow melt based on degree day factor and - - Code for ini-file: 1 """ JarvisCoefficients.calcEpSnow(self,k) self.PotEvaporation = self.EpHour self.PotEvaporation = cover(ifthenelse(self.EpHour > 0, self.EpHour, 0),0) self.Sw[k] = self.Sw_t[k] + self.Pre...
41,624
def get_inspexp_frames(slice, inspexp_data, images_path): """ Loads inspiration and expiration frames for the specified cine-MRI slice Parameters ---------- slice: CineMRISlice A cine-MRI slice for which to extract inspiration and expiration frames inspexp_data : dict A dictionary...
41,625
def cleaned_reviews_dataframe(reviews_df): """ Remove newline "\n" from titles and descriptions, as well as the "Unnamed: 0" column generated when loading DataFrame from CSV. This is the only cleaning required prior to NLP preprocessing. INPUT: Pandas DataFrame with 'title' and 'desc' colum...
41,626
def not_list(l): """Return the element wise negation of a list of booleans""" assert all([isinstance(it, bool) for it in l]) return [not it for it in l]
41,627
def first_order_forward(n, zero = True): """ """ m1 = -np.eye(n) + np.eye(n, k = 1) return np.vstack([np.ones(n), m1])
41,628
def main(): """ Example to create a disjoint set, and check if 2 items they are disjoint. :return: :rtype: """ items = ["A", "B", "C", "D"] api = DisjointSetAPI() # creates 4 sets each with single item api.create(items) print("Checking if A and B are disjoint sets") print...
41,629
def boil(config, recipe_config): """ Boil wort. """ up = config['unit_parser'] if 'Hops' in recipe_config: hops = recipe_config['Hops'] for hop in hops: if 'addition type' in hop and hop['addition type'] == 'fwh': if 'mass' in hop and 'name' in hop and 'type' in...
41,630
def test_camel_to_snake(): """ Test function to transform a camel cased string into a snake cased string""" # Normal case assert camel_to_snake("CamelCase") == "camel_case" # Case with an abbreviation already capitalized (here HTTP) assert camel_to_snake("CamelHTTPCase") == "camel_http_case" #...
41,631
def table(logger, table, message="", level=logging.DEBUG): """ Print a table (pandas for example) in Markdown format """ if isinstance(table, pd.DataFrame): table.reset_index(inplace=True) tbl = tabulate( table, headers='keys', tablefmt=myfmt, showindex=Fals...
41,632
async def rock_paper_scissors_prompt(message): """ """ global average_typing_speed if message.author != bot.user: msg = message.content if any(name in msg for name in names) \ and "paper" in msg \ and "rock" in msg \ and "scissors" in msg \ ...
41,633
def show_input_output_info(kernel_info_json, show_name): """ print input or ouput info to stdout """ if show_name + "_num" in kernel_info_json: print("[INFO] Have {} {} in operator:".format(kernel_info_json[show_name + "_num"], show_name)) for i in range(kernel_info_json[show_name + "_nu...
41,634
def _ecdf( data=None, p=None, x_axis_label=None, y_axis_label="ECDF", title=None, plot_height=300, plot_width=450, staircase=False, complementary=False, x_axis_type="linear", y_axis_type="linear", **kwargs, ): """ Create a plot of an ECDF. Parameters ----...
41,635
def remove_pool(arg, opts, shell_opts): """ Remove pool """ remove_confirmed = shell_opts.force res = Pool.list({ 'name': arg }) if len(res) < 1: print("No pool with name '%s' found." % arg, file=sys.stderr) sys.exit(1) p = res[0] if not remove_confirmed: res = in...
41,636
def main(event, context): """entry point""" try: if 'Records' in event: for record in event['Records']: request = extract_request_from_record(record) common.logger.info(f"Process request for user {request.user_name} ...") if common.is_obsolete_...
41,637
def _get_cipher(key: bytes) -> Cipher: """获取 DES3 Cipher 对象""" from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes algorithm = algorithms.TripleDES(key) cipher = Cipher(algorithm, modes.CBC(key[:8]), backend=default_b...
41,638
def product( fields, i=0, result='' ): """Takes a list of list of fields and produces a generator that permutes through every possible combination of fields in order.""" if i == len( fields ): yield result else: for field in fields[i]: for x in product( fields, i+1, result...
41,639
def _get_read_info(path): """Yield tuple (chr, pos) for different fileformats.""" filename, fileextension = os.path.splitext(path) if fileextension == '.bed': with open(path, 'r') as f: for line in f: tmp = line.split('\t') yield tmp[0], int(tmp[1]) e...
41,640
def get_real_dist2rim(x_dist, radius_cut, radius_sphere): """ Get the real distance to rim :param x_dist: :param radius_cut: :param radius_sphere: :return: """ x_transf = x_dist * ((radius_sphere) - np.sqrt((radius_sphere) ** 2 - (radius_cut) ** 2)) / radius_cut return x_transf
41,641
def read_json(filename): """ JSONファイル読み込む """ try: basedir = os.path.dirname(os.path.abspath(__file__)) indir = os.path.join(basedir, "data") readfilename = os.path.join(indir, filename) with codecs.open(readfilename, 'r', "utf-8") as f: jsonData = json.loads...
41,642
def get_workers_stats(worker_class=None): """Get the RQ workers stats. Args: worker_class (type): RQ Worker class Returns: list: List of worker stats as a dict {name, queues, state} Raises: redis.exceptions.RedisError: On Redis connection errors """ worker_class = worker_...
41,643
def _get_trafo(cmatrix: cairo.Matrix) -> qc3const.TrafoType: """Converts cairo matrix to trafo list :param cmatrix: (cairo.Matrix) cairo transformation matrix :return: (qc3const.TrafoType) transformation matrix """ return [i for i in cmatrix]
41,644
def mousover_plot(datadict, attr_x, attr_y, attr_color=None, attr_size=None, save_file=None, plot_title="", point_transparency = 0.5, point_size=20, default_color="#2222aa", hidden_keys = []): """ Produces dynamic scatter plot that can be interacted with by mousing over each point to see its label...
41,645
def globalInequalityChanges(Y, fieldNames, outFile, permutations=9999): """Global inequality change test This function tests whether global inequality has significantly changed for the Theil statistic over the period t to t+k. For more information on this function see [Rey_Sastre2010] (this function r...
41,646
def sign_jars(configs): """ Use Jenkins job to sign uploaded jars """ print("Using Jenkins job to sign uploaded Jars...") jenkins = Jenkins(configs["jenkins"]["url"], configs["jenkins"]["username"], configs["passwords"]["jenkins"], None, False, True, 600) ...
41,647
def generate_gisaid_fasta_df(fname, rtype="nuc", ambiguous_tol=0.01, len_tol=0.9): """ Generate pandas dataframe for sequences downloaded from GISAID """ fdat_df = [] standardise_gene_name = {"PB2":1, "PB1":2, "PA":3, "HA":4, "NP":5, "NA":6, "MP":7, "NS":8} subtype_to_influenza_gene_len = {"A":...
41,648
def test_function_day(client: Eve, sample_schema: dict): """Test to ensure day function works :param Eve client: Mockerena app instance :param dict sample_schema: Sample schema data :raises: AssertionError """ sample_schema["num_rows"] = 1 sample_schema["file_format"] = "json" sample_s...
41,649
def radial_trajectory(base_resolution, views=1, phases=None, ordering='linear', angle_range='full', tiny_number=7, readout_os=2.0): """Calculate a radial trajectory. This function sup...
41,650
def setver(c, assembly, version): """ Update the version of specified assembly """ if assembly in assemblyAliases: assembly = assemblyAliases[assembly] (assemblies[assembly])["setver"](version) updateNuspecs()
41,651
def bigBoxPlot (xvals, yvals, isGood, isLog=True): """ """ minval = log10(min(xvals)) maxval = log10(max(xvals)) delta = (maxval-minval)/10. for i in range(10): xpt = (minval+delta/2.)+i*delta t = yvals[isGood * (abs(log10(xvals) - xpt)<delta/2.)] if len(t)>0: box...
41,652
def highlight_threshold(image, img_data, threshold, color=(255, 0, 0)): """ Given an array of values for an image, highlights pixels whose value is greater than the given threshold. :param image: The image to highlight :param img_data: The values to use :param threshold: The threshold above which pi...
41,653
def test_setup_params(hass: HomeAssistant) -> None: """Test the initial parameters.""" state = hass.states.get(ENTITY_SPEED) assert state assert state.state == "ridiculous_speed" assert state.attributes.get(ATTR_OPTIONS) == [ "light_speed", "ridiculous_speed", "ludicrous_spee...
41,654
def error_norm(q_numerical, q_exact, dx, p=2): """ Compute the discrete error in q in the p norm Parameters ---------- q_numerical : numpy vector The numerical solution, an array size (N,) or (N,1) q_exact : numpy vector The exact solution, whose size matches q_numerical dx ...
41,655
def test_contains_only_phonetic_chars_will_recognize_phonetics(): """ Tests the contains_only_phonetic_chars() method recognizes real phonetic chars """ example_text = "The quick brown fox jumps over the lazy dog 1234567890" assert helpers.contains_only_phonetic_chars(example_text) == True
41,656
def remove(filename): """Delete file filename and don't raise if missing.""" try: os.remove(filename) except OSError: pass
41,657
def sync_sc_blocks(api_connections, wait_for=25, p=False): """ Wait for maximum wait_for seconds for everybody to have the same block count """ start = time.time() while True: if time.time() - start >= wait_for: raise TimeoutException("Syncing blocks") counts = [int(x.blo...
41,658
def _validate_voter(request, end_field): """Returns: voter, election, denied_reason, denied_detail (all optional).""" # TODO: Deprecate use of token here; can auto-generate log-in tokens instead. token = request.GET.get("token") election = get_current_election() voter = None if not election: ...
41,659
def flip(xyz_img): """ Take an xyz_img and flip its world from LPS / RAS to RAS / LPS. >>> data = np.random.standard_normal((30,40,50,5)) >>> metadata = {'name':'John Doe'} >>> lps_im = XYZImage(data, np.diag([3,4,5,1]), 'ijkt', metadata) >>> lps_im.xyz_transform XYZTransform( fu...
41,660
def pivoting_remove(z, rule): """Choose which active constraint will be replaced """ if rule is None: k = np.argmin(z) elif rule.lower() == 'bland': k = np.min(np.nonzero(z < 0)[0]) else: raise('Undefined pivoting rule') return k
41,661
def train_network(model, optimizer, train_loader, lss_fc) -> None: """Train Network for one Epoch.""" train_losses = [] for batch in tqdm(train_loader, total=len(train_loader)): optimizer.zero_grad() input_tensor, original = batch input_tensor = input_tensor.to('cuda') out ...
41,662
async def test_connection_error(opp, requests_mock): """Test we show user form on connection error.""" requests_mock.request(ANY, ANY, exc=requests.exceptions.ConnectionError()) result = await opp.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER}, data=FIXTURE_US...
41,663
def check_file_version(notebook, source_path, outputs_path): """Raise if file version in source file would override outputs""" _, ext = os.path.splitext(source_path) current = file_format_version(ext) version = notebook.metadata.get('jupytext_format_version') if version: del notebook.metadat...
41,664
def get_class(cls): """Return TestModuleVisitor report from a class instance.""" ast = get_ast(cls.__module__) nv = TestmoduleVisitor() nv.visit(ast) return nv._classes[cls.__name__]
41,665
def show_system_timezone( enode, _shell='vtysh', _shell_args={ 'matches': None, 'newline': True, 'timeout': None, 'connection': None } ): """ Display system timezone information This function runs the following vtysh command: :: # show system ti...
41,666
def p_EXPRESION_P(p): """ EXPRESION_P : GREATER_THAN EXP | LESS_THAN EXP | NOT_EQUAL EXP | EMPTY """
41,667
def summarize_list(values): """ Takes a list of integers such as [1,2,3,4,6,7,8] and summarises it as a string "1-4,6-8" :param values: :return: string """ sorted_values = numpy.array(sorted(values)) summaries = [ (f'{chunk[0]}-{chunk[-1]}' if len(chunk) > 1 else f'{chunk[0]}'...
41,668
def enforce_size(img, depth, instances, new_w, new_h): """ Ensures that the image is the given size without distorting aspect ratio. """ with torch.no_grad(): _, h, w = img.size() if h == new_h and w == new_w: return img, depth, instances # Resize the image so that ...
41,669
def update_V_softmax(V,B,T,O,R,gamma,eps=None,PBVI_temps=None, max_iter=100,verbose=False,n_samps=100,seed=False): """ inputs: V (list): V[0]: n_B x n_S array of alpha-vector values for each belief V[1]: n_B array, denoting which action generated each alpha-v...
41,670
def on_connection_open(client): """Called by the WebSocketServer when a new connection is opened. """ ws.send(client, "Welcome to the echo server!")
41,671
def start(message): """ Command that welcomes the user and configures the required initial setup """ if message.chat.type == 'private': chat_user = message.chat.first_name else: chat_user = message.chat.title message_text = f'Hi {chat_user}!! I can help you find empty rooms in ...
41,672
def test_scenario_should_set_rule_to_steps_when_rule_set(mocker): """A Scenario should forward the Rule to each Step""" # given first_step = mocker.MagicMock(name="First Step") second_step = mocker.MagicMock(name="Second Step") scenario = Scenario( 1, "Scenario", "My Scenario", [], None, Non...
41,673
def scaled_location_plot(yname, yopt, scaled_res): """ Plot the scaled location, given the dependant values and scaled residuals. :param str yname: Name of the Y axis :param ndarray yopt: Estimated values :param ndarray scaled_res: Scaled residuals :returns: the handles for the ...
41,674
def importNoiseTerms(filename): """ Imports noise data from an FWH file; the returned data is a list of length nProbes filled with (nTime,3) arrays """ f = open(filename,'r') deltaT = [] while True: line = f.readline(); # read line by line if line == '': # check for ...
41,675
def line_edit_style_factory(txt_color='white', tgt_layer_color='white', bg_color='#232323'): """Generates a string of a qss style sheet for a line edit. Colors can be supplied as strings of color name or hex value. If a color arg receives a tuple we assume it is either an rgb or ...
41,676
def create_key(key_len): """ Generates key using random device if present - key_len -- length of key """ try: #generates truly random numbers frand = open("/dev/random", "r") data = frand.read(key_len/2) frand.close() return data.encode('hex') exc...
41,677
def add_resources(api): """ 将api中的resource添加到app的route中 :param api: :return: """ curr_dir = os.path.dirname(os.path.abspath(__file__)) files = os.walk(os.sep.join([curr_dir, "resources"])) #: 获取resources中多有定义的resources信息 root, paths, fs = files.send(None) fs.remove("__init__.py")...
41,678
def connectToPostgres(): """ If rulemonitor database does not exist yet: $ initdb /home/rulemonitor/postgres/data $ pg_ctl -D /home/rulemonitor/postgres/data -l /home/rulemonitor/postgres/log $ createdb rulemonitor """ pghost = os.getenv("POSTGRES_HOST", "192.168.5.83") pg...
41,679
def ipv6_from_string(string: str) -> netaddr.IPSet: """ Takes a string and extracts all valid IPv6 Addresses as a SET of Strings Uses the validate_ip helper function to achieve. """ ipv6_regex = re.compile( '(?<![a-zA-Z\d\.])((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:)...
41,680
def test_parse_kml(): """Parses a KML file and plots the coordinates""" def plot_lines(lines): for i,l in enumerate(lines): plt.plot([l[0], l[3]], [l[1], l[4]], color = cm.gist_rainbow(float(i) / float(len(lines)))) plt.show() ...
41,681
def import_teams_by_sport(sport): """ Ajout dans la base de données de toutes les équipes/joueurs d'un même sport ayant un match prévu sur comparateur-de-cotes.fr """ url = "http://www.comparateur-de-cotes.fr/comparateur/" + sport soup = BeautifulSoup(urllib.request.urlopen(url), features="lxml"...
41,682
def get_feature_location( feature_text: str) -> Tuple[int, int, str, List, bool, bool]: """ Args: feature_text: endswith '\n' For example: ' CDS complement(join(<360626..360849,360919..360948, ' 361067..361220,361292....
41,683
def isdir(path): """Like os.path.isdir, but raises an exception on error.""" return bool(stat.S_ISDIR(os.stat(path).st_mode))
41,684
def _update_port_rate_limits_v1(port_name, broadcast_limit=None, broadcast_units=None, multicast_limit=None, multicast_units=None, unknown_unicast_limit=None, unknown_unicast_units=None, **kwargs): """ Perform GET and PUT calls to update a Port's r...
41,685
def test_inspect_empty_archive(run_cli_command): """Test the functionality of `verdi export inspect` for an empty archive.""" filename_input = get_archive_file('empty.aiida', filepath='export/migrate') result = run_cli_command(cmd_archive.inspect, [filename_input], raises=True) assert 'corrupt archive' ...
41,686
def random_geom_sum(pmf, p, low_mem=False): """Calculates the distribution of Z = X_1 + X_2 + ... + X_N. Parameters ---------- pmf : array Probability distribution of X such that pmf[x] = Pr(X = x). p : float Probability such that N ~ geom(p), i.e. Pr(N = n) = p(1-p)^{n-1}. ...
41,687
def convert_query(data_source, query, config): """Convert a normalized query to a specific data source.""" source = config.normalizers[data_source] with config.domain_schemas[source.domain].eql_schema: query = parse(query) converted = source.normalize_ast(query) print(converted)
41,688
def noto_tools(default=""): """Local path to nototools git repo. If this is called, we require config to be set up.""" result = _values.get("noto_tools", default) if result: return result raise Exception(_ERR_MSG)
41,689
def fdc_windtur_west(timestamp, sonicU, sonicV, sonicW, heading, rateX, rateY, rateZ, accX, accY, accZ, lat): """ Description: Calculates the L1 windspeed data product WINDTUR-VLW_L1 from the FDCHP instrument, which collects 20 minutes of data every hour. The L1 data ...
41,690
def registry(ctx, path, remote_path, offline): """Manage a registry.""" no_prompts = ctx.parent.params["no_prompts"] if "--help" in sys.argv: ctx.obj = None else: ctx.obj = RegistryManager.load( path, remote_path, offline_mode=offline, no_prompts=no_prompts )
41,691
def reports(): """View reports""" return render_template("reports.html")
41,692
def ensure_hypothesis_is_valid(experiment: Experiment): """ Validates that the steady state hypothesis entry has the expected schema or raises :exc:`InvalidExperiment` or :exc:`InvalidActivity`. """ hypo = experiment.get("steady-state-hypothesis") if hypo is None: return if not hypo...
41,693
def otr_statusbar_cb(data, item, window): """Update the statusbar.""" if window: buf = weechat.window_get_pointer(window, 'buffer') else: # If the bar item is in a root bar that is not in a window, window # will be empty. buf = weechat.current_buffer() result = '' i...
41,694
async def test_flow_user(hass: HomeAssistant): """Test config flow: discovered + configured through user.""" # Discovered via step user. result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESUL...
41,695
def rotate_ellipse_NS(time_deg, datastruc, const): """Rotate ellipse major/minor axis to north/south orientation.""" # Construct major and minor major, minor, pha, inc = get_constituent(const, datastruc) # construct current at this time try: major_current = major*np.cos(np.deg2rad(time_deg -...
41,696
def img_lookup(pid): """Query for object type and return correct JPG location""" r = requests.get("https://fsu.digital.flvc.org/islandora/object/{0}/datastream/JPG/view".format(pid)) if r.status_code == 200: return r.url elif r.status_code == 404: r2 = requests.get("https://fsu.digital.f...
41,697
def _get_midnight_date(date): """Return midnight date for the specified date. Effectively, this function returns the start of the day for the specified date. Arguments: date -- An arbitrary date (type: datetime.datetime) Return: Midnight date (type: datetime.datetime) """ return datet...
41,698
def main(): """Main funciton""" parser = argparse.ArgumentParser() parser.add_argument("--use-cfg", type=str, default="", help="path to the config json") parser.add_argument("--cflags", action="store_true", help="print the cflags") parser.add_argument(...
41,699