content
stringlengths
22
815k
id
int64
0
4.91M
def check_position(position): """Determines if the transform is valid. That is, not off-keypad.""" if position == (0, -3) or position == (4, -3): return False if (-1 < position[0] < 5) and (-4 < position[1] < 1): return True else: return False
31,200
def p_tables(p): """tables : schemaslash TABLE""" p[0] = p[1].tables()
31,201
def mobilenet_wd4_cub(num_classes=200, **kwargs): """ 0.25 MobileNet-224 model for CUB-200-2011 from 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,' https://arxiv.org/abs/1704.04861. Parameters: ---------- num_classes : int, default 200 Number of cl...
31,202
def base_plus_copy_indices(words, dynamic_vocabs, base_vocab, volatile=False): """Compute base + copy indices. Args: words (list[list[unicode]]) dynamic_vocabs (list[HardCopyDynamicVocab]) base_vocab (HardCopyVocab) volatile (bool) Returns: MultiVocabIndices ...
31,203
def font_encoding(psname): """Return encoding name given a psname""" return LIBRARY.encoding(psname)
31,204
def shader_with_tex_offset(offset): """Returns a vertex FileShader using a texture access with the given offset.""" return FileShader(shader_source_with_tex_offset(offset), ".vert")
31,205
def braycurtis(u, v): """ d = braycurtis(u, v) Computes the Bray-Curtis distance between two n-vectors u and v, \sum{|u_i-v_i|} / \sum{|u_i+v_i|}. """ u = np.asarray(u) v = np.asarray(v) return abs(u-v).sum() / abs(u+v).sum()
31,206
def test_outcomes_unwrap_returns_trio_value_over_qt_value(): """Unwrapping an Outcomes prioritizes a Trio value over a Qt value.""" this_outcome = qtrio.Outcomes(qt=outcome.Value(2), trio=outcome.Value(3)) result = this_outcome.unwrap() assert result == 3
31,207
def _load_pyfunc(path): """ Load PyFunc implementation. Called by ``pyfunc.load_pyfunc``. :param path: Local filesystem path to the MLflow Model with the ``fastai`` flavor. """ return _FastaiModelWrapper(_load_model(path))
31,208
def fit_pseudo_voigt(x,y,p0=None,fit_alpha=True,alpha_guess=0.5): """Fits the data with a pseudo-voigt peak. Parameters ----------- x: np.ndarray Array with x values y: np.ndarray Array with y values p0: list (Optional) It contains a initial guess the for the pseudo-vo...
31,209
def mkdir(path: str): """ :param path: :return: """ os.makedirs(path, exist_ok=True)
31,210
def get_ready_directories(directory): """Returns a directory with list of files That directories should have a 'buildinfo' and 'inventory.yaml' file which are not empty. """ log_files = {} for root, _, files in os.walk(directory): build_uuid = root.split('/')[-1] if check_info_...
31,211
def asbytes(s: Literal["a"]): """ usage.scipy: 2 """ ...
31,212
def lint(paths, include, exclude, only_staged, ignore_untracked): """ Run code checks (pylint + mypy) """ from peltak.core import log from custom_commands_logic import check log.info('<0><1>{}', '-' * 60) log.info('paths: {}', paths) log.info('include: {}', include) log....
31,213
def get_name_of_day(str_date): """ Возвращает имя дня. """ day = datetime.fromisoformat(str_date).weekday() return DAYS_NAME.get(day)
31,214
def reset_variable_in_store(store_name, path): """ Resets the variable name in the hdfstore :param store_name: :param path: :return: """ try: with pd.get_store(store_name) as store: store.remove(path) except Exception as e: pass
31,215
def download(client, activity, retryer, backup_dir, export_formats=None): """Exports a Garmin Connect activity to a given set of formats and saves the resulting file(s) to a given backup directory. In case a given format cannot be exported for the activity, the file name will be appended to the :attr:`n...
31,216
def plot_passive_daily_comparisons(df_list: list, stock:str): """**First dataframe must be the Portfolio with switching.** """ temp_df1 = df_list[0].iloc[0:0] # temp_df1.drop(temp_df1.columns[0],axis=1,inplace=True) temp_df2 = df_list[1].iloc[0:0] # temp_df2.drop(temp_df2.columns[0],axis=1,inplace=True) temp_da...
31,217
def show(root=None, debug=False, parent=None): """Display Loader GUI Arguments: debug (bool, optional): Run loader in debug-mode, defaults to False """ try: module.window.close() del module.window except (RuntimeError, AttributeError): pass if debu...
31,218
def test_fragment_two_aa_peptide_y_series(): """Test y2 fragmentation""" fragments = PeptideFragment0r('KK', charges=[1], ions=['y']).df # fragments = fragger.fragment_peptide(ion_series=['y']) assert isinstance(fragments, DataFrame) # assert len(fragments) == 2 row = fragments.iloc[3] asse...
31,219
def run(test, params, env): """ 'thin-provisioning' functions test using sg_utils: 1) Create image using qemu-img 2) Convert the image and check if the speed is much faster than standard time :param test: QEMU test object :param params: Dictionary with the test parameters ...
31,220
def k_fold_split(ratings, min_num_ratings=10, k=4): """ Creates the k (training set, test_set) used for k_fold cross validation :param ratings: initial sparse matrix of shape (num_items, num_users) :param min_num_ratings: all users and items must have at least min_num_ratings per user and per item to be...
31,221
def merge_dict(a, b, path:str=None): """ Args: a: b: path(str, optional): (Default value = None) Returns: Raises: """ "merges b into a" if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dic...
31,222
def validateSignedOfferData(adat, ser, sig, tdat, method="igo"): """ Returns deserialized version of serialization ser which Offer if offer request is correctly formed. Otherwise returns None adat is thing's holder/owner agent resource ser is json encoded unicode string of request sig i...
31,223
def get_relevant_phrases(obj=None): """ Get all phrases to be searched for. This includes all SensitivePhrases, and any RelatedSensitivePhrases that refer to the given object. :param obj: A model instance to check for sensitive phrases made specifically for that instance. :return: a dictionary of repl...
31,224
def test_last_ordered_3pc_not_reset_if_less_than_new_view(txnPoolNodeSet, looper, sdk_pool_handle, sdk_wallet_client): """ Check that if last_ordered_3pc's viewNo on a Replica is equal to the new viewNo after view change, then last_ordered_3pc is reset to (0,0). It can be that last_ordered_3pc was set f...
31,225
def write_reproducible_script(script_filename, databases_root_folder, table_name, analysis_id): """ Read information from database """ db_select = DBSelect(databases_root_folder + table_name) analysis = db_select.select_analysis(Analysis, analysis_id) neural_network_rows = db_select.select_all_from_anal...
31,226
def _prepare_cabal_inputs( hs, cc, posix, dep_info, cc_info, direct_cc_info, component, package_id, tool_inputs, tool_input_manifests, cabal, setup, setup_deps, setup_dep_info, srcs, compiler_...
31,227
def split_kp(kp_joined, detach=False): """ Split the given keypoints into two sets(one for driving video frames, and the other for source image) """ if detach: kp_video = {k: v[:, 1:].detach() for k, v in kp_joined.items()} kp_appearance = {k: v[:, :1].detach() for k, v in kp_joined.item...
31,228
def train(model, train_primary, train_ss, ss_padding_index): """ Runs through one epoch - all training examples. :param model: the initialized model to use for forward and backward pass :param train_primary: primary (amino acid seq) train data (all data for training) of shape (num_sentences, window_siz...
31,229
def low_shelve(signal, frequency, gain, order, shelve_type='I', sampling_rate=None): """ Create and apply first or second order low shelve filter. Uses the implementation of [#]_. Parameters ---------- signal : Signal, None The Signal to be filtered. Pass None to create ...
31,230
def setDiskOffload(nodename, servername, enabled): """Enables or disables dynacache offload to disk on the given server""" m = "setDiskOffload:" #sop(m,"Entry. nodename=%s servername=%s enabled=%s" % ( repr(nodename), repr(servername), repr(enabled) )) if enabled != 'true' and enabled != 'false': ...
31,231
def test_mesh2d_merge_two_nodes( meshkernel_with_mesh2d: MeshKernel, first_node: int, second_node: int, num_faces: int, ): """Tests `mesh2d_merge_two_nodes` by checking if two selected nodes are properly merged 6---7---8 | | | 3---4---5 | | | 0---1---2 """ mk = ...
31,232
def get_breast_zone(mask: np.ndarray, convex_contour: bool = False) -> Union[np.ndarray, tuple]: """ Función de obtener la zona del seno de una imagen a partir del area mayor contenido en una mascara. :param mask: mascara sobre la cual se realizará la búsqueda de contornos y de las zonas más largas. :...
31,233
def replace(temporaryans, enterword, answer): """ :param temporaryans: str, temporary answer. :param enterword: str, the character that user guesses. :param answer: str, the answer for this hangman game. :return: str, the temporary answer after hyphens replacement. """ # s = replace('-----',...
31,234
def extract_timestamp(line): """Extract timestamp and convert to a form that gives the expected result in a comparison """ # return unixtime value return line.split('\t')[6]
31,235
def test_parse__param_field_type_field_or_none__param_section_with_optional(): """Parse a simple docstring.""" def f(foo): """ Docstring with line continuation. :param foo: descriptive test text :type foo: str or None """ sections, errors = parse(f) assert len(...
31,236
def da_scala_dar_resources_library( daml_root_dir, daml_dir_names, lf_versions, add_maven_tag = False, maven_name_prefix = "", exclusions = {}, enable_scenarios = False, **kwargs): """ Define a Scala library with dar files as resources. """ ...
31,237
def svn_stream_from_stringbuf(*args): """svn_stream_from_stringbuf(svn_stringbuf_t str, apr_pool_t pool) -> svn_stream_t""" return _core.svn_stream_from_stringbuf(*args)
31,238
def get_autoencoder_model(hidden_units, target_predictor_fn, activation, add_noise=None, dropout=None): """Returns a function that creates a Autoencoder TensorFlow subgraph. Args: hidden_units: List of values of hidden units for layers. target_predictor_fn: Function that will pred...
31,239
def plot_histogram(ax,values,bins,colors='r',log=False,xminmax=None): """ plot 1 histogram """ #print (type(values)) ax.hist(values, histtype="bar", bins=bins,color=colors,log=log, alpha=0.8, density=False, range=xminmax) # Add a small annotation. # ax.annotate('Annotation', ...
31,240
def build_model(): """Build the model. Returns ------- tensorflow.keras.Model The model. """ input_x = tf.keras.Input( shape=(30,), name='input_x' ) # shape does not include the batch size. layer1 = tf.keras.layers.Dense(5, activation=tf.keras.activations.tanh) lay...
31,241
def test_compute_difficulty_0_difficult(result_r): """ GIVEN two valid dicts representing a quiz where difficults question are failed WHEN the method _compute_difficulty is called THEN Result.advices must be update with a corresponding new entry """ score = {1: 5, 2: 3, 3: 0} total = {1: 5, ...
31,242
def create_output_directory(output_dir_path: str) -> None: """ Create the output directory if it doesn't already exist. """ if not os.path.isdir(output_dir_path): print("Creating output directory...") os.mkdir(output_dir_path)
31,243
def evaluate_generator(generator, backbone_pool, lookup_table, CONFIG, device, val=True): """ Evaluate kendetall and hardware constraint loss of generator """ total_loss = 0 evaluate_metric = {"gen_macs":[], "true_macs":[]} for mac in range(CONFIG.low_macs, CONFIG.high_macs, 10): hardwa...
31,244
def load_data(config, var_mode): """Main data loading routine""" print("Loading {} data".format(var_mode)) # use only the first two characters for shorter abbrv var_mode = var_mode[:2] # Now load data. var_name_list = [ "xs", "ys", "Rs", "ts", "img1s", "cx1s", "cy1s", "f1s", ...
31,245
def getCameras(): """Return a list of cameras in the current maya scene.""" return cmds.listRelatives(cmds.ls(type='camera'), p=True)
31,246
def convert_quotes(text): """ Convert quotes in *text* into HTML curly quote entities. >>> print(convert_quotes('"Isn\\'t this fun?"')) &#8220;Isn&#8217;t this fun?&#8221; """ punct_class = r"""[!"#\$\%'()*+,-.\/:;<=>?\@\[\\\]\^_`{|}~]""" # Special case if the very first character is a qu...
31,247
def time_shift(signal, n_samples_shift, circular_shift=True, keepdims=False): """Shift a signal in the time domain by n samples. This function will perform a circular shift by default, inherently assuming that the signal is periodic. Use the option `circular_shift=False` to pad with nan values instead. ...
31,248
def compare_shapes( proto, input_key_values, expected_outputs, use_cpu_only=False, pred=None ): """ Inputs: - proto: MLModel proto. - input_key_values: str -> np.array or PIL.Image. Keys must match those in input_placeholders. - expected_outputs: dict[str, np.array]. ...
31,249
def get_avgerr(l1_cols_train,l2_cols_train,own_cols_xgb,own_cols_svm,own_cols_bay,own_cols_adab,own_cols_lass,df_train,df_test,experiment,fold_num=0): """ Use mae as an evaluation metric and extract the appropiate columns to calculate the metric Parameters ---------- l1_cols_train : list l...
31,250
def get_repository_metadata_by_changeset_revision( trans, id, changeset_revision ): """Get metadata for a specified repository change set from the database.""" # Make sure there are no duplicate records, and return the single unique record for the changeset_revision. Duplicate records were somehow # create...
31,251
def generate_encounter_time(t_impact=0.495*u.Gyr, graph=False): """Generate fiducial model at t_impact after the impact""" # impact parameters M = 5e6*u.Msun rs = 10*u.pc # impact parameters Tenc = 0.01*u.Gyr dt = 0.05*u.Myr # potential parameters potential = 3 Vh ...
31,252
def get_census_centroid(census_tract_id): """ Gets a pair of decimal coordinates representing the geographic center (centroid) of the requested census tract. :param census_tract_id: :return: """ global _cached_centroids if census_tract_id in _cached_centroids: return _cached_centroid...
31,253
def abvcalc_main(): """Entry point for abvcalc command line script. """ import argparse parser = argparse.ArgumentParser() parser.add_argument('og', type=float, help='Original Gravity') parser.add_argument('fg', type=float, help='Final Gravity') args = parser.parse_args() abv = 100. * ...
31,254
def reptile_select_list(news_list_url, mainElem, linkElem, TimeElem, titleElem, context_config, class_list=[]): """利用新闻列表来获取正文和标题""" args = [] args.append(mainElem) args.append(linkElem) args.append(TimeElem) args.append(titleElem) reptile_select_context(news_list_url, args, None, ...
31,255
def configure_context(args: Namespace, layout: Layout, stop_event: Event) -> Context: """Creates the application context, manages state""" context = Context(args.file) context.layout = layout sensors = Sensors(context, stop_event) context.sensors = sensors listener = KeyListener(context.on_key, ...
31,256
async def test_turn_off_image(opp): """After turn off, Demo camera raise error.""" await opp.services.async_call( CAMERA_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: ENTITY_CAMERA}, blocking=True ) with pytest.raises(OpenPeerPowerError) as error: await async_get_image(opp, ENTITY_CAMERA) ...
31,257
def offsetEndpoint(points, distance, beginning=True): """ Pull back end point of way in order to create VISSIM intersection. Input: list of nodes, distance, beginning or end of link Output: transformed list of nodes """ if beginning: a = np.array(points[1], dtype='float') b =...
31,258
def write_config(infile, data, ftype='yaml'): """ Input - full path to config file Dictionary of parameters to write Output - None """ infile = str(infile) if ftype in ['json','pyini']: try: data = json.dump(data, open(infile,'w'), sort_keys=True, indent=4) ...
31,259
def _remove_parenthesis(word): """ Examples -------- >>> _remove_parenthesis('(ROMS)') 'ROMS' """ try: return word[word.index("(") + 1 : word.rindex(")")] except ValueError: return word
31,260
def check_closed(f): """Decorator that checks if connection/cursor is closed.""" def g(self, *args, **kwargs): if self.closed: raise exceptions.Error(f"{self.__class__.__name__} already closed") return f(self, *args, **kwargs) return g
31,261
def get_box_filter(b: float, b_list: np.ndarray, width: float) -> np.ndarray: """ Returns the values of a box function filter centered on b, with specified width. """ return np.heaviside(width/2-np.abs(b_list-b), 1)
31,262
def search(ra=None, dec=None, radius=None, columns=None, offset=None, limit=None, orderby=None): """Creates a query for the carpyncho database, you can specify""" query = CarpynchoQuery(ra, dec, radius, columns, offset, limit, orderby) return query
31,263
def repetitions(seq: str) -> int: """ [Easy] https://cses.fi/problemset/task/1069/ [Solution] https://cses.fi/paste/659d805082c50ec1219667/ You are given a DNA sequence: a string consisting of characters A, C, G, and T. Your task is to find the longest repetition in the sequence. This is a ma...
31,264
def get_gmusicmanager( useMobileclient = False, verify = True, device_id = None ): """ Returns a GmusicAPI_ manager used to perform operations on one's `Google Play Music`_ account. If the Musicmanager is instantiated but cannot find the device (hence properly authorize for operation), then the attribute ``erro...
31,265
def measure(data, basis, gaussian=0, poisson=0): """Function computes the dot product <x,phi> for a given measurement basis phi Args: - data (n-size, numpy 1D array): the initial, uncompressed data - basis (nxm numpy 2D array): the measurement basis Returns: - A m-sized numpy 1D ar...
31,266
def to_huang_ner(out_file, cd, n_workers = 47, max_line = 1000): """ """ fn = 'huang_ner/' abs_cnt = 0 f = open(fn + '' + str(abs_cnt).zfill(5) + '.txt', 'w') f.write('Line\t') for x in range(n_workers): f.write(str(x) + '\t') f.write('\n') res = [] wids = [] ...
31,267
def inline(session, module): """ Run specific per-module inline tests """ session.install("-r", "requirements/install.txt") if str(module).endswith('mathematics'): session.install("-r", "requirements/nox/tests.txt") session.run('python', '-m', module)
31,268
def getUserByMail(email): """Get User by mailt.""" try: user = db_session.query(User).filter_by(email=email).one() return user except Exception: return None
31,269
def add_axes( # Ranges xrange=[0,1], yrange=[0,1], zrange=[0,1], # Titles xtitle = 'x', ytitle = 'y', ztitle = 'z', htitle = '', # Grids xyGrid=True, yzGrid=True, zxGrid=True, xyGrid2=False, yzGrid2=False, zxGrid2=False, xyGridTransparent=True, yzGridTransparent=True, ...
31,270
def parse_headers(headers, data): """ Given a header structure and some data, parse the data as headers. """ return {k: f(v) for (k, (f, _), _), v in zip(headers, data)}
31,271
def release_gen_payload(runtime, is_name, is_namespace, organization, repository, event_id): """Generates two sets of input files for `oc` commands to mirror content and update image streams. Files are generated for each arch defined in ocp-build-data for a version, as well as a final file for manifest-lists. One ...
31,272
def dataset_parser(value, A): """Parse an ImageNet record from a serialized string Tensor.""" # return value[:A.shape[0]], value[A.shape[0]:] return value[:A.shape[0]], value
31,273
def default_csv_file(): """ default name for csv files """ return 'data.csv'
31,274
def get_gc_alt(alt, unit='km'): """ Return index of nearest altitude (km) of GEOS-Chem box (global value) """ if unit == 'km': alt_c = gchemgrid('c_km_geos5_r') elif unit == 'hPa': alt_c = gchemgrid('c_hPa_geos5') else: err_str = 'No case setup for altitude unit ({})'.for...
31,275
def download(object_client, project_id, datasets_path): """Download the contents of file from the object store. Parameters ---------- object_client : faculty.clients.object.ObjectClient project_id : uuid.UUID datasets_path : str The target path to download to in the object store Re...
31,276
def set_log_level(level): """ Set the logging level for urbansim. Parameters ---------- level : int A supporting logging level. Use logging constants like logging.DEBUG. """ logging.getLogger('urbansim').setLevel(level)
31,277
def upload_to_db(buffer: BytesIO): """Записывает изменения, сделанные в xlsx в файле, в базу данных""" wb = load_workbook(filename=buffer) for ws in wb: for row in ws.iter_rows(min_row=2, max_row=ws.max_row): if row[9].value == 1: set_application_ok(row[0].value)
31,278
def get_assets_of_dataset( db: Session = Depends(deps.get_db), dataset_id: int = Path(..., example="12"), offset: int = 0, limit: int = settings.DEFAULT_LIMIT, keyword: str = Query(None), viz_client: VizClient = Depends(deps.get_viz_client), current_user: models.User = Depends(deps.get_curre...
31,279
def check_rule(body, obj, obj_string, rule, only_body): """ Compare the argument with a rule. """ if only_body: # Compare only the body of the rule to the argument retval = (body == rule[2:]) else: retval = ((body == rule[2:]) and (obj == obj_string)) return retval
31,280
def pdm_auto_arima(df, target_column, time_column, frequency_data, epochs_to_forecast = 12, d=1, D=0, seasonal=True, m =12, start_p = 2...
31,281
def get_lines(filename): """ Returns a list of lines of a file. Parameters filename : str, name of control file """ with open(filename, "r") as f: lines = f.readlines() return lines
31,282
def shout(*text): """Echoes text back, but louder. text: the text to echo back Who shouts backwards anyway?""" print(' '.join(text).upper())
31,283
def _check_socket_state(realsock, waitfor="rw", timeout=0.0): """ <Purpose> Checks if the given socket would block on a send() or recv(). In the case of a listening socket, read_will_block equates to accept_will_block. <Arguments> realsock: A real socket.socket() object to check for...
31,284
def str_to_pauli_term(pauli_str: str, qubit_labels=None): """ Convert a string into a pyquil.paulis.PauliTerm. >>> str_to_pauli_term('XY', []) :param str pauli_str: The input string, made of of 'I', 'X', 'Y' or 'Z' :param set qubit_labels: The integer labels for the qubits in the string, given in ...
31,285
def _GetNextPartialIdentifierToken(start_token): """Returns the first token having identifier as substring after a token. Searches each token after the start to see if it contains an identifier. If found, token is returned. If no identifier is found returns None. Search is abandoned when a FLAG_ENDING_TYPE tok...
31,286
def _challenge_transaction(client_account): """ Generate the challenge transaction for a client account. This is used in `GET <auth>`, as per SEP 10. Returns the XDR encoding of that transaction. """ builder = Builder.challenge_tx( server_secret=settings.STELLAR_ACCOUNT_SEED, cli...
31,287
def mapCtoD(sys_c, t=(0, 1), f0=0.): """Map a MIMO continuous-time to an equiv. SIMO discrete-time system. The criterion for equivalence is that the sampled pulse response of the CT system must be identical to the impulse response of the DT system. i.e. If ``yc`` is the output of the CT system with an ...
31,288
def main( loglevel="ERROR", keep_repos=False, cache_http=False, cache_ttl=7200, output_file=None, ): """Main""" logger.setLevel(loglevel) logger.info("Running circuitpython.org/libraries updater...") run_time = datetime.datetime.now() logger.info("Run Date: %s", run_time.strfti...
31,289
def main(args): """ Main entry. """ logging.info("Loading image lists ...") v_info = [] img_lst = dict() with open(args.ori_lst, 'r') as orif: v_info = [line.split() for line in orif] for impath, label in v_info: if label not in img_lst: img_lst[label] = [] ...
31,290
def normalize_type(type: str) -> str: """Normalize DataTransfer's type strings. https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-getdata 'text' -> 'text/plain' 'url' -> 'text/uri-list' """ if type == 'text': return 'text/plain' elif type == 'url': return 'tex...
31,291
def server_socket((host, port), (host_m,port_m)): """ Instances the main server. Receives data from client, forward the data to a mirror server and replies the client. :param host: host to bind socket :param port: port to listen to :return: """ s = Socket.get_instance() s.bind((h...
31,292
def _parity(N, j): """Private function to calculate the parity of the quantum system. """ if j == 0.5: pi = np.identity(N) - np.sqrt((N - 1) * N * (N + 1) / 2) * _lambda_f(N) return pi / N elif j > 0.5: mult = np.int32(2 * j + 1) matrix = np.zeros((mult, mult)) fo...
31,293
def get_log(id): """Returns the log for the given ansible play. This works on both live and finished plays. .. :quickref: Play; Returns the log for the given ansible play :param id: play id **Example Request**: .. sourcecode:: http GET /api/v2/plays/345835/log HTTP/1.1 **Exampl...
31,294
def filterLinesByCommentStr(lines, comment_str='#'): """ Filter all lines from a file.readlines output which begins with one of the symbols in the comment_str. """ comment_line_idx = [] for i, line in enumerate(lines): if line[0] in comment_str: comment_line_idx.append(i) ...
31,295
def test_browserdriver_phantomjs(): """PhantomJSDriver is registered as implementing BrowserDriver""" assert issubclass(PhantomJSDriver, BrowserDriver)
31,296
def assemble_result_from_graph(type_spec, binding, output_map): """Assembles a result stamped into a `tf.Graph` given type signature/binding. This method does roughly the opposite of `capture_result_from_graph`, in that whereas `capture_result_from_graph` starts with a single structured object made up of tenso...
31,297
def do_quota_class_show(cs, args): """List the quotas for a quota class.""" _quota_show(cs.quota_classes.get(args.class_name))
31,298
def test_right_shift_by_n(emulator, value1, value2, shift_amount): """Test for the left-shift-by-n utility""" # Arrange RAM[variables.tmp4] = 0x1 emulator.AC = -shift_amount & 0xFF RAM[0x42] = value1 emulator.Y = 0x00 emulator.X = 0x42 emulator.next_instruction = asm.symbol("right-shift-...
31,299