content
stringlengths
22
815k
id
int64
0
4.91M
def get_predictions(single_stream, class_mapping_dict, ip, port, model_name): """Gets predictions for a single image using Tensorflow serving Arguments: single_stream (dict): A single prodigy stream class_mapping_dict (dict): with key as int and value as class name ip (str): tensorflow ...
5,341,100
def interaction_graph(matrix): """Create a networkx graph object from a (square) matrix. Parameters ---------- matrix : numpy.ndarray | Matrix of mutual information, the information for the edges is taken from the upper matrix Returns ------- graph : networkx.Graph() ...
5,341,101
def tags_filter(osm_pbf, dst_fname, expression, overwrite=True): """Extract OSM objects based on their tags. The function reads an input .osm.pbf file and uses `osmium tags-filter` to extract the relevant objects into an output .osm.pbf file. Parameters ---------- osm_pbf : str Path to...
5,341,102
def bound_n_samples_from_env(n_samples: int): """Bound number of samples from environment variable. Uses environment variable `PYPESTO_MAX_N_SAMPLES`. This is used to speed up testing, while in application it should not be used. Parameters ---------- n_samples: Number of samples desired. ...
5,341,103
def weight_inter_agg(num_relations, self_feats, neigh_feats, embed_dim, weight, alpha, n, cuda): """ Weight inter-relation aggregator Reference: https://arxiv.org/abs/2002.12307 :param num_relations: number of relations in the graph :param self_feats: batch nodes features or embeddings :param ne...
5,341,104
def ho2ro(ho): """Axis angle pair to Rodrigues-Frank vector.""" return Rotation.ax2ro(Rotation.ho2ax(ho))
5,341,105
def stop_listener(): """ Tell the current running server to stop, must check is_listener_running() before calling """ f = open(SERVER_LOCK_FILE, 'r') port = int(f.readline()) f.close() server = ('127.0.0.1', port) client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) client_socke...
5,341,106
def get_ratio(old, new): # type: (unicode, unicode) -> float """Return a "similiarity ratio" (in percent) representing the similarity between the two strings where 0 is equal and anything above less than equal. """ if not all([old, new]): return VERSIONING_RATIO if IS_SPEEDUP: r...
5,341,107
def test_roundtrip_run(mlflow_client: MlflowClient): """Creates an experiment, gets it, and deletes it.""" # Create experiment experiment_name = "Test Roundtrip Run" experiment_id = mlflow_client.create_experiment(experiment_name) # Create run run = mlflow_client.create_run(experiment_id) m...
5,341,108
def test_wam_format(filename): """ Ensure the yaml file is valid and all required fields are present in each api block """ print('Checking ' + filename) with open(filename, 'rb') as fh: config = yaml.load(fh.read()) assert(config['version'] == '1.0') for name, webarchive in confi...
5,341,109
def sample2D(F, X, Y, mask=None, undef_value=0.0, outside_value=None): """Bilinear sample of a 2D field *F* : 2D array *X*, *Y* : position in grid coordinates, scalars or compatible arrays *mask* : if present must be a 2D matrix with 1 at valid and zero at non-valid points *undef_va...
5,341,110
async def test_add_and_delete(client, basedn): """ Test adding and deleting an LDAP entry. """ async with client.connect(True) as conn: entry = LDAPEntry("cn=async_test,%s" % basedn) entry["objectclass"] = [ "top", "inetOrgPerson", "person", "organ...
5,341,111
def read(file=None, timeout=10, wait=0.2, threshold=32): """Return the external temperature. Keyword arguments: file -- the path to the 1-wire serial interface file timeout -- number of seconds without a reading after which to give up wait -- number of seconds to wait after a failed read before ret...
5,341,112
def rotations_to_radians(rotations): """ converts radians to rotations """ return np.pi * 2 * rotations
5,341,113
def _expect_ket(oper, state): """Private function to calculate the expectation value of an operator with respect to a ket. """ oper, ket = jnp.asarray(oper), jnp.asarray(state) return jnp.vdot(jnp.transpose(ket), jnp.dot(oper, ket))
5,341,114
def resnet152(pretrained=False, last_stride=1, model_path=''): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ return _resnet(pretrained=pretrained...
5,341,115
def check_wheel_move_during_closed_loop(data, wheel_gain=None, **_): """ Check that the wheel moves by approximately 35 degrees during the closed-loop period on trials where a feedback (error sound or valve) is delivered. Metric: M = abs(w_resp - w_t0) - threshold_displacement, where w_resp = position at r...
5,341,116
def next_fast_len(target: int) -> int: """ Find the next fast size of input data to `fft`, for zero-padding, etc. SciPy's FFTPACK has efficient functions for radix {2, 3, 4, 5}, so this returns the next composite of the prime factors 2, 3, and 5 which is greater than or equal to `target`. (These ar...
5,341,117
def deformed(solver): """ Method: output the deformed state to a file """ V = FunctionSpace(solver.domain.mesh,solver.Ve) y = SpatialCoordinate(solver.domain.mesh) write = dot(Constant(solver.F_macro),y)+solver.v filename = File(os.path.join(solver.work_dir, "deformation.pvd")) filename << pro...
5,341,118
def get_user_requests(): """ endpoint for getting requests of a perticular user. --- parameters: - name: x-access-token in: header type: string required: true - name: user_id required: true in: path type: integer """
5,341,119
def human_format(val : int, fmt = '.1f') -> str : """ convert e.g. 1230 -> 1.23k """ units = ['', 'K', 'M', 'G'] base = min(int(np.floor(np.log10(val)))//3, len(units)) if base==0: return str(val) val = val/10**(3*base) res = ('{{:{}}} {}'.format(fmt, units[base])).format(val) ret...
5,341,120
def select_or_insert(conn, table, id_name, payload, name=None, multi=False, insert=True): """ Prepare the SQL statements, payload MUST be a list """ log.debug('payload: {}'.format(payload)) if multi is False: sql_str = ''.join(['SELECT ', id_name, ' FROM ', table, ' WHERE ', name, ' LIKE (%s);']) ...
5,341,121
def random_choice(number: int) -> bool: """ Generate a random int and compare with the argument passed :param int number: number passed :return: is argument greater or equal then a random generated number :rtype: bool """ return number >= randint(1, 100)
5,341,122
def request_l3_attachments(session, apic) -> Any: """Request current policy enformation for encap for Outs""" root = None uri = f"https://{apic}/api/class/l3extRsPathL3OutAtt.xml" response = session.get(uri, verify=False) try: root = ET.fromstring(response.text) except ET.Pa...
5,341,123
def main(args=None): """ Runs an Explorer node """ rclpy.init(args=args) explorer = ExploreController() explorer.run() rclpy.spin(explorer) explorer.destroy_node() rclpy.shutdown()
5,341,124
def robot(ctxt, file_=None): """Extract data from a ``pybot`` report. :param ctxt: the build context :type ctxt: `Context` :param file\_: name of the file containing the pybot report """ assert file_, 'Missing required attribute "file"' results = xmlio.Fragment() for case in RobotFram...
5,341,125
def bet_plot( pressure, bet_points, minimum, maximum, slope, intercept, p_monolayer, bet_monolayer, ax=None ): """ Draw a BET plot. Parameters ---------- pressure : array Pressure points which will make up the x axis. bet_points : array BET-tr...
5,341,126
def paged_response( *, view: viewsets.GenericViewSet, queryset: Optional[QuerySet] = None, status_code: Optional[int] = None, ): """ paged_response can be used when there is a need to paginate a custom API endpoint. Usage: class UsersView(ModelViewSet): ... ...
5,341,127
def getObjectPositions(mapData, threshold, findCenterOfMass = True): """Creates a segmentation map and find objects above the given threshold. Args: mapData (:obj:`numpy.ndarray`): The 2d map to segment. threshold (float): The threshold above which objects will be selected. findCent...
5,341,128
def specific_humidity(p,RH,t,A=17.625,B=-30.11,C=610.94,masked=False): """ From Mark G. Lawrence, BAMS Feb 2005, eq. (6) q = specific_humidity(p,RH,t,A,B,C) inputs: p = pressure (Pa) RH = relative humidity (0-1) t = temperature (K) keywords: A, B and C are optional fi...
5,341,129
def list_versions(): """ List the EMDB-SFF versions that are migratable to the current version :return: status :return: version_count """ version_count = len(VERSION_LIST) for version in VERSION_LIST[:-1]: _print('* {version}'.format(version=version)) return os.EX_OK, version_cou...
5,341,130
def build_parser(): """ Build a pyparsing parser for our custom topology description language. :return: A pyparsing parser. :rtype: pyparsing.MatchFirst """ ParserElement.setDefaultWhitespaceChars(' \t') nl = Suppress(LineEnd()) inumber = Word(nums).setParseAction(lambda l, s, t: int(t[...
5,341,131
def decode_owner(owner_id: str) -> str: """Decode an owner name from an 18-character hexidecimal string""" if len(owner_id) != 18: raise ValueError('Invalid owner id.') hex_splits = split_by(owner_id, num=2) bits = '' for h in hex_splits: bits += hex_to_bin(h) test_owner = '' for seq in split_by(b...
5,341,132
def test_inline_config(): """:meth:`config.inline()` shell commands list to string.""" test_config = config.inline(ibefore_config) assert test_config == iafter_config
5,341,133
def _get_back_up_generator(frame_function, *args, **kwargs): """Create a generator for the provided animation function that backs up the cursor after a frame. Assumes that the animation function provides a generator that yields strings of constant width and height. Args: frame_function: A funct...
5,341,134
def from_aiohttp( schema_path: str, app: Any, *, base_url: Optional[str] = None, method: Optional[Filter] = None, endpoint: Optional[Filter] = None, tag: Optional[Filter] = None, operation_id: Optional[Filter] = None, skip_deprecated_operations: bool = False, validate_schema: boo...
5,341,135
def wasb(connection_name, path_from, path_to, is_file, raise_errors, sync_fw): """Create wasb path context.""" _download( connection_name=connection_name, connection_kind=V1ConnectionKind.WASB, path_from=path_from, path_to=path_to, is_file=is_file, raise_errors=ra...
5,341,136
def summarize(fname, start, stop,output_dir): """ Process file[start:stop] start and stop both point to first char of a line (or EOF) """ ls_1995_1996 = [] for i in range (1995,2006): ls_1995_1996.append([]) with open(fname, newline='', encoding='utf-8') as inf: # jump to s...
5,341,137
def compute_recall(true_positives, false_negatives): """Compute recall >>> compute_recall(0, 10) 0.0 >>> compute_recall(446579, 48621) 0.901815 """ return true_positives / (true_positives + false_negatives)
5,341,138
def get_highest_seat_id(): """ Returns the highest seat ID from all of the boarding passes. """ return max(get_seat_ids())
5,341,139
def error_function_index(gpu_series, result_series): """ utility function to compare GPU array vs CPU array Parameters ------ gpu_series: cudf.Series GPU computation result series result_series: pandas.Series Pandas computation result series Returns ----- double ...
5,341,140
def get_tipo_aqnext(tipo) -> int: """Solve the type of data used by DJANGO.""" tipo_ = 3 # subtipo_ = None if tipo in ["int", "uint", "serial"]: tipo_ = 16 elif tipo in ["string", "stringlist", "pixmap", "counter"]: tipo_ = 3 elif tipo in ["double"]: tipo_ = 19 elif...
5,341,141
def fetch_indicators_command(client: Client) -> List[Dict]: """Wrapper for fetching indicators from the feed to the Indicators tab. Args: client: Client object with request Returns: Indicators. """ indicators = fetch_indicators(client) return indicators
5,341,142
def test_dtm_alt_min_max(): """ Test dtm alt min/max """ dtm_file = os.path.join(data_path(), "dtm", "srtm_ventoux", "srtm90_non_void_filled", "N44E005.hgt") geoid_file = os.path.join(data_path(), "dtm", "geoid", "egm96_15.gtx") dtm_ventoux = DTMIntersection(dtm_file, geoid_file, roi=[256, 256, ...
5,341,143
def hr_lr_ttest(hr, lr): """ Returns the t-test (T statistic and p value), comparing the features for high- and low-risk entities. """ res = stats.ttest_ind(hr.to_numpy(), lr.to_numpy(), axis=0, nan_policy="omit", equal_var=False) r0 = pd.Series(res[0], index=hr.columns) r1 = pd.Series(res[1], inde...
5,341,144
def _is_empty(str_: str) -> bool: """文字列が空か 文字列が空であるかを判別する Args: str_ (str): 文字列 Returns: bool: 文字列が空のときはTrue, 空でないときはFalseを返す. """ if str_: return False return True
5,341,145
def delete(val: str) -> None: """Deletes a word from the trie if it exists and displays the status of the operation Args: val (str): The word you wish to delete from the trie """ print(request('Delete keyword', val))
5,341,146
def template (name, typename, value) : """ <configProperty> <name>${name}</name> <value> <type> <kind>tk_${typename}</kind> </type> <value> <${typename}>${value}</${typename}> </value> </value> </configProperty> """
5,341,147
def main(): """ Run this main function if this script is called directly. :return: None """ working_directory = os.path.dirname(os.path.realpath(__file__)) print(working_directory) repo_details = RepoDetails(working_directory, sub_paths=['\\README.md'], use_directory_hash=True) r...
5,341,148
def energy_generate_random_range_dim2(filepath,dim_1_low,dim_1_high,dim_2_low,dim_2_high,num=500): """ 6, 8 and 10 """ queryPool=[] query=[] for _ in range(num): left1 = random.randint(dim_1_low, dim_1_high) right1 = random.randint(left1, dim_1_high) query.append...
5,341,149
def preprocess(data_folder): """ Runs the whole pipeline and returns NumPy data array""" SAMPLE_TIME = 30 CHANNELS = ['EEG Fpz-Cz', 'EEG Pz-Oz'] res_array = [] for path in os.listdir(data_folder): if path.endswith("PSG.edf"): full_path = os.path.join(data_folder, path) ...
5,341,150
def get_waas_policies(compartment_id: Optional[str] = None, display_names: Optional[Sequence[str]] = None, filters: Optional[Sequence[pulumi.InputType['GetWaasPoliciesFilterArgs']]] = None, ids: Optional[Sequence[str]] = None, state...
5,341,151
def _get_output_type(output): """Choose appropriate output data types for HTML and LaTeX.""" if output.output_type == 'stream': html_datatype = latex_datatype = 'ansi' text = output.text output.data = {'ansi': text[:-1] if text.endswith('\n') else text} elif output.output_type == 'er...
5,341,152
def cat_train_validate_on_cv( logger, run_id, train_X, train_Y, test_X, metric, kf, features, params={}, num_class=None, cat_features=None, log_target=False, ): """Train a CatBoost model, validate using cross validation. If `test_X` has a valid value, creates a ne...
5,341,153
def find_left(char_locs, pt): """Finds the 'left' coord of a word that a character belongs to. Similar to find_top() """ if pt not in char_locs: return [] l = list(pt) while (l[0]-1, l[1]) in char_locs: l = [l[0]-1, l[1]] return l
5,341,154
def make_file_url(file_id, base_url): """Create URL to access record by ID.""" url_parts = list(urlparse.urlparse(base_url)) url_parts[2] = pathlib.posixpath.join( DATAVERSE_API_PATH, DATAVERSE_FILE_API ) args_dict = {'persistentId': file_id} url_parts[4] = urllib.parse.urlencode(args_di...
5,341,155
def std_func(bins, mass_arr, vel_arr): """ Calculate std from mean = 0 Parameters ---------- bins: array Array of bins mass_arr: array Array of masses to be binned vel_arr: array Array of velocities Returns --------- std_arr: array Standard devia...
5,341,156
def test_transact_opcode(deploy_client): """ The receipt status field of a transaction that did not throw is 0x1 """ contract_proxy = deploy_rpc_test_contract(deploy_client, "RpcTest") address = contract_proxy.contract_address assert len(deploy_client.web3.eth.getCode(to_checksum_address(address))) > 0...
5,341,157
def log_neg(rho,mask=[1,0]): """ Calculate the logarithmic negativity for a density matrix Parameters: ----------- rho : qobj/array-like Input density matrix Returns: -------- logneg: Logarithmic Negativity """ if rho.type != 'oper': raise TypeError("In...
5,341,158
def test_remove(tmpdir, kind, driver, specify_driver): """Test various dataset removal operations""" extension = {"ESRI Shapefile": "shp", "GeoJSON": "json"}[driver] filename = "delete_me.{extension}".format(extension=extension) output_filename = str(tmpdir.join(filename)) create_sample_data(output...
5,341,159
def create_polygon(pixels_selected: set, raster_path: str) -> gpd.GeoDataFrame: """ It allows to transform each of the indexes of the pixel data in coordinates for further processing the answer polygon Parameters -------------- pixels_selected: set Set with the pixels selected for t...
5,341,160
def test_delete_webhook(client): """Tests deletion of a webhook """ resp = client.delete_webhook(PROJECT_ID, WEBHOOK_ID) assert resp['project_id'] == PROJECT_ID assert resp['webhook_deleted']
5,341,161
def main(rows: int, columns: int, mines: int) -> None: """Your favorite sweeping game, terminal style.""" ui = PySweeperUI(rows, columns, mines) ui.main()
5,341,162
def read_output(path_elec,path_gas): """ Used to read the building simulation I/O file Args: path_elec: file path where data is to be read from in minio. This is a mandatory parameter and in the case where only one simulation I/O file is provided, the path to this file should be indicated here. ...
5,341,163
def parse_lmap(filename, goal, values): """Parses an LMAP file into a map of literal weights, a LiteralDict object, the literal that corresponds to the goal variable-value pair, and the largest literal found in the file.""" weights = {} max_literal = 0 literal_dict = LiteralDict() for line i...
5,341,164
def show_sample(sample): """Shows the sample with tasks and answers""" print("Train:") for i in range(len(sample["train"])): fig = plt.figure() ax1 = fig.add_subplot(121) ax1.matshow(np.array(sample["train"][i]["input"]), cmap="Set3", norm=mpl.colors.Normalize(vmin=0, vmax=9)) ...
5,341,165
def read_image(path: str): """ Read an image file :param path: str. Path to image :return: The image """ return imageio.imread(path)
5,341,166
def main(): """ Quality Control Workflow. """ cfp = ConfigParser() if cfp.start is not None and cfp.end is not None: assert cfp.start <= cfp.end else: print("Error Start or End Time.") sys.exit() if cfp.index != "all": print("Index should be [ al...
5,341,167
def test_send_invalid_apikey( api_options, email_id, recipient, email_data ): """ Test send with invalid API key. """ invalid_api = sendwithus.api('INVALID_API_KEY', **api_options) result = invalid_api.send( email_id, recipient, email_data=email_data ) assert ...
5,341,168
def electrolyte_conductivity_Capiglia1999(c_e, T, T_inf, E_k_e, R_g): """ Conductivity of LiPF6 in EC:DMC as a function of ion concentration. The original data is from [1]. The fit is from Dualfoil [2]. References ---------- .. [1] C Capiglia et al. 7Li and 19F diffusion coefficients and therma...
5,341,169
def random_bdays(n): """Returns a list of integers between 1 and 365, with length n. n: int returns: list of int """ t = [] for i in range(n): bday = random.randint(1, 365) t.append(bday) return t
5,341,170
def int_to_charset(val, charset): """ Turn a non-negative integer into a string. """ if not val >= 0: raise ValueError('"val" must be a non-negative integer.') if val == 0: return charset[0] output = "" while val > 0: val, digit = divmod(val, len(charset)) output += chars...
5,341,171
def Reset(remove_obstacles = False, remove_weight = False): """ Rsets all the nodes to normal nodes except the start and end nodes """ global remaining_nodes_to_flip remaining_nodes_to_flip = 0 screen.fill(background_color) for column in node_list: for node in column: if node.is_obstacle: if remove_obs...
5,341,172
def search(tabela, *, parms='*', clause=None): """ Função que recebe como parâmetro obrigatório o nome da tabela a ser consultada, como parâmetro padrão recebe os filtros da pesquisa e retorna todas as linhas encontradas """ banco = Banco() banco.connect() banco.execute(f"SELECT {parms} FR...
5,341,173
def make_mask_3d(imagename, thresh, fl=False, useimage=False, pixelmin=0, major=0, minor=0, pixelsize=0, line=False, overwrite_old=True, closing_diameter=6, pbimage=None, myresidual=None, myimage=None, extension='.fullmask', spectral_closing=3): ""...
5,341,174
def hash(data): """run the default hashing algorithm""" return _blacke2b_digest(data)
5,341,175
def _print_log_events( events: typing.List[dict], function_name: str, show_name: bool, ): """ Print out the given set of events from a `get_log_events` call. :param events: The raw events to print out. :param function_name: The name of the function from which the events came...
5,341,176
def _insert_text_func(s, readline): """Creates a function to insert text via readline.""" def inserter(): readline.insert_text(s) readline.redisplay() return inserter
5,341,177
def init_logging(verbose: bool) -> None: """ Initialize the logging system """ if verbose: logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.DEBUG) else: logging.basicConfig(format="%(levelname)s: %(message)s")
5,341,178
def dumps(ndb_model, **kwargs): """Custom json dumps using the custom encoder above.""" return NdbEncoder(**kwargs).encode(ndb_model)
5,341,179
def classifier_on_rbm_scores(models, dataset_train, dataset_test, clfs=None): """ TODO: store progress on heirarchical clustering; that is the slowest step clfs: list of classifiers """ if clfs is None: clfs = [CLASSIFIER] features_order = list(models.keys()) feature_dim = len(featu...
5,341,180
def _evolve_no_collapse_psi_out(config): """ Calculates state vectors at times tlist if no collapse AND no expectation values are given. """ global _cy_rhs_func global _cy_col_spmv_func, _cy_col_expect_func global _cy_col_spmv_call_func, _cy_col_expect_call_func num_times = len(config....
5,341,181
def say_hello(): """Prints "Hello, world!" """ print("Hello, World!")
5,341,182
def get_version_from_package() -> str: """Read the package version from the source without importing it.""" path = os.path.join(os.path.dirname(__file__), "arcpy2foss/__init__.py") path = os.path.normpath(os.path.abspath(path)) with open(path) as f: for line in f: if line.startswith...
5,341,183
def delete_cert(resource, event, trigger, **kwargs): """Delete client certificate and private key """ if not verify_client_cert_on(): return with get_certificate_manager(**kwargs) as cert: if cfg.CONF.nsx_v3.nsx_client_cert_storage.lower() == "none": filename = get_cert_filename...
5,341,184
def create_critic_train_op(hparams, critic_loss, global_step): """Create Discriminator train op.""" with tf.name_scope('train_critic'): critic_optimizer = tf.train.AdamOptimizer(hparams.critic_learning_rate) output_vars = [ v for v in tf.trainable_variables() if v.op.name.startswith(...
5,341,185
def interpolate(data, tstep): """Interpolate limit order data. Uses left-hand interpolation, and assumes that the data is indexed by timestamp. """ T, N = data.shape timestamps = data.index t0 = timestamps[0] - (timestamps[0] % tstep) # 34200 tN = timestamps[-1] - (timestamps[-1] % tstep)...
5,341,186
def test_aligner_9(): """ testing semi-global alignment example coming from https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-096-algorithms-for-computational-biology-spring-2005/lecture-notes/lecture5_newest.pdf page 22. The example targets `end-gap-free` alignment. This im...
5,341,187
def doColorTransfer(org_content, output, raw_data, with_color_match = False): """ org_content path or 0-1 np array output path or 0-1 np array raw_data boolean | toggles input """ if not raw_data: org_content = imageio.imread(org_content, pilmode="RGB").astype(float)/256 output = image...
5,341,188
def update_file(filename: str, variable_dict: dict) -> None: """Update the given file with the given data""" try: file = open(f"data/gamedata/{filename}.json", "w", encoding="utf-8") file.write(dumps(variable_dict, indent=3)) file.close() except TypeError: print("TypeError")
5,341,189
def test_chunked_full_blocks(): """ Test chunking when the input length is a multiple of the block length. """ chunks = list(_chunked("abcd", 2)) assert len(chunks) == 2 assert len(chunks[0]) == 2 assert len(chunks[1]) == 2
5,341,190
def tb_filename(tb): """Helper to get filename from traceback""" return tb.tb_frame.f_code.co_filename
5,341,191
async def fetch_symbol(symbol: str): """ get symbol info """ db = SessionLocal() s = db.query(SymbolSchema).filter(SymbolSchema.symbol == symbol).first() res = {"symbol": s.symbol, "name": s.name} return res
5,341,192
def compile_to_json(expression: expr.Expression): """Compile expression tree to json-serializable python datatypes""" pass
5,341,193
def all_live_response_sessions(cb: CbResponseAPI) -> List: """List all LR sessions still in server memory.""" return [sesh for sesh in cb.get_object(f"{CBLR_BASE}/session")]
5,341,194
def unserialize_model_params(bin: bin): """Unserializes model or checkpoint or diff stored in db to list of tensors""" state = StatePB() state.ParseFromString(bin) worker = sy.VirtualWorker(hook=None) state = protobuf.serde._unbufferize(worker, state) model_params = state.tensors() return mo...
5,341,195
def config(clazz): """Decorator allowing to transform a python object into a configuration file, and vice versa :param clazz: class to decorate :return: the decorated class """ return deserialize(serialize(dataclass(clazz)))
5,341,196
def wrap_method_once(func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]: """manage Runnable state for given method""" # we don't re-wrap methods that had the state management wrapper if hasattr(func, 'handler_wrapped'): return func @functools.wraps(func) def wrapped_runnable_method(*ar...
5,341,197
async def all(iterable: ty.AsyncIterator[T]) -> bool: """Return ``True`` if **all** elements of the iterable are true (or if the iterable is empty). :param iterable: The asynchronous iterable to be checked. :type iterable: ~typing.AsyncIterator :returns: Whether all elements of the iterable are ...
5,341,198
def set_file_logger(filename: str, name: str = 'parsl', level: int = logging.DEBUG, format_string: Optional[str] = None): """Add a stream log handler. Args: - filename (string): Name of the file to write logs to - name (string): Logger name - level (logging.LEVEL): Set the logging level...
5,341,199