content
stringlengths
22
815k
id
int64
0
4.91M
def get_systemd_services(service_names): """ :param service_names: {'service_unit_id': 'service_display_name'} e.g., {'cloudify-rabbitmq.service': 'RabbitMQ'} """ systemd_services = get_services(service_names) statuses = [] services = {} for service in systemd_services: is_servic...
11,000
def json_handler(obj): """serialize non-serializable data for json""" import datetime from werkzeug.local import LocalProxy # serialize date if isinstance(obj, (datetime.date, datetime.timedelta, datetime.datetime)): return unicode(obj) elif isinstance(obj, LocalProxy): return unicode(obj) else: raise Ty...
11,001
def downgrade(): """Reverts changes performed by upgrade().""" op.drop_refresh_updated_at_trigger("mod_release") op.drop_table("mod_release")
11,002
def _random_prefix(sentences): """ prefix random generator input: list of input sentences output: random word """ words = _word_dict(sentences) return choice(words)
11,003
def bootstrap_gitdir(): """Installs `gitdir` and configures `git`. Requires the `python` setup.""" subprocess.run(['git', 'config', '--global', 'merge.conflictstyle', 'diff3'], check=True) gitdir_gitdir = git_dir(existing_only=False) / 'github.com' / 'fenhl' / 'gitdir' if not gitdir_gitdir.exists(): ...
11,004
def test_build_request_no_server(): """ Test Building of URL """ # TODO: add put and delete request for method_type in ["get", "post"]: api_request = create_api_request(GET_ITEMS_ENDPOINT, server_description="", method_type=method_type) assert api_request.build_url() is None
11,005
def call(*args, **kwargs): """Thin wrapper over the `prelim_call` function. This function applies a deduplication procedure to preliminary calls. """ for call in merge_adjacent(dedup(prelim_call(*args, **kwargs))): yield call
11,006
def user_logout(*args, **kwargs): # pylint: disable=unused-argument """ This endpoint is the landing page for the logged-in user """ # Delete the Oauth2 token for this session log.info('Logging out User: %r' % (current_user,)) delete_session_oauth2_token() logout_user() flash('You...
11,007
def create_ith_simcat(d=None): """Write 'simcat' and 'skipped_ids' tables for a given sample of sources Args: d: {'Samp': fits_table for the properties of sources in the brick 'brickwcs': WCS object for the brick 'metacat': fits_table with configuration params for the simulated ...
11,008
def redraw_frame(image, names, aligned): """ Adds names and bounding boxes to the frame """ i = 0 unicode_font = ImageFont.truetype("DejaVuSansMono.ttf", size=17) img_pil = Image.fromarray(image) draw = ImageDraw.Draw(img_pil) for face in aligned: draw.rectangle((face[0], face[...
11,009
def _tp_relfq_name(tp, tp_name=None, assumed_globals=None, update_assumed_globals=None, implicit_globals=None): # _type: (type, Optional[Union[Set[Union[type, types.ModuleType]], Mapping[Union[type, types.ModuleType], str]]], Optional[bool]) -> str """Provides the fully qualified name of a type rela...
11,010
def is_dapr_actor(cls: Type[Actor]) -> bool: """Checks if class inherits :class:`Actor`. Args: cls (type): The Actor implementation. Returns: bool: True if cls inherits :class:`Actor`. Otherwise, False """ return issubclass(cls, Actor)
11,011
def save_v1(filename, data, folder="", compressed=False): """ Create a folder structure inside a zipfile Add .json and .npy and .npz files with the correct names And subfolders for more complicated objects with the same layout Each class should have a save and a load method which can be used...
11,012
def compute_summary(print_terminal=False, save=False): """ Computes benchmark summary. """ # TI ti_percentage = marche_df['occupazione_ti'].iloc[-1] # increment TI ti_rolling_7_mean = marche_df['occupazione_ti'].rolling(7).mean() ti_perc_increment = (ti_rolling_7_mean.iloc[-1] - ti_rol...
11,013
def unpickle(file): """ unpickle the data """ fo = open(file, 'rb') dict = cPickle.load(fo) fo.close() return dict
11,014
def delete_entry(cur, id): """Erase entry""" if (input('Are you sure [yN]? ').lower().strip() == 'y'): entries = cur.execute('SELECT * FROM mytodos') for entry in entries: if int(id) in entry: cur.execute(f"DELETE FROM mytodos WHERE ID={id}")
11,015
def _calc_norm_gen_prob(sent_1, sent_2, mle_lambda, topic): """ Calculates and returns the length-normalized generative probability of sent_1 given sent_2. """ sent_1_len = sum([count for count in sent_1.raw_counts.values()]) return _calc_gen_prob(sent_1, sent_2, mle_lambda, topic) ** (1.0 / sent_1...
11,016
def isomorphic(l_op, r_op): """ Subject of definition, here it is equal operation. See limintations (vectorization.rst). """ if l_op.getopnum() == r_op.getopnum(): l_vecinfo = forwarded_vecinfo(l_op) r_vecinfo = forwarded_vecinfo(r_op) return l_vecinfo.bytesize == r_vecinfo.b...
11,017
def partition5(l, left, right): """ Insertion Sort of list of at most 5 elements and return the position of the median. """ j = left for i in xrange(left, right + 1): t = numpy.copy(l[i]) for j in xrange(i, left - 1, -1): if l[j - 1][0] < t[0]: break l[j] = l[j - 1] l[j] = t return int(math.floor(...
11,018
def max_validator(max_value): """Return validator function that ensures upper bound of a number. Result validation function will validate the internal value of resource instance field with the ``value >= min_value`` check. Args: max_value: maximum value for new validator """ def valid...
11,019
def main(): """ Function which contains main program's cycle. """ path = input("Enter the file path: ") try: res = json_read(path) except: print("There is no such file! Exiting...") return obj_path = [] while True: print("-" * 100) temp = choice(re...
11,020
def test_song_from_search_term(): """ Tests if Song.from_search_term() works correctly. """ song = Song.from_search_term("Dirty Palm - Ropes") assert song.name == "Ropes" assert song.artists == ["Dirty Palm", "Chandler Jewels"] assert song.album_name == "Ropes" assert song.album_artist...
11,021
def standalone_job_op(name, image, command, gpus=0, cpu_limit=0, memory_limit=0, env=[], tensorboard=False, tensorboard_image=None, data=[], sync_source=None, annotations=[], metrics=['Train-accuracy:PERCENTAGE'], arena_image='cheyang/arena_launcher:v0.5', timeout_hours...
11,022
def main(dataset, hb_thr): """The main processing function. Keyword arguments: >>> dataset: The loaded trajectory data generated by TCA. >>> hb_thr: The hard braking threshold, float. RETURN: Time of detected hard braking, Locations of involved vehicles, the deceleration value, and the...
11,023
def load_randompdata(dataset_str, iter): """Load data.""" names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph'] objects = [] for i in range(len(names)): with open("data/ind.{}.{}".format(dataset_str, names[i]), 'rb') as f: if sys.version_info > (3, 0): objects.appen...
11,024
def page_to_reload(): """ Returns page that is refreshed every argument of content attribute in meta http-equiv="refresh". """ val = knob_thread.val year = int(val * 138./256 + 1880) return ( """<!DOCTYPE html> <html> <head><meta http-equiv="refresh" content=".2"> <style> h1 {{color:...
11,025
def svn_log_changed_path2_create(*args): """svn_log_changed_path2_create(apr_pool_t pool) -> svn_log_changed_path2_t""" return _core.svn_log_changed_path2_create(*args)
11,026
def plot_timeseries(model, radius, lon, save=False, tag=''): """ Plot the solar wind model timeseries at model radius and longitude closest to those specified. :param model: An instance of the HUXt class with a completed solution. :param radius: Radius to find the closest model radius to. :param lon...
11,027
def missing_values_rf_rebase(repo, master, branch, rebase_branch): """ >>> import sys >>> sys.path.append('/home/joncrall/code/ibeis/_scripts') >>> from setup_special_sklearn import * >>> dpath = ut.truepath('~/code/scikit-learn') >>> master = 'master' >>> repo = ut.Repo(dpath=dpath) >>>...
11,028
def convert_csv_to_excel(csv_path): """ This function converts a csv file, given by its file path, to an excel file in the same directory with the same name. :param csv_path:string file path of CSV file to convert :return: string file path of converted Excel file. """ (file_path, file...
11,029
def check_from_dict(method): """A wrapper that wrap a parameter checker to the original function(crop operation).""" @wraps(method) def new_method(self, *args, **kwargs): word_dict, = (list(args) + [None])[:1] if "word_dict" in kwargs: word_dict = kwargs.get("word_dict") ...
11,030
def iter_model_rows(model, column, include_root=False): """Iterate over all row indices in a model""" indices = [QtCore.QModelIndex()] # start iteration at root for index in indices: # Add children to the iterations child_rows = model.rowCount(index...
11,031
def env_observation_space_info(instance_id): """ Get information (name and dimensions/bounds) of the env's observation_space Parameters: - instance_id: a short identifier (such as '3c657dbc') for the environment instance Returns: - info: a dict containing 'name' (such as 'Di...
11,032
def build_target_from_transitions( dynamics_function: TargetDynamics, initial_state: State, final_states: Set[State], ) -> Target: """ Initialize a service from transitions, initial state and final states. The set of states and the set of actions are parsed from the transition function. Thi...
11,033
def citation(dll_version: Optional[str] = None) -> dict: """ Return a citation for the software. """ executed = datetime.now().strftime("%B %d, %Y") bmds_version = __version__ url = "https://pypi.org/project/bmds/" if not dll_version: # assume we're using the latest version d...
11,034
def comment_pr_(ci_data, github_token): """Write either a staticman comment or non-staticman comment to github. """ return sequence( (comment_staticman(github_token) if is_staticman(ci_data) else comment_general), post(github_token, ci_data), lambda x: dict(status_code=x.status_c...
11,035
def response_loss_model(h, p, d_z, d_x, d_y, samples=1, use_upper_bound=False, gradient_samples=0): """ Create a Keras model that computes the loss of a response model on data. Parameters ---------- h : (tensor, tensor) -> Layer Method for building a model of y given p and x p : (tenso...
11,036
def get_hourly_load(session, endpoint_id, start_date, end_date): """ :param session: session for the database :param endpoint_id: id for the endpoint :param start_date: datetime object :param end_date: datetime object and: end_date >= start_date :return: """ numdays = (end_date - start_d...
11,037
def startend(start=None, end=None): """Return TMIN, TAVG, TMAX.""" # Select statement sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)] if not end: # Calculate TMIN, TAVG, TMAX for dates greater than start results = session.query(*sel).\ ...
11,038
def configure_camera(config): """ Configures the camera. :param config: dictionary containing BARD configuration parameters optional parameters in camera. source (default 0), window size (default delegates to cv2.CAP_PROP_FRAME_WIDTH), calibration directory and roi (region of...
11,039
def munsell_value_Moon1943(Y: FloatingOrArrayLike) -> FloatingOrNDArray: """ Return the *Munsell* value :math:`V` of given *luminance* :math:`Y` using *Moon and Spencer (1943)* method. Parameters ---------- Y *luminance* :math:`Y`. Returns ------- :class:`np.floating` or :...
11,040
def make_heatmap_and_hist(mag, hist, show_plot): """Handles creating and then labeling the one magnitude heatmap and corresponding histogram. Parameters ---------- mag: int The magnitude that should be plotted int he heatmpa. fig: figure object The figure object the pie chart sh...
11,041
def log_errors(func): """ A wrapper to print exceptions raised from functions that are called by callers that silently swallow exceptions, like render callbacks. """ @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exceptio...
11,042
def get_urls( url_queue: Queue, images: List[Tuple[str, Image]], ImageClass: type, ) -> None: """Processes URL sources from a/some separate thread(s)""" source = url_queue.get() while not interrupted.is_set() and source: log(f"Getting image from {source!r}", logger, verbose=True) ...
11,043
def count_total_words(sentence_list): """ 문장 리스트에 있는 단어를 셉니다. :param sentence_list: 단어의 리스트로 구성된 문장 리스트 :return: 문장에 있는 단어의 개수 """ return sum( [count_words_per_sentence(sentence) for sentence in sentence_list] )
11,044
def grib_index_select_double(iid,key,val): """ @brief Select the message subset with key==value. The value is a double. The key must have been created with integer type or have integer as native type if the type was not explicitly defined in the index creation. \b Examples: \ref index.py "inde...
11,045
def translate_dbpedia_url(url): """ Convert an object that's defined by a DBPedia URL to a ConceptNet URI. We do this by finding the part of the URL that names the object, and using that as surface text for ConceptNet. This is, in some ways, abusing a naming convention in the Semantic Web. The ...
11,046
def setSecurityPolicy(aSecurityPolicy): """Set the system default security policy. This method should only be caused by system startup code. It should never, for example, be called during a web request. """ last = _ImplPython._defaultPolicy _ImplPython._defaultPolicy = aSecurityPolicy retur...
11,047
def map_sentence2ints(sentence): """Map a sentence to a list of words.""" word_list = re.findall(r"[\w']+|[.,!?;]", sentence) int_list = [const.INPUTVOCABULARY.index(word) for word in word_list] return np.array(int_list).astype(np.int32)
11,048
def get_api_key( api_key_header: str = Security( APIKeyHeader(name=settings.API_KEY_HEADER, auto_error=False) ) ) -> str: """ This function checks the header and his value for correct authentication if not a 403 error is returned: - api_key_header = Security api header https://git...
11,049
def add_pred_to_test(test_df, pred_np, demo_col_list, days): """ derived from Tensorflow INPUT: - df (pandas DataFrame) - group (string) OUTPUT: - show_group_stats_viz """ test_df = test_df.copy() for c in demo_col_list: t...
11,050
def test_index(mock_app): """Test the CLI that creates indexes in the database""" runner = mock_app.test_cli_runner() assert runner # Test the command that updates the indexes without arguments result = runner.invoke(cli, ['index']) # It should print confirm message assert 'This will dele...
11,051
def getCriticality(cvss): """ color convention fot the cells of the PDF """ if cvss == 0.0: return ("none", "#00ff00", (0, 255, 0)) if cvss < 3.1: return ("low", "#ffff00", (255, 255, 0)) if cvss < 6.1: return ("medium", "#ffc800", (255, 200, 0)) if cvss < 9.1: return...
11,052
def combine_groups(groups: List[np.ndarray], num_features: int) -> np.ndarray: """ Combines the given groups back into a 2d measurement matrix. Args: groups: A list of 1d, flattened groups num_features: The number of features in each measurement (D) Returns: A [K, D] array conta...
11,053
def skippable(*prompts, argument=None): """ Decorator to allow a method on the :obj:`CustomCommand` to be skipped. Parameters: ---------- prompts: :obj:iter A series of prompts to display to the user when the method is being skipped. argument: :obj:`str` By default,...
11,054
def test(): """ unit tests """ import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests)
11,055
def collate( samples, pad_idx, eos_idx, left_pad_source=True, left_pad_target=False, input_feeding=True, ): """ 相对 fairseq.data.language_pair_dataset.collate 的区别是: 1. prev_output_tokens的key不再是target,而是 prev_output_tokens(因为自定义了prev_output_tokens,) ...
11,056
def _cache_name(address): """Generates the key name of an object's cache entry""" addr_hash = hashlib.md5(address).hexdigest() return "unsub-{hash}".format(hash=addr_hash)
11,057
def format_currency( value: Decimal, currency: str | None = None, show_if_zero: bool = False, invert: bool = False, ) -> str: """Format a value using the derived precision for a specified currency.""" if not value and not show_if_zero: return "" if value == ZERO: return g.led...
11,058
def guess_ghostscript() -> str: """Guess the path to ghostscript. Only guesses well on Windows. Should prevent people from needing to add ghostscript to PATH. """ if os.name != 'nt': return 'gs' # I'm not sure where to look on non-Windows OSes so just guess 'gs'. def sort_by_version(v: Pat...
11,059
def ExportFakeTF1ImageModule(*, input_image_height: int, input_image_width: int, output_feature_dim: int, export_path: str): """Makes a TF-hub image feature module for use in unit tests. The resulting module has the signature of a image model, but contains a minimal set of trainable ...
11,060
def supplemental_div(content): """ Standardize supplemental content listings Might not be possible if genus and tree content diverge """ return {'c': content}
11,061
def viewTypes(): """View types of item when sent through slash command""" user_id, user_name, channel_id = getUserData(request.form) checkUser(user_id) itemType = request.form.get('text') try: text = viewTypesItems(itemType) except ItemNotInPantry: reply = "Sorry! But either t...
11,062
def load_and_preprocess(): """ Load the data (either train.csv or test.csv) and pre-process it with some simple transformations. Return in the correct form for usage in scikit-learn. Arguments --------- filestr: string string pointing to csv file to load into pandas Returns ...
11,063
def _dates2absolute(dates, units): """ Absolute dates from datetime object Parameters ---------- dates : datetime instance or array_like of datetime instances Instances of pyjams.datetime class units : str 'day as %Y%m%d.%f', 'month as %Y%m.%f', or 'year as %Y.%f' Returns ...
11,064
def Mix_GetNumMusicDecoders(): """Retrieves the number of available music decoders. The returned value can differ between runs of a program due to changes in the availability of the shared libraries required for supporting different formats. Returns: int: The number of available music ...
11,065
def check_ft_grid(fv, diff): """Grid check for fft optimisation""" if np.log2(np.shape(fv)[0]) == int(np.log2(np.shape(fv)[0])): nt = np.shape(fv)[0] else: print("fix the grid for optimization \ of the fft's, grid:" + str(np.shape(fv)[0])) sys.exit(1) lvio = [] ...
11,066
def _concat_applicative( current: KindN[ _ApplicativeKind, _FirstType, _SecondType, _ThirdType, ], acc: KindN[ _ApplicativeKind, _UpdatedType, _SecondType, _ThirdType, ], function: KindN[ _ApplicativeKind, Callable[[_FirstType], Callable[[_UpdatedType], _UpdatedType]]...
11,067
def goto_x(new_x): """ Move tool to the new_x position at speed_mm_s at high speed. Update curpos.x with new position. If a failure is detected, sleep so the operator can examine the situation. Since the loss of expected responses to commands indicates that the program does not know the exact po...
11,068
def server_rename(adapter_id, server_id): """Renames a server using a certain adapter, if that adapter supports renaming.""" adapter = get_adapter(adapter_id) if not adapter: return output.failure("That adapter doesn't (yet) exist. Please check the adapter name and try again.", 501) if not ada...
11,069
def add_months(img, year, **kwargs): """Add months""" img_draw = ImageDraw.Draw(img) for month_index in range(1, 12 + 1): month_object = MonthObject( draw=img_draw, year=year, month=month_index, x=MONTHS_LEFT + MONTH_HORIZONTAL_STEP * ((month_index - 1...
11,070
def _to_absolute_uri(uri): """ Converts the input URI into an absolute URI, relative to the current working directory. :param uri: A URI, absolute or relative. :return: An absolute URI. """ if ":" in uri: #Already absolute. Is either a drive letter ("C:/") or already fully specified URI ("http://"). return pat...
11,071
def index(): """ Root URL response, load UI """ return app.send_static_file("index.html")
11,072
def plot_separacion2D(x, y, grado, mu, de, w, b): """ Grafica las primeras dos dimensiones (posiciones 1 y 2) de datos en dos dimensiones extendidos con un clasificador polinomial así como la separación dada por theta_phi """ if grado < 2: raise ValueError('Esta funcion es para grafica...
11,073
def restore_capitalization(word, example): """ Make the capitalization of the ``word`` be the same as in ``example``: >>> restore_capitalization('bye', 'Hello') 'Bye' >>> restore_capitalization('half-an-hour', 'Minute') 'Half-An-Hour' >>> restore_capitalization('usa', 'I...
11,074
def showWelcomeAnimation(): """Shows welcome screen animation of flappy bird""" messagex = int((SCREENWIDTH - IMAGES['message'].get_width()) / 2) messagey = int(SCREENHEIGHT * 0.12) basex = 0 # amount by which base can maximum shift to left baseShift = IMAGES['base'].get_width() - IMAGES['backg...
11,075
def test_loss_at_machine_precision_interval_is_zero(): """The loss of an interval smaller than _dx_eps should be set to zero.""" def f(x): return 1 if x == 0 else 0 def goal(l): return learner.loss() < 0.01 or learner.npoints >= 1000 learner = Learner1D(f, bounds=(-1, 1)) simp...
11,076
def params_document_to_uuid(params_document): """Generate a UUID5 based on a pipeline components document""" return identifiers.typeduuid.catalog_uuid(params_document)
11,077
def test_parseerror_initial_attrs(arg_names, args, exp_line, exp_column): """Test initial attributes of ParseError.""" msg = args[0] posargs, kwargs = func_args(args, arg_names) # Execute the code to be tested exc = ParseError(*posargs, **kwargs) assert isinstance(exc, Error) assert len(e...
11,078
def modify_account() -> typing.RouteReturn: """IntraRez account modification page.""" form = forms.AccountModificationForm() if form.validate_on_submit(): rezident = flask.g.rezident rezident.nom = form.nom.data.title() rezident.prenom = form.prenom.data.title() rezident.prom...
11,079
def fizzbuzz(end=100): """Generate a FizzBuzz game sequence. FizzBuzz is a childrens game where players take turns counting. The rules are as follows:: 1. Whenever the count is divisible by 3, the number is replaced with "Fizz" 2. Whenever the count is divisible by 5, the number is replaced...
11,080
def image_generator(mode='train'): """ mode : train, val, test """ X = [] y_age = [] y_gender = [] while True: for idx, row in df[df['set'] == mode].iterrows(): # images image_path = os.path.join(images_path, row['image_names']) image_ar...
11,081
def generate_lane_struct(): """ Generate the datatype for the lanes dataset :return: The datatype for the lanes dataset and the fill values for the lanes dataset """ lane_top_list = [] for item in [list1 for list1 in lane_struct if list1.__class__.__name__ == "LaneTop"]: lane_top_list.appen...
11,082
def clean_maya_environment(): """Contextmanager to reset necessary environment values for a clean run, then restore overwritten values. """ with temp_app_dir(): script_path = os.environ.get('MAYA_SCRIPT_PATH', '') module_path = os.environ.get('MAYA_MODULE_PATH', '') try: ...
11,083
def notification_list(next_id=None): # noqa: E501 """notification_list Get all your certificate update notifications # noqa: E501 :param next_id: :type next_id: int :rtype: NotificationList """ return 'do some magic!'
11,084
def _delete_dest_path_if_stale(master_path, dest_path): """Delete dest_path if it does not point to cached image. :param master_path: path to an image in master cache :param dest_path: hard link to an image :returns: True if dest_path points to master_path, False if dest_path was stale and was ...
11,085
def SendPost(user, password, xdvbf, cookie, session, url=URL.form): """ 根据之前获得的信息,发送请求 :param user: 学号 :param password: 密码 :param xdvbf: 验证码内容 :param cookie: 之前访问获得的cookie :param session: 全局唯一的session :param url: 向哪个资源发送请求 :return: response """ form_data = { "timestam...
11,086
def css_flat(name, values=None): """Все значения у свойства (по порядку) left -> [u'auto', u'<dimension>', u'<number>', u'<length>', u'.em', u'.ex', u'.vw', u'.vh', u'.vmin', u'.vmax', u'.ch', u'.rem', u'.px', u'.cm', u'.mm', u'.in', u'.pt', u'.pc', u'<percentage>', u'.%'] """ cu...
11,087
def disconnect(sid): """ The function is called when a client disconnects """ print('Client disconnected')
11,088
def prepare_mqtt(MQTT_SERVER, MQTT_PORT=1883): """ Initializes MQTT client and connects to a server """ client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect(MQTT_SERVER, MQTT_PORT, 60) return client
11,089
def load_inputs(mod, switch_data, inputs_dir): """ Import data to support unit commitment. The following files are expected in the input directory. All files and fields are optional. If you only want to override default values for certain columns in a row, insert a dot . into the other columns. ...
11,090
def process_message_impl(message): """Called on a background thread once for each message. It is the responsibility of the caller to gracefully handle exceptions""" log.debug(f"Processing: {message}") data_map = json.loads(message.data)['payload'] log.notify(f"pubsub: processing {json.dumps(data_ma...
11,091
def game(): """ Main program function. """ # setting logger logger.setLevel(logging.INFO) # Initialize Pygame and set up the window pygame.init() size = [SCREEN_WIDTH, SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption("SeatSmart") # Create our objec...
11,092
def record_iterator_class(record_type): """ Gets the record iterator for a given type A way to abstract the construction of a record iterator class. :param record_type: the type of file as string :return: the appropriate record iterator class """ if record_type == 'bib': return Bib...
11,093
def start_service(service: Type[LabDataService], port: int) -> None: """ Start a service in a ThreadedServer. """ threaded_server = rpyc.ThreadedServer( service=service, port=port, protocol_config={"allow_public_attrs": True, "allow_pickle": True}, ) threaded_server.start...
11,094
def sort_servers_closest(servers: Sequence[str]) -> Dict[str, float]: """Sorts a list of servers by http round-trip time Params: servers: sequence of http server urls Returns: sequence of pairs of url,rtt in seconds, sorted by rtt, excluding failed servers (possibly empty) """ ...
11,095
def TestMotion(): """ """ #clear registries storing.Store.Clear() #deeding.Deed.Clear() doing.Doer.Clear() store = storing.Store(name = 'Test') #CreateActions(store) print("\nTesting Motion Sim Controller") simulator = SimulatorMotionUuv(name = 'simulatorMotionTest', store = ...
11,096
def palgo( dumbalgo: type[DumbAlgo], space: Space, fixed_suggestion_value: Any ) -> SpaceTransformAlgoWrapper[DumbAlgo]: """Set up a SpaceTransformAlgoWrapper with dumb configuration.""" return create_algo(algo_type=dumbalgo, space=space, value=fixed_suggestion_value)
11,097
def english_to_french(english_text): """ Input language translate function """ translation = language_translator.translate(text=english_text, model_id = "en-fr").get_result() french_text = translation['translations'][0]['translation'] return french_text
11,098
def noise_get_turbulence( n: tcod.noise.Noise, f: Sequence[float], oc: float, typ: int = NOISE_DEFAULT, ) -> float: """Return the turbulence noise sampled from the ``f`` coordinate. Args: n (Noise): A Noise instance. f (Sequence[float]): The point to sample the noise from. ...
11,099