content
stringlengths
22
815k
id
int64
0
4.91M
def analyzer_options(*args): """ analyzer_options() Allow the user to set analyzer options. (show a dialog box) ( 'ui_analyzer_options' ) """ return _ida_kernwin.analyzer_options(*args)
32,100
def vector_vector_feature(v_a, v_b, weight, p_idx, frames, symmetric): """ Taking outer product, create matrix feature per pair, average, express in SO2 feature. :param v_a: [E, 3] :param v_b: [E, 3] :param weight: [E] :param p_idx: [E] index [0, V) :param frames: [V, 3, 3] per vertex, row...
32,101
def shopping_promos(bot, update): """ Get Latest Shopping Promos """ promo_list = {'Lazada': 'https://www.couponese.com/store/lazada.sg/', 'Amazon': 'https://www.couponese.com/store/amazon.com.sg/', 'Redmart': 'https://www.couponese.com/store/redmart.com/', ...
32,102
def parse_steps(filename): """ Read each line of FILENAME and return a dict where the key is the step and the value is a list of prerequisite steps. """ steps = defaultdict(lambda: list()) all_steps = set() with open(filename) as f: for line in f: words = line.split(' ') ...
32,103
def swait_multiple(cos): """Sync-wait for the given coroutines.""" asyncio.get_event_loop().run_until_complete(asyncio.wait(cos))
32,104
def load(file): # real signature unknown; restored from __doc__ """ load(file) -- Load a pickle from the given file """ pass
32,105
def sitestructure(config, path, extra): """Read all markdown files and make a site structure file""" # no error handling here, because compile_page has it entire_site = list() for page in glob.iglob(path + '**/*.md', recursive=True): merged = compile_page(None, config, page, extra) if 'tags' in merged: merg...
32,106
def _create_component(tag_name, allow_children=True, callbacks=[]): """ Create a component for an HTML Tag Examples: >>> marquee = _create_component('marquee') >>> marquee('woohoo') <marquee>woohoo</marquee> """ def _component(*children, **kwargs): if 'children' in kw...
32,107
def typeof(val, purpose=Purpose.argument): """ Get the Numba type of a Python value for the given purpose. """ # Note the behaviour for Purpose.argument must match _typeof.c. c = _TypeofContext(purpose) ty = typeof_impl(val, c) if ty is None: msg = _termcolor.errmsg( "can...
32,108
def scale_site_by_jobslots(df, target_score, jobslot_col=Metric.JOBSLOT_COUNT.value, count_col=Metric.NODE_COUNT.value): """ Scale a resource environment (data frame with node type information) to the supplied share. This method uses the number of jobslots in each node as a target metric. """ if df...
32,109
def primesfrom2to(n): """Input n>=6, Returns a array of primes, 2 <= p < n""" sieve = np.ones(n / 3 + (n % 6 == 2), dtype=np.bool) sieve[0] = False for i in xrange(int(n ** 0.5) / 3 + 1): if sieve[i]: k = 3 * i + 1 | 1 sieve[((k * k) / 3)::2 * k] = False sieve[(k * k + 4 * k - 2 * k * (i &...
32,110
def file_types_diff(cwd, old_ver, new_ver): """ NB: Uses Git and the magic/ directory Select only files that are Copied (C), Modified (M), Renamed (R), have their type (i.e. regular file, symlink, submodule, ...) changed (T) Returns a list of changed file types! """ # diff only Modified and Type c...
32,111
def TimeFromTicks(ticks): """construct an object holding a time value from the given ticks value.""" return Time(*time.localtime(ticks)[3:6])
32,112
def check_key_exists(file_location, section, key): """ Searches an INI Configuration file for the existance of a section & key :param file_location: The file to get a key value from :param section: The section to find the key value :param key: The key that can contain a value to retrieve :retur...
32,113
def replace_na(str_value: str, ch: str = "0") -> str: """replaces \"0\" with na, specifically designed for category list, may not work for others need Args: str_value (str): category list ch (str, optional): Replacemet char. Defaults to "0". Returns: str: clean cotegory name ""...
32,114
def intent_requires(): """ This view encapsulates the method get_intent_requirement It requires an Intent. :return: A dict containing the different entities required for an Intent """ data = request.get_json() if "intent" in data: return kg.get_intent_requirements(data["intent"]) ...
32,115
def standardize_df_off_tr(df_tr:pd.DataFrame, df_te:pd.DataFrame): """Standardize dataframes from a training and testing frame, where the means and standard deviations that are calculated from the training dataset. """ for key in df_tr.keys(): if key != 'target': ...
32,116
def filter_clusters(aoi_clusters, min_ratio, max_deviation, message, run=None): """ min_ratio: Has to have more than x % of all dots in the corner within the cluster max_deviation: Should not deviate more than x % of the screen size from the respective AO...
32,117
def set_to_true(): """matches v1, which assign True to v1""" key = yield symbol res = Assign(key, True) return res
32,118
def fit_spectrum(spectrum, lineshapes, params, amps, bounds, ampbounds, centers, rIDs, box_width, error_flag, verb=True, **kw): """ Fit a NMR spectrum by regions which contain one or more peaks. Parameters ---------- spectrum : array_like NMR data. ndarray or emulated type...
32,119
def d1_to_q1(A, b, mapper, cnt, M): """ Constraints for d1 to q1 """ for key in mapper['ck'].keys(): for i in range(M): for j in range(i, M): # hermetian constraints if i != j: A[cnt, mapper['ck'][key](i, j)] += 0.5 ...
32,120
def handle_args(): """ Gathers commmand line options and sets up logging according to the verbose param. Returns the parsed args """ parser = argparse.ArgumentParser(description='Checks the queue for new messages and caclulates the calendar as needed') parser.add_argument('--verbose', '-v', action='count')...
32,121
def relative_of(base_path: str, relative_path: str) -> str: """Given a base file and path relative to it, get full path of it""" return os.path.normpath(os.path.join(os.path.dirname(base_path), relative_path))
32,122
def _get_dict_roi(directory=None): """Get all available images with ROI bounding box. Returns ------- dict : {<image_id>: <ROI file path>} """ d = OrderedDict() for f in listdir(directory or IJ_ROI_DIR): d[splitext(f)[0]] = join(directory or IJ_ROI_DIR, f) return d
32,123
def geol_units(img, lon_w, lat, legend=None): """Get geological units based on (lon, lat) coordinates. Parameters ---------- img: 2d-array 2D geol map image centered at 180°. lon_w: float or array Point west longitude(s). lat: float or array Point latitude(s). legend...
32,124
def Water_Mask(shape_lsc,Reflect): """ Calculates the water and cloud mask """ mask = np.zeros((shape_lsc[1], shape_lsc[0])) mask[np.logical_and(Reflect[:, :, 3] < Reflect[:, :, 2], Reflect[:, :, 4] < Reflect[:, :, 1])] = 1.0 water_mask_temp = np.copy(mask) retur...
32,125
def unzip(sequence: Iterable) -> Tuple[Any]: """Opposite of zip. Unzip is shallow. >>> unzip([[1,'a'], [2,'b'], [3,'c']]) ((1, 2, 3), ('a', 'b', 'c')) >>> unzip([ [1,'a','A'], [2, 'b','B'], [3,'c','C'] ]) ((1, 2, 3), ('a', 'b', 'c'), ('A', 'B', 'C')) shallow nature of unzip. >>> unzip([ [...
32,126
def test_list_base64_binary_enumeration_1_nistxml_sv_iv_list_base64_binary_enumeration_2_3(mode, save_output, output_format): """ Type list/base64Binary is restricted by facet enumeration. """ assert_bindings( schema="nistData/list/base64Binary/Schema+Instance/NISTSchema-SV-IV-list-base64Binary-...
32,127
def plot_vm( vm_params_dict: dict, srf_corners: np.ndarray, land_outline_path: Path, centre_line_path: Path, mag: float, outdir: Path, ptemp: Path, logger: Logger = qclogging.get_basic_logger(), ): """ Plots VM domain as well as SRF domain if possible Parameters --------...
32,128
def get_gs_distortion(dict_energies: dict): """Calculates energy difference between Unperturbed structure and most favourable distortion. Returns energy drop of the ground-state relative to Unperturbed (in eV) and the BDM distortion that lead to ground-state. Args: dict_energies (dict): ...
32,129
def test__resolve_configuration__import_error(warnings_mock): """ Test resolution for an none-existant module. """ parsed = _parse_configuration({'abcdefghijklmnopqrstuvwxyz': HParams()}) _resolve_configuration(parsed) assert warnings_mock.warn.call_count == 1
32,130
def parse_accept_language(data: str = None): """Parse HTTP header `Accept-Language` Returns a tuple like below: ``` ((1.0, Locale('zh_Hant_TW')), (0.9, Locale('en')), (0.0, _fallback_ns)) ``` """ langs = {(0.0, _fallback_ns)} if data is None: return tuple(langs) for s in d...
32,131
def stop_service(): """ Stopping the service """ global __service_thread dbg("Trying to stop service thread") shutdown_service() __service_thread.join() __service_thread = None info("Server stopped") return True
32,132
def get_constants_name_from_value(constant_dict, value) : """ @param constant_dict : constant dictionary to consider @param value : value's constant name to retrieve @rtype : a string """ try: return constant_dict[value] except KeyError: log.error("The c...
32,133
def rotxyz(x_ang,y_ang,z_ang): """Creates a 3x3 numpy rotation matrix from three rotations done in the order of x, y, and z in the local coordinate frame as it rotates. The three columns represent the new basis vectors in the global coordinate system of a coordinate system rotated by this matrix. ...
32,134
def hpdi(proba, array): """ Give the highest posterior density interval. For example, the 95% HPDI is a lower bound and upper bound such that: 1. they contain 95% probability, and 2. in total, have higher peaks than any other bound. Parameters: proba: float A value b...
32,135
def upgrade(): """Migrations for the upgrade.""" from aiida.storage.psql_dos.migrations.utils.migrate_repository import migrate_repository migrate_repository(op.get_bind(), op.get_context().opts['aiida_profile'])
32,136
def chunks(list_: list[Any], chunk_size: int) -> Generator[list[Any], None, None]: """Equally-sized list chunks.""" for i in range(0, len(list_), chunk_size): yield list_[i:i + chunk_size]
32,137
def PAMI_for_delay(ts, n = 5, plotting = False): """This function calculates the mutual information between permutations with tau = 1 and tau = delay Args: ts (array): Time series (1d). Kwargs: plotting (bool): Plotting for user interpretation. defaut is False. n (int):...
32,138
def _capabilities(repo, proto): """return a list of capabilities for a repo This function exists to allow extensions to easily wrap capabilities computation - returns a lists: easy to alter - change done here will be propagated to both `capabilities` and `hello` command without any other act...
32,139
def findExonIntron(HLATypings, Sequence, Blocks): """ Find Exon and Intron sequence part from query based on the reference One typing; one or two blocks """ IMGTglstrings = re.sub("HLA-", "", HLATypings) tplist = IMGTglstrings.split("/") #query_seqs = [Seq(q, generic_dna) for q...
32,140
def dep(doclike: types.DocLike) -> Dict[str, int]: """ Count the number of times each syntactic dependency relation appears as a token annotation in ``doclike``. Args: doclike Returns: Mapping of dependency relation to count of occurrence. """ return dict(collections.Counte...
32,141
def fix_phonology_table(engine, phonology_table, phonologybackup_table, user_table): """Give each phonology UUID and modifier_id values; also give the phonology backups of existing phonologies UUID values. """ print_('Fixing the phonology table ... ') msgs = [] #engine.execute('set names latin1...
32,142
def D(field, dynkin): """A derivative. Returns a new field with additional dotted and undotted indices. Example: >>> D(L, "01") DL(01001)(-1/2) >>> D(L, "21") DL(21001)(-1/2) """ undotted_delta = int(dynkin[0]) - field.dynkin_ints[0] dotted_delta = int(dynkin[1]) ...
32,143
def _det(m, n): """Recursive calculation of matrix determinant""" """utilizing cofactors""" sgn = 1 Det = 0 if n == 1: return m[0][0] cofact = [n*[0] for i in range(n)] for i in range(n): _get_cofact(m, cofact,0,i,n); Det += sgn*m[0][i]*_det(cofact, n - 1); ...
32,144
def get_vcps() -> List[LinuxVCP]: """ Interrogates I2C buses to determine if they are DDC-CI capable. Returns: List of all VCPs detected. """ vcps = [] # iterate I2C devices for device in pyudev.Context().list_devices(subsystem="i2c"): vcp = LinuxVCP(device.sys_number) ...
32,145
def toGoatLatin(S): """ :type S: str :rtype: str """ l_words = [] for i, word in enumerate(S.split()): if not is_vowel(word[0]): word = word[1:] + word[0] aa = "a" * (i + 1) l_words.append(word + "ma" + aa) return " ".join(l_words)
32,146
def test_autoinstrumentation(): """Config auto instrumentation PL_IMPL_AUTO_INSTRUMENT=1""" if sys.platform == "win32": LOG("Skipped: Auto instrumentation is applicable only under Linux and with GCC") return build_target( "testprogram", "USE_PL=1 PL_IMPL_AUTO_INSTRUMENT=1", ...
32,147
def cli_file_convert(file_path, replace=False): """Simple logic for converting files from the CLI""" file_path = os.path.realpath(os.path.expanduser(file_path)) logger.info("Trying to convert: " + file_path) with open(file_path, 'r') as f: json_data = json.load(f, object_hook=clean_json._byteify...
32,148
def train(config: DictConfig, do_cross_validation: bool) -> Optional[float]: """Contains training pipeline. Instantiates all PyTorch Lightning objects from config. Args: config (DictConfig): Configuration composed by Hydra. do_cross_validation (bool): Whether to perform cross validation. ...
32,149
def list_startswith(_list, lstart): """ Check if a list (_list) starts with all the items from another list (lstart) :param _list: list :param lstart: list :return: bool, True if _list starts with all the items of lstart. """ if _list is None: return False lenlist = len(_list) ...
32,150
def _get_default_scheduler(): """Determine which scheduler system is being used. It tries to determine it by running both PBS and SLURM commands. If both are available then one needs to set an environment variable called 'SCHEDULER_SYSTEM' which is either 'PBS' or 'SLURM'. For example add the fol...
32,151
def get_subscribers(subreddit_, *args): """Gets current sub count for one or more subreddits. Inputs ------- str: Desired subreddit name(s) Returns ------- int: sub count or dict:{subreddit: int(sub count)} """ if len(args) > 0: subreddit = reddit.subreddit(subreddit_) ...
32,152
def test_md001_front_matter_with_title(): """ Test to make """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--disable-rules", "MD003,MD022", "--set", "extensions.front-matter.enabled=$!True", "scan", "test/resources/rules/md001/fr...
32,153
def validate_mongo_role_definition_id(ns): """ Extracts Guid role definition Id """ if ns.mongo_role_definition_id is not None: ns.mongo_role_definition_id = _parse_resource_path(ns.mongo_role_definition_id, False, "mongodbRoleDefinitions")
32,154
def pattern_match(value, pattern, env=None): """ Pattern match a value and a pattern. Args: value: the value to pattern-match on pattern: a pattern, consisting of literals and/or locally bound variables env: a dictionary of local variables bound while matching ...
32,155
def dijkstra(adjacency_list, source_vertex, cull_distance = sys.maxsize): """ Implementation of Dijkstra's Algorithm for finding shortest path to all vertices in a graph. Parameters ---------- adjacency_list (dict of int : (dict of int : int)) Maps vertices to a dictionary of ne...
32,156
def process_existing_fiber(country): """ Load and process existing fiber data. Parameters ---------- country : dict Contains all country specfic information. """ iso3 = country['iso3'] iso2 = country['iso2'].lower() folder = os.path.join(DATA_INTERMEDIATE, iso3, 'network_e...
32,157
def wraps(wrapped): """A functools.wraps helper that handles partial objects on Python 2.""" # https://github.com/google/pytype/issues/322 if isinstance(wrapped, functools.partial): # pytype: disable=wrong-arg-types return six.wraps(wrapped, assigned=_PARTIAL_VALID_ASSIGNMENTS) else: ...
32,158
def byte_to_bits(byte): """Convert a byte to an tuple of 8 bits for use in Merkle-Hellman. The first element of the returned tuple is the most significant bit. Usage:: byte_to_bits(65) # => [0, 1, 0, 0, 0, 0, 0, 1] byte_to_bits(b'ABC'[0]) # => [0, 1, 0, 0, 0, 0, 0, 1] byte_to_bit...
32,159
def load_translation(in_f, file): """ Extract lines from a template and save it to a file. """ # vd( in_f) with open(in_f, 'r') as f: l = f.read().split('\n') n = 0; r = {} for rs in l: n += 1 # находим подчеркивание со скобочками aa = re.findall(r'_\([^)]+\)', rs) for res in aa: # вырезаем саму строчку ...
32,160
def _init(): """ Internal function which checks if Maxima has loaded the "orthopoly" package. All functions using this in this file should call this function first. TEST: The global starts ``False``:: sage: sage.functions.orthogonal_polys._done False Then after using one...
32,161
def KK_RC48_fit(params, w, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ Rs = params["Rs"] R1 = params["R1"] R2 = params["R2"] R3 = params["R3"] R4 = params["R4"] R5 = params["R5"] R6 = params["R6"] ...
32,162
def test_complex_serialization(tmpdir): """ Test serializing a complex nested structure and checking it for validity (without deserializing) by inspecting Path objects in the value hierarchy """ AlkymiConfig.get().cache = True tmpdir = Path(str(tmpdir)) AlkymiConfig.get().cache_path = tmpdir...
32,163
def race(deer, seconds): """ Use the reindeer's speed and rest times to find the timed distance """ distance = 0 stats = reindeer[deer] resting = False while True: if resting: if seconds <= stats[2]: break seconds -= stats[2] else: ...
32,164
def AsdlEqual(left, right): """Check if generated ASDL instances are equal. We don't use equality in the actual code, so this is relegated to test_lib. """ if left is None and right is None: return True if isinstance(left, (int, str, bool, pybase.SimpleObj)): return left == right if isinstance(le...
32,165
def FindPriority(bug_entry): """Finds and returns the priority of a provided bug entry. Args: bug_entry: The provided bug, a IssueEntry instance. Returns: A string containg the priority of the bug ("1", "2", etc...) """ priority = '' for label in bug_entry.label: if label.text.lower().startswi...
32,166
def attention_padding_mask(q, k, padding_index=0): """Generate mask tensor for padding value Args: q (Tensor): (B, T_q) k (Tensor): (B, T_k) padding_index (int): padding index. Default: 0 Returns: (torch.BoolTensor): Mask with shape (B, T_q, T_k). True element stands for requ...
32,167
def get_pcap_bytes(pcap_file): """Get the raw bytes of a pcap file or stdin.""" if pcap_file == "-": pcap_bytes = sys.stdin.buffer.read() else: with open(pcap_file, "rb") as f: pcap_bytes = f.read() return pcap_bytes
32,168
def run(s, output_cmd=True, stdout=False): """Runs a subprocess.""" if output_cmd: print(f"Running: {s}") p_out = subprocess.run( s, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, check=False ) if stdout: return p_out.stdout.decode("utf-8").strip() else: ...
32,169
def process_params(request, standard_params=STANDARD_QUERY_PARAMS, filter_fields=None, defaults=None): """Parse query params. Parses, validates, and converts query into a consistent format. :keyword request: the bottle request :keyword standard_params: query params that are present ...
32,170
def all_attributes(cls): """ Each object will have the attributes declared directly on the object in the attrs dictionary. In addition there may be attributes declared by a particular object's parent classes. This function walks the class hierarchy to collect the attrs in the object's parent classes ...
32,171
def _reshape_model_inputs(model_inputs: np.ndarray, num_trajectories: int, trajectory_size: int) -> np.ndarray: """Reshapes the model inputs' matrix. Parameters ---------- model_inputs: np.ndarray Matrix of model inputs num_trajectories: int Number of traje...
32,172
def _create_module(module_name): """ex. mod = _create_module('tenjin.util')""" from types import ModuleType mod = ModuleType(module_name.split('.')[-1]) sys.modules[module_name] = mod return mod
32,173
def test_file_lock_timeout_error(project, runner): """Test file lock timeout.""" with FileLock(".renku.lock"): result = runner.invoke(cli, ["dataset", "import", "10.5281/zenodo.3715335"]) assert "Unable to acquire lock." in result.output
32,174
def VIS(img, **normalization): """Unmixes according to the Vegetation-Impervious-Soil (VIS) approach. Args: img: the ee.Image to unmix. **normalization: keyword arguments to pass to fractionalCover(), like shade_normalize=True. Returns: unmixed: a 3-band image file in o...
32,175
def create_labels(mapfile, Nodes=None): """ Mapping from the protein identifier to the group Format : ##protein start_position end_position orthologous_group protein_annotation :param Nodes: set -- create mapping only for these set of nodes :param mapfile: file that contains the...
32,176
def threshold_calc(CurrentValue): """Adaptive threshold calculation to adapt to different mel values or environments""" global filteredY, avgFilter, stdFilter, count, signal_time, used if abs(CurrentValue - avgFilter) > config.THRESHOLD * stdFilter: if CurrentValue > avgFilter: if count...
32,177
def provide(annotation_path=None, images_dir=None): """Return image_paths and class labels. Args: annotation_path: Path to an anotation's .json file. images_dir: Path to images directory. Returns: image_files: A list containing the paths of images. annotatio...
32,178
def test_plot_ci(): """ Tests the ci_plot function to make sure the outputs are correct. Returns -------- None The test should pass and no asserts should be displayed. 9 tests in total """ # test integration with calculate_boot_stats function test_stat ...
32,179
def sortKSUID(ksuidList): """ sorts a list of ksuids by their date (recent in the front) """ return sorted(ksuidList, key=lambda x: x.getTimestamp(), reverse=False)
32,180
def tearDownModule(): """Delete the test instance, if it was created.""" if CREATE_INSTANCE: Config.INSTANCE.delete()
32,181
def plot_worm_data(w): """ Plot the tempo, loudness, and structural annotations of a worm file against time. :param w: a WormFile object """ ax1 = plt.subplot(313) plt.plot(w.data[:,0],w.data[:,3],'|') plt.ylabel('Structure') plt.xlabel('Time (seconds)') ax2 = plt.subplot...
32,182
def is_installable_dir(path): # type: (str) -> bool """Return True if `path` is a directory containing a setup.py file.""" if not os.path.isdir(path): return False setup_py = os.path.join(path, "setup.py") if os.path.isfile(setup_py): return True return False
32,183
def get_vocabulary(list_): """ Computes the vocabulary for the provided list of sentences :param list_: a list of sentences (strings) :return: a dictionary with key, val = word, count and a sorted list, by count, of all the words """ all_the_words = [] for text in list_: for word ...
32,184
def Import_Method(): """The function Import_Method() allows the user to import an existing method and update the parameters. The function calls the function Display_Method() to set the initial values of the widgets, and PlotMethod() to display the graphical representation of the segments """ # Open a method fi...
32,185
def localize_list(original, welsh): """Call localize on each element in a list.""" for index, value in enumerate(original): localize(original, welsh, index, value)
32,186
def lod_build_config(slurm_nodes, mds_list, oss_list, fsname, mdtdevs, ostdevs, inet, mountpoint, index): """ Build lod configuration for LOD instance """ # pylint: disable=too-many-arguments,too-many-locals,too-many-branches # take slurm nodes directly if found node_list = ...
32,187
def check_field(rule: tuple, field: int) -> bool: """check if a field is valid given a rule""" for min_range, max_range in rule: if min_range <= field <= max_range: return True return False
32,188
def test_extern_vitis_ai_resnet18(dpu_target): """Test first part of Vitis AI on-the-fly quantization runtime with ResNet 18 model""" dtype = "float32" ishape = (1, 3, 224, 224) mod, params = relay.testing.resnet.get_workload(num_layers=18, batch_size=1) ref_mod, params = relay.testing.resnet.get_w...
32,189
def merge_adjacent(gen): """Merge adjacent messages that compare equal""" gen = iter(gen) last = gen.next() for this in gen: if this.merge_key == last.merge_key: last.merge(this) elif last < this: yield last last = this else: raise ...
32,190
def split(value, precision=1): """ Split `value` into value and "exponent-of-10", where "exponent-of-10" is a multiple of 3. This corresponds to SI prefixes. Returns tuple, where the second value is the "exponent-of-10" and the first value is `value` divided by the "exponent-of-10". Args ...
32,191
def test_pipeline_slice(): """Testing something.""" drop_num1 = SilentDropStage('num1') drop_num2 = SilentDropStage('num2') drop_char = SilentDropStage('char') pipeline = PdPipeline([drop_num1, drop_num2, drop_char]) assert len(pipeline) == 3 pipeline = pipeline[0:2] assert len(pipeline)...
32,192
def load_settings(): """Load JSON data from settings file :return: dictionary with settings details :rtype: dict """ if os.path.exists(config.SETTINGS_FILE): with open(config.SETTINGS_FILE, 'r') as sfile: settings = json.loads(sfile.read()) else: settings = { ...
32,193
def init_logging(logfile=None, debug=False): """Customize log and send it to console and logfile""" logging.addLevelName(25, 'PRINT') if logging.getLoggerClass().__name__ == 'FatalLogger': # disable log deduplication by Pelican logging.getLoggerClass().limit_filter.LOGS_DEDUP_MIN_LEVEL = loggi...
32,194
def lock_access(lock: threading.Lock): """ Context manager syntatic sugar for lock aquisition and release """ lock.aquire() yield lock.release()
32,195
def test_cert(host, port=443, timeout=5, **kwargs): """Test that a cert is valid on a site. Args: host (:obj:`str`): hostname to connect to. can be any of: "scheme://host:port", "scheme://host", or "host". port (:obj:`str`, optional): port to connect to on ho...
32,196
def get_predicates(): # noqa: E501 """get_predicates Get a list of predicates used in statements issued by the knowledge source # noqa: E501 :rtype: List[BeaconPredicate] """ return controller_impl.get_predicates()
32,197
def CheckUpdates(): """Check for updates and inform the user. """ manager = update_manager.UpdateManager() try: manager.PerformUpdateCheck() # pylint:disable=broad-except, We never want this to escape, ever. Only # messages printed should reach the user. except Exception: pass
32,198
def noisy_job_stage3(aht, ht, zz, exact=False): """Adds noise to decoding circuit. Args: ===== aht, ht, zz : numeric Circuit parameters for decoding circuit exact : bool If True, works with wavefunction Returns: ======== noisy_circuit : cirq.Circuit Noisy versio...
32,199