content
stringlengths
22
815k
id
int64
0
4.91M
def show_scores(need_input): """Demonstrates the table of 5 records. Args: need_input: boolean statement indicating whether to enter a new name. Returns: None. """ pygame.mixer.music.load(MENU_MUSIC) pygame.mixer.music.set_volume(0.3) pygame.mixer.m...
45,200
def snp2dict(snpfile): """Get settings of dict from .snp file exported from save&restore app. Parameters ---------- snpfile : str Filename of snp file exported from save&restore app. Returns ------- r : dict Dict of pairs of PV name and setpoint value. """ with open...
45,201
def _handle_zeros_in_scale(scale, copy=True, constant_mask=None): """ Set scales of near constant features to 1. The goal is to avoid division by very small or zero values. Near constant features are detected automatically by identifying scales close to machine precision unless they are precomp...
45,202
def test_yaml_config_file(): """Test loading a YAML config file First, pass a correctly formatted YAML file that only includes a single YAML document. Secondly, pass a correctly formatted YAML file that includes two YAML docuements. Expectation: The second test should fail to load with a warning, load...
45,203
def pub_list(settings=None): """ List all running virtual machines. """ vms = CLOUD_BACKEND.list_vms() # Display results sys.stdout.write('%s | %s | %s\n' % ('ip_addr', 'mac_addr', 'vm_name')) for name, ipaddr, mac in vms: sys.stdout.write('%s | %s | %s\n' % (ipaddr, mac, name))
45,204
def runuart(): """UART线程的任务函数 如果线程标识位为True,则不断调用读取函数,对pcb_version赋值 """ global pcb_data global objUART global uart_thread_destroy_flag while uart_thread_destroy_flag: recevied_data = objUART.waitForPcbData() if recevied_data[0] is True: # 获取控制板(pcb)版本,...
45,205
def ST_LineStringFromText(geos): """ Transform the representation of linestring from WKT to WKB. :type geos: WKT :param geos: Linestring in WKT form. :rtype: WKB :return: Linestring in WKB form. :example: >>> from pyspark.sql import SparkSession >>> from arctern_pyspark import...
45,206
def get_container_state(pod, name): """Get the state of container ``name`` from a pod. Returns one of ``waiting, running, terminated, unknown``. """ phase = pod["status"].get("phase", "Unknown") if phase == "Pending": return "waiting" cs = get_container_status(pod, name) if cs is no...
45,207
def implicit_ecp( objective, equality_constraints, initial_values, lr_func, max_iter=500, convergence_test=default_convergence_test, batched_iter_size=1, optimizer=optimizers.sgd, tol=1e-6): """Use implicit differentiation to solve a nonlinear equality-constrained program of the form: m...
45,208
def test_improve_coverage_setLicense(accelize_drm, conf_json, cred_json, async_handler, live_server, request): """ Improve coverage of the setLicense function """ driver = accelize_drm.pytest_fpga_driver[0] async_cb = async_handler.create() async_cb.reset() conf_json[...
45,209
def concatenate(input_files, output_file): """ Concatenates the input files into the single output file. In debug mode this function adds a comment with the filename before the contents of each file. """ from .modules import utils, concat if not isinstance(input_files, (list, tuple)): ...
45,210
def get_detection_probability_Braun2008(filename, index, TS_threshold): """ Find the detection probability as a function of the expected number of source counts in a detector. Returns Nsrc_list and Pdet :param filename: Filename :param index: spectral index :param TS_threshold: TS <=>...
45,211
def device_create(db: Session, name: str, device_type: DeviceType, activation_token: str) -> Device: """ Create a new Device """ device = Device( name=name, device_type=device_type, activation_token=activation_token, c...
45,212
async def test_limited_progress_event_updates(mock_device): """Test progress updates only once if no other events.""" # assert not playing heos = Heos("127.0.0.1", all_progress_events=False) await heos.connect() await heos.get_players() player = heos.players.get(1) # Attach dispatch handler...
45,213
def create_flash_objs(lma, good_data): """ lma is an LMAdataFile object. Its data instance gets overwritten with the sorted, qc'd, flash_id'd data. very similar to collect_output in autorun_mflash """ logger = logging.getLogger('FlashAutorunLogger') try: while Tru...
45,214
def xy_potential(_): """ Potential for square XY model with periodic boundary conditions """ def potential(_, passive_rates): pot = -passive_rates.sum(dim=(-1, -2, -3)) # sum over all sites and directions return pot return potential
45,215
def distribute_srcs_2D(X, Y, n_src, ext_x, ext_y, R_init): """Distribute n_src's in the given area evenly Parameters ---------- X, Y : np.arrays points at which CSD will be estimated n_src : int demanded number of sources to be included in the model ext_x, ext_y : floats ...
45,216
def _setBlueprintNumberOfAxialMeshes(meshPoints, factor): """ Set the blueprint number of axial mesh based on the axial mesh refinement factor. """ if factor <= 0: raise ValueError( "A positive axial mesh refinement factor " f"must be provided. A value of {factor} is inva...
45,217
def run_benchmark( execution_mode: str, params: config_definitions.ExperimentConfig, model_dir: str, distribution_strategy: tf.distribute.Strategy = None ) -> Mapping[str, Any]: """Runs benchmark for a specific experiment. Args: execution_mode: A 'str', specifying the mode. Can be 'accuracy', ...
45,218
def make_fun(f, *args, **kwargs): """ This function calls the function f while taking into account some of the limitations of the pandas UDF support: - support for keyword arguments - support for scalar values (as long as they are picklable) - support for type hints and input checks. :param ...
45,219
def stack_clips(ds_dir, dataset_txtfile, dataset_txtfile_output_path, NumStackingFrames = 16, overlapFrames=0, step=1): """ Saves a zero based file with all the starts of each stack """ if not os.path.isdir(utl.get_full_path_for_dir_containing_file(dataset_txtfile_output_path)): ...
45,220
def plot_confusion_matrix(targets, predictions, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=Tr...
45,221
def _get_filter_syntax(_filter_info, _prefix=True): """This function retrieves the proper filter syntax for an API call.""" if type(_filter_info) != tuple and type(_filter_info) != list: raise TypeError("Filter information must be provided as a tuple (element, criteria) or a list of tuples.") elif t...
45,222
def test_validate_user_returns_user_matching_email(dummy_request, db_session, one_user): """Test that validate_user raises HTTPForbidden for bad email.""" db_session.add(one_user) data = { 'email': one_user.email, 'password': 'password' } auth_user = validate_user(dummy_request.dbse...
45,223
def glRectsv( v1, v2): """ v1, v2 - seq( GLshort, 2) """ if 2 != len( v1): raise TypeError( len( v1), "2-array expected for v1") if 2 != len( v2): raise TypeError( len( v2), "2-array expected for v2") _gllib.glRectsv( v1, v2)
45,224
def pad_and_crop(ndarray, target_shape=(10, 10, 10)): """ Center pad and crop a np.ndarray with any shape to a given target shape Parameters In this implementation the pad and crop is invertible, ceil and round respects uneven shapes pad = floor(x),floor(x)+1 crop = floor(x)+1, floor(x) ----...
45,225
def pol2cart(r,theta): """ Translate from polar to cartesian coordinates. """ return (r*math.cos(float(theta)/180*math.pi), r*math.sin(float(theta)/180*math.pi))
45,226
def mass2mk_ben(m): """mass2mk_ben - mass to M_K, Benedict et al. (2016) double exponential. Usage: mk = mass2mk_ben(mass) Where mk is absolute 2MASS K magnitude and mass is in solar masses. This version is the original double-exponential "forward model" (for going from mass to absolute magnitude) from the pape...
45,227
def apply_and_concat_one_nb(n, apply_func_nb, *args): # numba doesn't accepts **kwargs """A Numba-compiled version of `apply_and_concat_one`. !!! note * `apply_func_nb` must be Numba-compiled * `*args` must be Numba-compatible * No support for `**kwargs` """ output_0 = to_2...
45,228
def chdir(path: Path) -> Iterator: """Context manager to help execute code in a different directory. Args: path: directory to change to. Yields: None """ old_pwd = os.getcwd() os.chdir(str(path)) try: yield finally: os.chdir(old_pwd)
45,229
def main(queue_name, host): """Creates the connection to RabbitMQ as a consumer and binds to the queue waiting for messages """ counter = 0 while True: counter += 1 try: params = pika.ConnectionParameters(host=host, port=5672) connection = pika.BlockingConnect...
45,230
def test_push_method(): """Test if push method adds new item to linked list.""" from linked_list import LinkedList test_list = LinkedList() test_list.push(1) assert test_list.head.data == 1
45,231
def run_scheduler(): """ A loop that handles running the daily list on time. """ while True: schedule.run_pending() time.sleep(1)
45,232
def recreate_db(): """Cleans everything (!) and sets up database""" drop_keyspace('documents') drop_table(Documents) create_keyspace_simple('documents', replication_factor=1) sync_table(Documents)
45,233
def convertCovariance2Dto3D(covariance2d): """ convert the covariance from [x, y, theta] to [x, y, z, roll, pitch, yaw] :param covariance2d: covariance matrix in 3x3 format. each row and column corresponds to [x, y, theta] :return: covariance matrix in 6x6 format. each row and colu...
45,234
def fit_gan_wasserstein(nb_epoch: int, x_LS: np.array, y_LS: np.array, x_VS: np.array, y_VS: np.array, x_TEST: np.array, y_TEST: np.array, gen, dis, opt_gen, opt_dis, n_discriminator:int, batch_size:int=100, wdb:bool=False, gpu:bool=True): """ Fit GAN with discriminator using the Wasserstein distance estimate. ...
45,235
def manifest_file_registration(workspace_id): """マニフェストテンプレートファイル登録 Args: workspace_id (int): ワークスペースID Returns: response: HTTP Respose """ globals.logger.debug("CALL manifest_file_registration:{}".format(workspace_id)) try: # 登録内容は基本的に、引数のJsonの値を使用する(追加項目があればここで記載) ...
45,236
def pad(image_array, final_dims_in_pixels, zero_fill_mode=False): """ Pad image data to final_dim_in_pixels Attributes: image_array (float, np.array): 3D numpy array containing image data final_dim_in_pixels (list): Final number of pixels in xyz dimensions. Example: [256, 256, 80] ...
45,237
def save_and_plot(canddatalist): """ Converts a canddata list into a plots and a candcollection. Calculates candidate features from CandData instance(s). Returns structured numpy array of candidate features labels defined in st.search_dimensions. Generates png plot for peak cands, if so defined in p...
45,238
def GetReviewers(host, change): """Gets information about all reviewers attached to a change.""" path = 'changes/%s/reviewers' % change return _SendGerritJsonRequest(host, path)
45,239
def plot_single_points(xs, ys, color=dark_color, s=50, zorder=1e6, edgecolor='black', **kwargs): """Plot single points and return patch artist.""" if xs is None: xs = tuple(range(len(ys))) return plt.scatter(xs, ys, marker='o', s=s, color=color, zorder=zorder, edgecolor=edgecolor, **kwargs)
45,240
def find_imports(source: str, filename=constants.DEFAULT_FILENAME, mode='exec'): """return a list of all module names required by the given source code.""" # passing an AST is not supported because it doesn't make sense to. # either the AST is one that we made, in which case the imports have already been made and ca...
45,241
async def test_flow_non_encrypted_already_configured_abort(hass): """Test flow without encryption and existing config entry abortion.""" MockConfigEntry( domain=DOMAIN, unique_id="1.2.3.4", data={CONF_HOST: "1.2.3.4", CONF_NAME: DEFAULT_NAME, CONF_PORT: DEFAULT_PORT}, ).add_to_hass(...
45,242
def link_by_distance_and_corr( regions_file, target_regions_file, out_file, regions_signal_file, target_regions_signal_file, k_nearest=3, max_dist=100000, corr_coeff_thresh=0, abs_corr_coeff_thresh=None, annotate_gene_ids=True, add_...
45,243
def generate_character_data(sentences_train, sentences_dev, sentences_test, max_sent_length, char_embedd_dim=30): """ generate data for charaters :param sentences_train: :param sentences_dev: :param sentences_test: :param max_sent_length: :return: C_train, C_dev, C_test, char_embedd_table ...
45,244
def draw_pie_distribution_of_elements(Genome_EP, ChIP_EP, gprom=(1000, 2000, 3000), gdown=(1000, 2000, 3000), prom=(1000,2000,3000), down=(1000,2000,3000)): """Draw the pie charts of the overall distributions of ChIP regions and genome background """ # get the labels (legend) for the genome pie chart gn...
45,245
def get_neighborhood(leaflet, mdsys): """ Get neighborhood object for the give leaflet """ dist = distances.distance_array(leaflet.positions, leaflet.positions, mdsys.dimensions[:3]) nbrs = Neighborhood(leaflet.positions, dist, mdsys.dimensions[:3]) return nbrs
45,246
def clean_title(title: str) -> str: """Strip unwanted additional text from title.""" for splitter in [" (", " [", " - ", " (", " [", "-"]: if splitter in title: title_parts = title.split(splitter) for title_part in title_parts: # look for the end splitter ...
45,247
def test_gibbon_chooses_same_as_min_value_entropy_search() -> None: """ When based on a single max-value sample, GIBBON should choose the same point as MES (see :cite:`Moss:2021`). """ model = QuadraticMeanAndRBFKernel(noise_variance=tf.constant(1e-10, dtype=tf.float64)) x_range = tf.linspace(-...
45,248
def upgrade_cost_analysis( inputs, cost_database, params_file, show_params, sequential_upgrade, nearest_redirect, config_file, verbose=False ): """Create JADE configuration for upgrade cost analysis.""" level = logging.DEBUG if verbose else log...
45,249
def _Overwrite(fp): """Overwrite first byte in an open file and flush contents.""" fp.seek(0) fp.write('x') fp.flush()
45,250
def get_dates(): """ Query date in the tweets table :return: """ sql = "SELECT date FROM tweets" dates = cx.read_sql(db, sql) return dates
45,251
def plot_ltraj(ltraj, id=1): """Plot `ltraj` using R method.""" adehabitat = import_adehabitat() adehabitat.plot_ltraj(ltraj, id=1)
45,252
def alter_label_if_ipython(transform, pvalueish): """Alters the label to an interactive label with ipython prompt metadata prefixed for the given transform if the given pvalueish belongs to a user-defined pipeline and current code execution is within an ipython kernel. Otherwise, noop. A label is either a us...
45,253
def test_scale_app_in_group(): """Scales an individual app in a group.""" group_def = groups.sleep_group() groups_id = group_def["groups"][0]["id"] app1_id = group_def["groups"][0]["apps"][0]["id"] app2_id = group_def["groups"][0]["apps"][1]["id"] client = marathon.create_client() client.c...
45,254
def _convert_to_dict(best_param): """ Utiliy method for converting best_param string to dict Args: :best_param: the best_param string Returns: a dict with param->value """ best_param_dict = {} for hp in best_param: hp = hp.split('=') best_param_dict[hp[0]] ...
45,255
def read_in(file_index, normalized, train, ratio): """ Reads in a file and can toggle between normalized and original files :param file_index: patient number as string :param normalized: binary that determines whether the files should be normalized or not :param train: int that determines whether or...
45,256
def _expand_currency(data: dict) -> str: """ Verbalizes currency tokens. Args: data: detected data Returns string """ currency = _currency_dict[data['currency']] quantity = data['integral'] + ('.' + data['fractional'] if data.get('fractional') else '') magnitude = data.get('magni...
45,257
def getCampaignID(title): """ Returns the id of a campaign from a dm name and a title """ conn = connectToDB() cur = conn.cursor() print title query = cur.mogrify('select id from campaigns where title = %s;', (title,)) print query cur.execute(query) results = cur.fetchone() return re...
45,258
def calculate_exe_time(input_function): """ This decorator method take in a function as argument and calulates its execution time. :param input_function: name of method to be executed. :return process_time: method that calls the input_function and calculates execution time. """ def process_time...
45,259
def do_hashmap_threshold_get(cc, args={}): """Get a threshold.""" try: threshold = cc.hashmap.thresholds.get(threshold_id=args.threshold_id) except exc.HTTPNotFound: raise exc.CommandError('Threshold not found: %s' % args.threshold_id) utils.print_dict(threshold.to_dict())
45,260
def load_xyz_from_txt(file_name): """Load xyz poses from txt. Each line is: x,y,x Args: file_name (str): txt file path Returns: torch.Tensor: Trajectory in the form of homogenous transformation matrix. Shape [N,4,4] """ global device poses = np.genfromtxt(file_name, del...
45,261
def category_add(): """ Route for category add """ # request Form data form = CategoryForm(request.form) if request.method == "POST" and form.validate(): # Set new category name variable category_name = form.name.data.lower() if category_check(category_name): ...
45,262
def generation(control_area, date, output_dir): """ Writes a generation report for a single day to a CSV file in the given directory. """ start = _parse_date(date) end = start + timedelta(days=1) result = generation_task(app.config["BA_NAME"], control_area, start, end) filename = f"{output_d...
45,263
def simplex_method_tests(): """ 单纯形表法测试 """ # 普通标准问题 pb = LpProblem([-5, 5, 13, 0, 0], [[-1, 1, 3, 1, 0], [12, 4, 10, 0, 1]], [20, 90]) s = pb.solve(SimplexMethod, show_tab=True) print(s) # 唯一解 pb = LpProblem([2, 3, 0, 0, 0], [[1, 2, 1, 0, 0], [4, 0, 0, 1, 0], [0, 4, 0, 0, 1]], [8, ...
45,264
def plot(series, title, xlabel, ylabel, leg_location="lower right"): """ Plots data :param series: data series :param title: plot title :param xlabel: x labels :param ylabel: y labels :param ylabel: y labels :param leg_location: label location """ plt.figure(figsize=(15, 10)) ...
45,265
def generate_text(input: TextGenerationInput) -> TextGenerationOutput: """Generate text based on a given prompt.""" payload = { "text": input.text, "temperature": input.temperature, "min_length": input.min_length, "max_length": input.max_length, "do_sample": input.do_sam...
45,266
def test_recovery_detail_links(client, angler, report, species): """Verify that we have links to the report's page, the report details page, and the form to edit the recovery information.""" recovery = RecoveryFactory(report=report, species=species) response = client.get( reverse("tfat:recover...
45,267
def cb(*args): """If apply_async has troubles?""" print("cb() called and got the following as args:") print(args)
45,268
def check(**kw): """ Description: operating with system checks. """ with open(CHECK_SHELL[5:-1], "r") as f: lines = f.readlines() CHECKX_OPTS = [i[:-2] for i in lines if i.startswith("--")] try: if kw["arg"] is None: __logxsOut(f"{[i[2:] for i in CHECKX_OPTS]}") ...
45,269
def set_state_and_obs_state(device, state, obs_state): """ Set subarray device state and observing state. :param device: subarray device proxy :param state: the desired device state :param obs_state: the desired observing state """ if device.State().name != state or device.obsState.name !=...
45,270
def file_content_hash(file_name, encoding, database=None): """ Returns the hash of the contents of the file Use the database to keep a persistent cache of the last content hash. """ _, content_hash = _file_content_hash(file_name, encoding, database) return content_hash
45,271
def pass_multiallelic_sites(mqc): """ The number of PASS multiallelic sites. Source: count_variants.py (bcftools view) """ k = inspect.currentframe().f_code.co_name try: d = next(iter(mqc["multiqc_npm_count_variants"].values())) v = d["pass_multiallelic_sites"] v = int(...
45,272
def read_dialog_file(json_filename: str) -> list[Message]: """ Read messages from the dialog file @return: list of Message objects (without intent) """ with open(json_filename, encoding="utf8") as dialog_json: return [ Message(is_bot=msg["is_bot"], text=msg["text"]) f...
45,273
def check(caller_id, node_id_list): """ Tries to restart cc1-node service on each specified Node @cmview_admin_cm @param_post{node_id_list,list(int)} @note Not used (but might be used one day) """ try: for node_id in node_id_list: node_tools.check(node_id) except Ex...
45,274
def dtwavexfm3(X, nlevels=3, biort=DEFAULT_BIORT, qshift=DEFAULT_QSHIFT, include_scale=False, ext_mode=4, discard_level_1=False): """Perform a *n*-level DTCWT-3D decompostion on a 3D matrix *X*. :param X: 3D real array-like object :param nlevels: Number of levels of wavelet decomposition ...
45,275
def character_regions(img, line_regs, bg_thresh=None, **kwargs): """ Find the characters in an image given the regions of lines if text in the image. Args: img (numpy.ndarray): Grayscaled image. line_regs (list[tuple[int, int]]): List of regions representing where the lines ...
45,276
def mask_to_disk(mask, fname, n_classes, cmap_name="rainbow"): """ write segmentation mask to disk using a particular colormap mask (float): this contains the predicted labels in the range [0, n_classes]. fname (str): of the the image to be saved n_classes (int): total number of classes in the data...
45,277
def test_100_request_stream() -> None: """Test `request_stream()`. Based on https://github.com/gabrielfalcao/HTTPretty/blob/master/tests/functional/test_requests.py#L290 """ mock_url = "http://test" expected_stream = [ b'{"foo-bar":"baz"}\n', b"\r\n", b"\n", b'{"gree...
45,278
def cache_clear(request): """ Очищает директорию кеша. """ Core.get_instance().clear_cache() return { 'size': Core.get_instance().get_cache_size() }
45,279
def add_to_targetipaddr_db(instance): """Adds IP addresses as individual entries in TargetIpAddr database.""" if instance.target_type == Target.IPADDR: if '-' in instance.target: iprange = instance.target.split('-') iplist = list(netaddr.iter_iprange(iprange[0], iprange[1])) ...
45,280
def sort_crp_tables(tables): """Sort cluster assignments by number""" keys = sorted(tables, key=lambda t: (len(tables[t]), min(tables[t])), reverse=True) items = [item for table in keys for item in tables[table]] dividers = [len(tables[table]) for table in keys] return (items, np.cum...
45,281
def killRunningEvents(hostname, password): """Terminates all running vmkperf events from the provided server.""" # Pauses execution of the following commands to ensure the the internal # python script used to obtain the PMU data termiantes properly. time.sleep(1) # Command to ssh into the server a...
45,282
def sum_category_hours(day, now, timelog=TIMELOG, category_hours=False): """ Sum the hours by category. """ if not category_hours: category_hours = {} activities = get_rows(day, timelog) for activity in activities: category = activity.category duration = activity.get_duration(now...
45,283
def demo_gpu_color(fpath): """ Example: GPU color kernel """ img = cimg.fromFile(fpath) # GPU shader written in the Core Image Kernel Language # This is a Color Kernel, since only the color fragment is processed src = """ kernel vec4 crush_red(__sample img, float a, float b) { // Crus...
45,284
def test_spline_transformer_manual_knot_input(): """ Test that array-like knot positions in SplineTransformer are accepted. """ X = np.arange(20).reshape(10, 2) knots = [[0.5, 1], [1.5, 2], [5, 10]] st1 = SplineTransformer(degree=3, knots=knots, n_knots=None).fit(X) knots = np.asarray(knots)...
45,285
def get_signin_reward(cookies, taskid, total_days): """ 领取每日登陆奖励 """ headers = { 'Host': 'farm.dmall.com', 'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'User-Agent': UserAgent, 'Accept': '*/*', 'Referer': 'https://...
45,286
def run_factory( factory, # type: LazyFactory args=None, # type: Optional[Iterable[Any]] kwargs=None, # type: Optional[Mapping[str, Any]] ): # type: (...) -> Any """ Import and run factory. .. code:: python >>> from objetto.utils.factoring import run_factory >>> bool(ru...
45,287
def steps_smoother(steps, resolution): """ :param delta_steps: array of delta positions of 2 joints for each of the 4 feet :return: array of positions of 2 joints for each of the 4 feet """ smoothed_steps = [] for i in range(len(steps)): step = steps[i] next_step = steps[(i + 1) ...
45,288
def get_instance_server(name: Optional[str] = None, server_id: Optional[str] = None, zone: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetInstanceServerResult: """ Gets information about an instance server...
45,289
def leaper(x, y, int1, int2): """sepcifically for the rook, permutes the values needed around a position for no_conflict tests""" return [(x+int1, y+int2), (x-int1, y+int2), (x+int1, y-int2), (x-int1, y-int2), (x+int2, y+int1), (x-int2, y+int1), (x+int2, y-int1), (x-int2, y-int1)]
45,290
def vnfd_list2(ctx, nf_type, filter, long): """list all xNF packages (VNF, HNF, PNF)""" logger.debug("") vnfd_list(ctx, nf_type, filter, long)
45,291
def calc_offsets(obj): """ The search "hit" should have a 'fullsnip' annotation which is a the entire text of the indexable resource, with <start_sel> and <end_sel> wrapping each highlighted word. Check if there's a selector on the indexable, and then if there's a box-selector use this to gener...
45,292
def run(fresh=False): """Read books from Goodreads shelf, then check availability in library. fresh -- (optional) if False, use locally cached files """ if fresh: clearCache() downloadGRShelf() print('Creating Library Summary: {}'.format(jsonlFn)) with jsonlines.open(jsonlFn, 'w'...
45,293
def print_turn_eval(config): """Print basic info prior to evaluating which move to make.""" print('TURN # %d EVALUATION (%s):' % \ ((config.num_moves + 1), config.players[config.turn]['color'])) print('------------------------') print('Total Moves Available: %d' % len(config.legal_moves)) pr...
45,294
def del_job(job): """ Function to delete a job. Used to spawn a thread and wait for jobs to cleanup hashcat proc """ time.sleep(22) logger.debug('Thread: deleting job') job.delete() del_jobid(job.id)
45,295
def test_convert_i_case_spacy(conv): """Test that "I" case conversion also works if spaCy is invoked.""" assert conv.convert_para("I estimate that I am capitalized at the start of sentences but that I'm lower-case in the middle. I am still capitalized at the start.") ==\ 'Y éstimait that y am capite...
45,296
def save_model(): """Save currently saved model as tf_saved_model form.""" # loading actively trained agent a = train.restore_existing_agent() model = verify.ModelWrapper(a.q_net, a.use_categorical) # making a single call so tf knows the input shape env = a.build_temp_env() x = env.reset().observation ...
45,297
def parse_args(): """ Parse command-line arguments Returns ------- Parser argument namespace """ parser = argparse.ArgumentParser(description="Fibermorph") parser.add_argument( "--output_directory", default=None, help="Required. Full path to and name of desired outpu...
45,298
def spread(self, value="", **kwargs): """Turns on a dashed tolerance curve for the subsequent curve plots. APDL Command: SPREAD Parameters ---------- value Amount of tolerance. For example, 0.1 is ± 10%. """ return self.run("SPREAD,%s" % (str(value)), **kwargs)
45,299