content
stringlengths
22
815k
id
int64
0
4.91M
def ws_add_technicians(message, **kwargs): """ Perform things on connection start """ # pdb.set_trace() user = message.user #groupName = 'test' Group("hellothere",channel_layer=message.channel_layer).add(message.reply_channel) #Group(groupName).add(Channel("abc")) data = {'name'...
80,100
def _is_compatible(program: Loop, min_len: int, quantum: int, sample_rate: TimeType) -> _CompatibilityLevel: """ check whether program loop is compatible with awg requirements possible reasons for incompatibility: program shorter than minimum length program duration not an integer ...
80,101
def get_data_for_tpu(tpu_name, economic_dataframe, marry_dataframe, edu_dataframe, population_dataframe): """ :param tpu_name: the name of the tpu :param economic_dataframe: the dataframe contains median income and employment rate :param marry_dataframe: the dataframe which saves the marrital status ...
80,102
def gridaspoints(*arrs): """Creates an N-dimensional grid form arrs and returns grid points sequence of point coordinate pairs """ # there is a small gotcha here. # with the convention following the 2013-08-30 sprint in Potsdam it was # agreed upon that arrays should have shapes (...,z,y,x) simi...
80,103
def download_powermeter_csv(agent): """ Method to download a CSV list of mains sensor readings for all configured power meters and panels **parameters** :param agent: An agent instance from the device where the pmc data should be downloaded :return: returns the pmc data in csv format **Exampl...
80,104
def get_learner(case, *args, **kwargs): """Generator function for test""" data = Data(*args, is_learner=True, **kwargs) p = getattr(data.indexer, 'partitions', 1) X, y = data.get_data((12, 4), 2) (F, wf), (H, wh) = data.ground_truth(X, y, p) data.indexer.fit(X) learner, transformer = Estima...
80,105
def read_backend_config(config_file): """Parse YAML configuration file Parameters ---------- config_file : str path to the ramp-backend YAML configuration file Returns ------- config : dict dictionary with RAMP database configuration info Raises ------ ValueErr...
80,106
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up System Bridge from a config entry.""" client = Bridge( BridgeClient(aiohttp_client.async_get_clientsession(hass)), f"http://{entry.data[CONF_HOST]}:{entry.data[CONF_PORT]}", entry.data[CONF_API_KEY], ) ...
80,107
def cleaned(cls): """Call individual cleaning methods and collect all of their ValidationErrors Purpose: This decorator allows you to write individual methods that do some validation or cleaning without having to worry about collecting all of their ValidationErrors together into a list ...
80,108
def test_optional_test_case(): """Check test_case for optional case.""" validator = ImplementationValidator(base_url="http://example.org", verbosity=0) output = dummy_test_case( validator, ("string response", "message"), request="test_request", optional=True ) assert validator.results.succe...
80,109
def jedi_epc_server( address='localhost', port=0, port_file=sys.stdout, sys_path=[], virtual_env=[], sys_path_append=[], debugger=None, log_traceback=None, ): """Start EPC server. :type log_settings: LogSettings """ logger.debug( ...
80,110
def check_framescene(scene, frame, cameras, quality, check_green_frames, check_empty_frame, min_nbr_people): """ Checks a frame for all cameras in one scene. Returns True if all frame is good. Returns False if any frame was bad. """ for camera in cameras: bad, ids = ...
80,111
def update_model_structure_as_new(id: str, structure: Structure, dry_run: bool = False): # noqa """ TODO: Update model structure by adjusting layers (add, modify, delete) or rewiring the connections between layers. Examples: Fine-tune the model by modify the layer with name 'fc' (last laye...
80,112
def _get_consecutive_and_overlapping_fronts(onset_fronts, offset_fronts, onset_front_id, offset_front_id): """ Gets an onset_front and an offset_front such that they both occupy at least some of the same frequency channels, then returns the portion of each that overlaps with the other. """ # Get the...
80,113
def create(req, sock, client, server, cfg): """ :param req: ``.message.Request`` 请求 :param sock: client sock :param client: client addr, e.g. ``('127.0.0.1', 10000)`` :param server: server sock, e.g. ``('127.0.0.1', 8000)`` """ resp = Response(req, sock, cfg) # set initial environ e...
80,114
def test_basex_gaussian_sigma_07_reg_10_corrected(): """Check a gaussian solution for BASEX: small sigma, regularized, corrected""" basex_gaussian(sigma=0.7, reg=10, cor=True, tol=6e-3)
80,115
def main( module: str, queues: Optional[str], # noqa max_threads: int, # noqa max_processes: Optional[int], # noqa management_interval: int, # noqa slot_wait_interval: int, # noqa consumer_backoff_factor: int, # noqa consumer_backoff_floor: int, # noqa consumer_backoff_ceiling...
80,116
def time_formatted(event:str, mode:str, t: float, dnf: bool=False) -> str: """ Reverses parse_time """ if t == statistics.DNF: return "DNF" if dnf else "" if event in ["3x3x3 Fewest Moves", "3x3x3 Multi-Blind"]: if event == "3x3x3 Fewest Moves" and mode == "average": return str(t...
80,117
def tsum(x: T.Tensor, axis: int=None, keepdims: bool=False) -> T.FloatingPoint: """ Return the sum of the elements of a tensor along the specified axis. Args: x: A float or tensor. axis (optional): The axis for taking the sum. keepdims (optional): If this is set to true, the dimensi...
80,118
def ask_multi_choices(prompt="Add to choices : ", choices_list=[], to_save="s", to_quit="q"): """Collect multi choices from list Keyword Arguments: prompt {str} -- the question method (default: {"Add to choices : "}) choices_list {list} -- the available options (default: {[]}) to_sa...
80,119
def DtypeToType(dtype): """Converts a Numpy dtype to the FeatureNameStatistics.Type proto enum.""" if dtype.char in np.typecodes['AllFloat']: return GetFeatureStatsProtoDef().FLOAT elif (dtype.char in np.typecodes['AllInteger'] or dtype == np.bool or np.issubdtype(dtype, np.datetime64) or np.i...
80,120
def test_csv(filename, ncols=88): """ https://docs.python.org/3/library/csv.html """ import csv nlines = 0 with open(filename, newline='') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='"', doublequote=True, escapechar='"', quoting=csv.QUOTE_NONE, ...
80,121
def register_prelu_func(graph): """Register Prelu op with function def, this is need for importing graph_def with unregistered Prelu op. Args: graph: A tf.Graph object to insert prelu function into. """ # Create a function for Prelu op @function.Defun(tf.float32, tf.float32, func_name='Prelu') def pr...
80,122
def multi_options(op): """ Multi Value Options options number must equal nargs """ for option in op: print(option)
80,123
def _parseSteps(raw_steps, lang=None): """ :type raw_steps: Iterable[dict] :param lang: (Optional) Descriptor of the language to query the step, without any specification of encoding or modifiers. :type lang: str | None :rtype: Iterable[TutorialStep] """ def getI18nStringForStepKey(...
80,124
def profile(length=25): """ 在请求分析器的监视下运行程序 :param length: :return: """ profile_dir = os.path.join(basedir, 'tmp\profile') from werkzeug.contrib.profiler import ProfilerMiddleware app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length]) app.run()
80,125
def train(): """ Performs training and evaluation of ConvNet model. First define your graph using class ConvNet and its methods. Then define necessary operations such as savers and summarizers. Finally, initialize your model within a tf.Session and do the training. --------------------------- How to eva...
80,126
def test_generate_entity_id_given_keys(): """Test generating an entity id given current ids.""" assert ( entity.generate_entity_id( "test.{}", "overwrite hidden true", current_ids=["test.overwrite_hidden_true"], ) == "test.overwrite_hidden_true_2" ...
80,127
def legendre_P(n,x): """ Returns the Legendre polynomial of the first kind for integers `n > -1`. REFERENCE: - AS 22.5.35 page 779. EXAMPLES:: sage: P.<t> = QQ[] sage: legendre_P(2,t) 3/2*t^2 - 1/2 sage: legendre_P(3, 1.1) 1.67750000000000 sage...
80,128
def spawn_dates_times(df, spawn_dates=True, spawn_times=False): """ Build date/times column from a timeseries dataframe :param df: (pd.DataFrame) - dataframe with datetime index :param spawn_dates: (boolean) - whether to spawn year, month, day cols :param spawn_times: (boolean) - whether to spawn h...
80,129
def parse_date(string, format=None): """ :type string: str :type format: NoneType or str :rtype: NoneType or date """ if format is None: formats = FORMATS else: formats = [format] for f in formats: try: return dt.datetime.strptime(string, f).date() except ValueError: pass return None
80,130
def adhesion_structure_vertical_for_dual_extruder(file_name, adhesion_type, no_extruder=2): """ Generate adhesion structure for vertical adhesion :param file_name: source gcode file :param adhesion_type: "blob" or "grid" :param materials: material list in sequential order :param target_layers: i...
80,131
def impurity_of_split_rec(points: List[DataPoint], split: float) -> float: """ Recursive method wrapper to split the data points into two arrays based on the split point provided and return the gini impurity measure for that split point. """ print("Printing split: {}".format(split)) smaller = [] ...
80,132
def GetConsoleOriginalTitle() -> str: """ GetConsoleOriginalTitle from Win32. Return str. Only available on Windows Vista or higher. """ if IsNT6orHigher: arrayType = ctypes.c_wchar * MAX_PATH values = arrayType() ctypes.windll.kernel32.GetConsoleOriginalTitleW(values, ct...
80,133
def close_conn(db_conn: Tuple[sql.Cursor, sql.Connection]): """ Closes the connection to the database with cursor and connection objects <db_conn>. :param db_conn: Cursor and connection to database. :return: None """ c, conn = db_conn conn.close()
80,134
def build_train_mf(make_obs_ph, q_func, num_actions, optimizer, grad_norm_clipping=None, gamma=1.0, scope="mfec", alpha=1.0, beta=1.0, theta=1.0, latent_dim=32, ib=True, reuse=None): """Creates the train function: Parameters ---------- make_obs_ph: str -> tf.placeholder or TfInput ...
80,135
def _batch_into_watershed_subsets( watershed_root_dir, degree_separation, done_token_path, watershed_subset=None): """Construct geospatially adjacent subsets. Breaks watersheds up into geospatially similar watersheds and limits the upper size to no more than specified area. This allows for ...
80,136
def connection(): """ Function that provide the SQL connection to be uses by the ORM. Returns ------- (bool, SQL connection object) The first element of the tuple indicates whether the connection is to be closed after every query. The second element should provide an SQL connection ...
80,137
def mergeinput_preprocess_duo(df1, df2): """ Merge 2 data frames into one for full analysis. Output will be two form: long form and wide form long form: simply add 2 df on top of each other wide form: each row represents a request coordinate with result from both run. -> calculate ED relevant cols f...
80,138
def mbeans(query=None): """ Returns a list of all the available MBeans in the server. The optional query parameter will filter the list by objectname """ return server.getQueryMBeans(ObjectName(query), None)
80,139
def process(line): """For each line of input, _____.""" line = line[:-1] # Do something more here! print(line.lower())
80,140
def is_decimal_dtype(obj): """Check whether an array-like or dtype is of the decimal dtype. Parameters ---------- obj : array-like or dtype The array-like or dtype to check. Returns ------- bool Whether or not the array-like or dtype is of the decimal dtype. """ ret...
80,141
def run_queued(function, *args, **kwargs): """Queue a function that will be called by the Core object after a very small time. This method must be called from the thread where the Core object has been initialised or from another thread created by the run_thread() method. Use it for safely call Tkinter...
80,142
def assert_it(img, lbl): """ Add assertation between augmentation operation :param img: :param lbl: :return: """ # Check input image assert_msg = "input image should be HxW, with type of np.uint8" assert isinstance(img, np.ndarray), assert_msg assert np.ndim(img) == 2, assert_msg...
80,143
def calculate_F1(max, compensate = 0, threshold = 0.5): """ Args: max (M,N) return: AP,TP,FP,FN,precision,recall,F1 """ if compensate < 0: compensate = 0 TP = 0 FP = 0 FN = 0 for i in range(len(max)): if max[i] > threshold: TP = TP + 1 ...
80,144
def runtime(X, y, model_generator, method_name): """ Runtime (sec / 1k samples) transform = "negate_log" sort_order = 2 """ old_seed = np.random.seed() np.random.seed(3293) # average the method scores over several train/test splits method_reps = [] for i in range(3): X_trai...
80,145
def get_mask(json_data, microplate_names): """Return wrapper for numpy array.""" return ControlMask(json_data, microplate_names)
80,146
def utc2sec(*utc): """Convert list composed of year,month,day,hour,minute,second [,microsec] :param utc: list of year,month,day,hour,minute,second :returns: number of seconds since the epoch 0001-01-01 """ utc2=list(utc) if len(utc)<7: utc2.append(0) return int(utc2micro(*utc2)/10*...
80,147
def testGlobalBufferOnlyClear(): """ """ io = startHubProcess() exp = io.devices.experiment assert exp != None io.sendMessageEvent("Message Should Be Cleared Global Only") # clear only the global event buffer io.clearEvents(device_label=None) events = io.getEvents() assert len(e...
80,148
def subprocess_run(subprocessCMD, shell=False): """ Run a subprocess command, passed by dict of arguments. Executes by default with shell=False, and then logging STDOUT and STDERR """ procCall = subprocess.run(subprocessCMD,stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=shell) logging.info('--...
80,149
def scale_sample(xy_sample,grid): """ This function is used to apply the shifts and scaling to the sample. """ sample = xy_sample.copy() if grid.dim == 2: sample[:,2] = sample[:,2] + grid.shifts[0]*sample[:,0] + grid.shifts[1]*sample[:,1] sample[:,0] = sample[:,0]/grid.b0 sample...
80,150
def test_inverted_path_shape(): """Tests that the inverted path is of the right shape""" for batch_size in (1, 2, 5): for input_stream in (2, 3, 10): for input_channels in (1, 2, 6): path = torch.rand((batch_size, input_stream, input_channels)) for depth in (2...
80,151
def radius_aperture(info_dict): """ Compute the radius of the aperture Parameters ---------- info_dict: dictionary wavelength: float wavelength in angstrom Returns -------- aperture: float radius of the aperture in arcsec """ if info_dict["psf_type"] == "gaussi...
80,152
def find_file(filename): """ Finds a file in the directory that has the same name as the parameter <filename>. If the file does not exist, the directory is searched for <filename.*> instead, and if only one match is found, that particular filename is returned. """ if isinstance(filename, F...
80,153
def FermiDirac(Ef, EJ, T): """ Returns the Fermi-Dirac probability distribution, given the crystal's Fermi energy, the temperature and the energy where the distribution values is required. Args: | Ef: Fermi energy in J | EJ: Energy in J | T : Temperature in K Returns: ...
80,154
def start_tornado_server(port=HTTP_PORT): """ Start the Tornado server """ # Setup the application context handlers = [ (r"/", MainHandler), (r"/static/(.*)", web.StaticFileHandler, {"path": STYLES_DIR}), ] settings = dict(template_path=TEMPLATES_DIR) application = t...
80,155
def glXQueryVersion(dpy): """ dpy - Display* return - bool, int, int: support, major, minor""" major = Numeric.zeros(1, Numeric.Int32) minor = Numeric.zeros(1, Numeric.Int32) res = _glxlib.glXQueryVersion(dpy, major, minor) return res, major[0], minor[0]
80,156
def reset_failed_assoc(failed_status='status != 2', reset=True, remove_files=True): """ Reset failed visits """ import astropy.time import numpy as np from grizli.aws import db failed_assoc = db.SQL(f"""SELECT * FROM assoc_table WHERE {failed_status}"...
80,157
def deinterlace_to_preallocated(interlaced, even_rows, odd_rows): """ Deinterlaces the interlaced image into even_rows and odd_rows images, which must be pre-allocated, and the correct size. """ validate_interlaced_image_sizes(even_rows, odd_rows, interlaced) even_rows[:, :, :] = interlaced[0::...
80,158
def get_message_data(): """Default valid message data.""" return { 'message': ''' -----BEGIN PGP MESSAGE----- Version: Keybase OpenPGP v2.0.8 Comment: https://keybase.io/crypto wcBMA6Uvn0xuUMOaAQf/bGf4y9ZfKChSOAJs4M5V7K3nDC2p/sUNcfy8FzoIl9VE j2vT3bMZsaT3cJkQMfABqWgzq8VlQjRP1/m+bBX4jRUYVVpxxVZzumtle53qG...
80,159
def usgs_kyanite_parse(*, df_list, source, year, **_): """ Combine, parse, and format the provided dataframes :param df_list: list of dataframes to concat and format :param args: dictionary, used to run flowbyactivity.py ('year' and 'source') :return: df, parsed and partially formatted to fl...
80,160
def merge_root_infoplists( ctx, input_plists, output_plist, output_pkginfo, bundle_id = None, child_plists = [], child_required_values = [], include_executable_name = True, version_keys_required = False): """Creates an action that merges Info.p...
80,161
def banner_create_activity(sender, instance, created, **kwargs): """ banner创建成功 保存 activity_stream """ if created: user = User.objects.filter(merchant=instance.merchant).first() save_activitystream.delay(actor=user.nickname, actor_id=user.id, ...
80,162
def navigate_to_default_page_cms_section(admin_browser, default_page_title): """Navigate to the news page section of the CMS. Args: default_page_title (str): The title of a default page modelself. """ admin_browser.click_link_by_text('Pages') admin_browser.find_by_xpath('//span[@class="ico...
80,163
def prepare_element(sample_nist_component_def: component.ComponentDefinition): """Prepare a target element for remove tests.""" element = Element(sample_nist_component_def) parties: List[common.Party] = [] parties.append( common.Party(**{ 'uuid': 'ff47836c-877c-4007-bbf3-c9d9bd80500...
80,164
def axes_match(ax_array): """Helper to ensure y-axis limits match. Input should be 2x1 arrays of axes. """ # Lower limit ax_min = min(ax_array[0].get_ylim()[0], ax_array[1].get_ylim()[0]) # Upper limit ax_max = max(ax_array[0].get_ylim()[1], ax_array[1].get_ylim()[1]) lim = (ax_min, ax...
80,165
def flow_warp_tensor(mask, flow, coord=None): """ :param mask: 1xCxHxW :param flow: HxWx2 :return: """ if coord is None: shape = mask.shape[-2:] coord = torch.ones(shape).cuda().long() coord = torch.nonzero(coord).float() flow = flow2coord(flow, coord) flow = flow.unsqueeze(0) if mask.sha...
80,166
def filter_filename(dirname, include=[], exclude=[], array_id=None): """Filter filename in a directory""" def get_array_id(filename): array_id = filename.split("_")[-2] try: array_id = eval(array_id) except: pass return array_id filename_collect = [] ...
80,167
def get_filestore(config): """Returns the correct filestore based on the platform in |config|. Raises an exception if there is no correct filestore for the platform.""" # TODO(metzman): Force specifying of filestore. if config.platform == config.Platform.EXTERNAL_GITHUB: return filestore.github_actions.Gith...
80,168
def neighborhood_ambulance_combinations(neighborhoods, total_ambulance): """ This function returns all possible combinatios for neighborhoods and the number of ambulances they hold. Inputs: neighborhoods (Array of string) neighborhood names that contains ambulance stations total_ambula...
80,169
def get_number_of_desktops(): """ Returns the number of virtual desktops. :return: The number of desktops. :rtype: util.PropertyCookieSingle (CARDINAL/32) """ cook = util.get_property(root, '_NET_NUMBER_OF_DESKTOPS') return util.PropertyCookieSingle(cook)
80,170
def scalar_to_array(input_x): """ Converts a scalar to a `Tensor`. Args: input_x (Union[int, float]): The input is a scalar. Only constant value is allowed. Returns: Tensor. 0-D Tensor and the content is the input. Raises: TypeError: If `input_x` is neither int nor float. ...
80,171
def handle_action(): """Handle a response when a user clicks a button from Wizzy in Slack""" event_data = json.loads(request.form["payload"]) user = event_data['user']['id'] # if channel empty, it's a shortcut if event_data.get('channel') is None: # shortcut - grab callback, put in action di...
80,172
def calc_permutation_matrix( system_order: List[int], size_list: List[int] ) -> np.ndarray: """calculate permutation matrix. permutation matrix can reorder the system order to [0, 1,..., n]. Parameters ---------- system_order : List[int] system_order before permutation. size_list :...
80,173
def MakePlotsWithMLEStats(DataDirectory, fname_prefix, basin_list = [0], start_movern = 0.2, d_movern = 0.1, n_movern = 7, parallel=False): """ This function makes a chi-elevation plot for each basin and each value of m/n and prints the MLE value between the tributaries and the main stem. ...
80,174
def interface(agents, envrionment, steps): """ Agents-Environment Interface. Let the agents interact. Parameters ---------- agents : iterable of agents envrionment : envrionment steps : int (Number of interaction steps) """ def allagentinteract(obs, rews): actions = [] ...
80,175
def update_screen(ai_settings,screen,stats,ship,bullets,aliens,play_button,sb): """Updaate the screen images and returns to the new screen""" #Redraw the screen every cycle screen.fill(ai_settings.bg_color) #Issue3 for bullet in bullets.sprites(): bullet.draw_bullet() ship.blitme() alien...
80,176
def cvt_horizontal_flip( sample_input: Dataset, sample_output: Dataset, probability: float = 0.5 ) -> Dataset: """Converts the sample_input dataset to horizontal flips in sample_output dataset. Args: sample_input: input dataset passed to generate output dataset. sample_output: output datase...
80,177
def register_model_list_columns(model, columns): """ Define which columns will be displayed in the generic list template for a given model """ model_list_columns.setdefault(model, []) model_list_columns[model].extend(columns)
80,178
def data_generation(config_file, DATA_FP, startdate=None, enddate=None, forceupdate=False): """ Generate the map and feature data for this city Args: config_file - path to config file DATA_FP - path to data directory, e.g. ../data/boston/ startdate (optional) ...
80,179
def search(): """Display search options""" return render_template("search.html")
80,180
def get_client_setting(setting: str, cid: str) -> ClientSetting: """Return client setting based on setting name and cid.""" for client_setting in get_setting(setting).clients: if client_setting.cid == cid: return client_setting raise ClientSettingNotFound()
80,181
def test_dataset_edit_no_change(runner, client, project, dirty): """Check metadata editing does not commit when there is no change.""" if dirty: with (client.path / 'dirty_file').open('w') as fp: fp.write('a') result = runner.invoke( cli, ['dataset', 'create', 'dataset', '-t', '...
80,182
def between(x, min, max, exclude_max=UNSET) -> ProcessBuilder: """ Between comparison :param x: The value to check. :param min: Lower boundary (inclusive) to check against. :param max: Upper boundary (inclusive) to check against. :param exclude_max: Exclude the upper boundary `max` if set to `t...
80,183
def parse_description(issue): """ :param issue: Issue object. :return: ROGA type: (a string that should be listeria/salmonella/vtec - otherwise they'll get others later. seq_ids: List of seqIDs which will later be written to file and used in ROGA report generation. """ # Take whatever i...
80,184
def test_to_tree_multi_level(): """ Test a sentence with several levels of dependencies deep is properly parsed. """ source = ( '# sent_id = fr-ud-dev_00002\n' '# text = Les études durent six ans mais leur contenu diffère donc selon les Facultés.\n' '1 Les le DET _ Definite=Def|G...
80,185
def feedback(data: FeedbackData) -> str: """ Pass the request data as FeedbackData object, as this can be customised in the model.py file to adapt based on deployed model to make predictions Parameters: data: Parse the request body data based on your model schema and pass this to pred...
80,186
def get_dataset(id_): """특정 dataset에 대한 정보 반환 Args: id_ (int): dataset ID Returns: _type_: _description_ """ result_json = {"datasetName": "", "image_metadata": []} query = Dataset.query.filter_by(id=id_).first() result_json["datasetName"] = query.name query = ImageM...
80,187
def deprecation_warning(obj, dep_from, dep_to): """Prints a deprecation warning. Parameters ---------- obj: class The class with the deprecated attribute dep_from: str old (deprecated) name of the attribute dep_to: str new name for the attribute """ warnings.warn...
80,188
def test_metathesis(word, anagram): """ Tests if a word and an anagram are a metathesis pair This is only true if the words are I. Anagrams II. Differ in two places """ count = 0 for para in zip(word, anagram): if para[0] != para[1]: count += 1 return count == 2
80,189
def get_plugin_manager() -> PluginManager: """ Gets the plugin manager and automatically registers internal plugins. Returns: The plugin manager. """ # Import plugins within the function to prevent circular imports and partial initialization from aac.plugins import ( gen_json, ...
80,190
def filegen(template_file, new_filename, **kwargs): """ Generates a new text file format based on an existing FAST file. Useful for creating .fst, .dat, or .inp files with specified parameter modifications. Note that MoorDyn files, due to their unique format, are not compatible with this functio...
80,191
def create_if_necessary(ctx, directory): """Ask user to allow directory creation if necessary.""" msg = f"Directory {directory} does not exist. Create it?" if not osp.exists(directory): if not click.confirm(msg): ctx.exit() os.makedirs(directory) click.echo(f"Created dire...
80,192
def register_command(subparser): """Register the sub-command with any additional arguments.""" parser = subparser.add_parser('serve', help='Serve the contents of the publishers output files') parser.set_defaults(func=_main) parser.add_argument('--port', '-p', type=int, help='Port that the server will b...
80,193
def get_token(username, password): """Returns a new token for login credentials.""" payload = {'username': username, 'password': password} key = username + password # simple key token = jwt.encode(payload, key, algorithm='HS256') # Convert bytes to string token = token.decode('utf-8') # Sto...
80,194
def standardize(ds, dim="time"): """Standardize Dataset/DataArray .. math:: \\frac{x - \\mu_{x}}{\\sigma_{x}} Args: ds (xarray object): Dataset or DataArray with variable(s) to standardize. dim (optional str): Which dimension to standardize over (default 'time'). Returns: ...
80,195
def predict(model, image_files, resize=False, show_image=True, cloud=None): """Predict using an model in a local or GCS directory (offline), or a deployed model (online). Args: model: if cloud is None, a local or GCS directory of a trained model. Otherwise, it specifies a deployed model identified by m...
80,196
def retrieve_past_timestamps(ref_timestamp, streams_stamps, prev_timestamp=0): """ get timestamps between two annotated frames. Parameters ---------- ref_timestamp : The timestamp of the annotated image. streams_stamps : Timestamps dict of the whole sequence prev_timestamp : The timestamp o...
80,197
def topics_offset_distance( kafka_client, group, topics, offset_storage='zookeeper', ): """Get the distance a group_id is from the current latest offset for topics. If the group is unkown to kafka it's assumed to be an offset 0. All other errors will not be caught. This method forc...
80,198
def get_first_meeting_day_num(days: str): """ Returns the number representing the day of first meeting of the week :param days:str: Days field of WebReg list, example: "MWF" """ day_nums = get_day_nums(days) first_day_num = day_nums[0] return first_day_num
80,199