content
stringlengths
22
815k
id
int64
0
4.91M
def test_delete2(service, create_cmd): """Run command 'delete' to delete second application plan""" ret = toolbox.run_cmd(create_cmd('delete', f"{service['id']} {out_variables['plan2'][0]}")) assert not ret['stderr'] assert f"Application plan id: {out_variables['plan2'][0]} deleted" in ret['stdout']
40,800
def manhattan_distances(X, Y): """Compute pairwise Manhattan distance between the rows of two matrices X (shape MxK) and Y (shape NxK). The output of this function is a matrix of shape MxN containing the Manhattan distance between two rows. Arguments: X {np.ndarray} -- First matrix, contai...
40,801
def remove_access_group(request): """ Add access groups to the image. """ if request.method != "POST": messages.error(request, "Invalid request method.") return redirect('images') if 'id' not in request.POST or not request.POST.get('id').isdigit() or 'access_group' not in request.PO...
40,802
def convert_to_jpg_if_needed(src): """ If the src image is not in the supported image format list, convert it to jpg :param src: the source file :returns: None, or the new file (django file) """ im = Image.open(src) if im.format in settings.XGDS_IMAGE_ACCEPTED_WEB_FORMATS: return Non...
40,803
def test_average_gap_temp(small_core_no_power): """Test the calculation of area-weighted average temperature""" # print(small_core_no_power.asm_params['duct_ftf'][1] / np.sqrt(3)) # print(small_core_no_power.asm_params['pin_pitch'][1]) # print(small_core_no_power.asm_params['n_pin'][1]) # print(smal...
40,804
def test_gather_segments_data(df_and_regressors): """Check that TSDataset._gather_segments_data correctly finds segment data for info/describe methods.""" df, df_exog, known_future = df_and_regressors # add NaN in the middle df.iloc[-5, 0] = np.NaN # add NaNs at the end df.iloc[-3:, 1] = np.NaN ...
40,805
def replace_strings_in_file(i): """ Input: { file (file_out) - if !='', use this file for output, otherwise overwrite original one! replacement_json_file - replacement file with multiple strings to substitute } Output: { return...
40,806
def fill_polygon(points, im_shape): """Fill the polygon defined by convex or contour points Parameters ---------- points: array Coordinates of the points that define the convex or contour of the mask im_shape: array Array shape of the mask Returns ------- im_cnt: array Fil...
40,807
def load(section, option, archive=_ConfigFile): """ Load variable """ cfg = ConfigParser() try: cfg.readfp(file(archive)) except Exception, e: sys.stderr.write("%s, %s\n" % (archive, e.strerror)) return try: return cfg.get(section, option) except: sys.stderr.write("Incorrect value...
40,808
def merge_duplicates(model_name, keep_descriptors=False): """ Identifies repeated experimental values and returns mean values for those data along with their standard deviation. Only aggregates experimental values that have been acquired at the same temperature and pressure. Parameters --------...
40,809
def compress_dcmroot_2_zipfile(dcmroot, zip_file): """ :param dcmroot: :param zip_file: :return: """ print('zipping %s to %s'%(dcmroot, zip_file)) ziping_file = zipfile.ZipFile(zip_file, 'w') with ziping_file: for _subroot, _, files in os.walk(dcmroot): for ...
40,810
def autoencoder_cost_and_grad_sparse(theta, visible_size, hidden_size, lambda_, rho_, beta_, data): """ Version of cost and grad that incorporates the hidden layer sparsity constraint rho_ : the target sparsity limit for each hidden node activation beta_ : controls the weight of the sparsity pen...
40,811
def isnpixok(npix): """Return :const:`True` if npix is a valid value for healpix map size, :const:`False` otherwise. Parameters ---------- npix : int, scalar or array-like integer value to be tested Returns ------- ok : bool, scalar or array-like :const:`True` if given value is...
40,812
def setup_logging( default_level=logging.DEBUG, env_key='LOG_CFG' ): """Setup logging configuration """ from cep_price_console.utils import config global debug_log global info_log global error_log config.LOGGING_PATH.mkdir(parents=True, exist_ok=True) message = [] pa...
40,813
def preprocess(filename, filename_out): """ The input python file will be decorated with indent/dedent so that textX can find the blocks easily. This function will write the output code in filename_out. filename: str name of the file to parse. filename_out: str name of the temp...
40,814
def solve_field(fname, timeout=15, solve_opts=None, *args, **kwargs): """ Plate solves an image. Note: This is a low-level wrapper around the underlying `solve-field` program. See `get_solve_field` for more typical usage and examples. Args: fname(str, required): Filename to solve in...
40,815
def gcs_option(args, run): """Add a Google Cloud Storage File observer to the experiment. The argument value should be `gs://<bucket>/path/to/exp`. """ match_obj = re.match(r"gs:\/\/([^\/]*)\/(.*)", args) if match_obj is None or len(match_obj.groups()) != 2: raise ValueError( "V...
40,816
def get_team_metadata(convert_users_role_to_string=False): """Returns team metadata :param convert_users_role_to_string: convert integer team users' roles to human comprehensible strings :type convert_users_role_to_string: bool :return: team metadata :rtype: dict """ response = _api.send_re...
40,817
def get_request_timestamp(req_type=None, timestamp=getCurrentMillis()): """ :param req_type: YTD, QTD, MTD, WTD, TODAY or None if None return first unix timestamp :return: unix timestamp """ @dataclass class YTD(object): pass bench_date = pd.to_datetime(getUTCBeginDay(timestamp...
40,818
async def test_ssdp_not_successful_2( hass: HomeAssistant, remote: Mock, no_mac_address: Mock ): """Test starting a flow from discovery but no device found.""" with patch( "homeassistant.components.samsungtv.bridge.Remote", side_effect=OSError("Boom"), ), patch( "homeassistant.co...
40,819
def test_load_user_by_token(session): """Ensure a user can be looked up by JSON Web Token.""" nu = auth_service.register_user(session, 'test@jadetree.io', 'hunter2JT', 'Test User') assert nu.id == 1 # load_user_by_token is hardcoded for JWT_SUBJECT_BEARER_TOKEN token = auth_service.generate_user_to...
40,820
def to_nest_placeholder(nested_tensor_specs, default=None, name_scope="", outer_dims=()): """Converts a nest of TensorSpecs to a nest of matching placeholders. Args: nested_tensor_specs: A nest of tensor specs. default: Optional consta...
40,821
def train(args): """Run training loop with the given args. The function consists of the following steps: 1. Load model: gets the model from a checkpoint or from models/models.py. 2. Load optimizer and learning rate scheduler. 3. Get data loaders and class weights. 4. Get loss fu...
40,822
async def discover(): """Discover and return devices on local network.""" discovery = TuyaDiscovery() try: await discovery.start() await asyncio.sleep(DEFAULT_TIMEOUT) finally: discovery.close() return discovery.devices
40,823
def test_loss_L2_5(): """ equation: NavierStokes 2D """ geo = psci.geometry.Rectangular( space_origin=(-0.05, -0.05), space_extent=(0.05, 0.05)) pdes = psci.pde.NavierStokes(nu=0.01, rho=1.0) pdes, geo = psci.discretize(pdes, geo, space_nsteps=(4, 4)) bc_value = np.zeros((12, 2), d...
40,824
def update_firewall_policy(module, oneandone_conn): """ Updates a firewall policy based on input arguments. Firewall rules and server ips can be added/removed to/from firewall policy. Firewall policy name and description can be updated as well. module : AnsibleModule object oneandone_conn: ...
40,825
def dense_to_one_hot(labels_dense, num_classes): """Convert class labels from scalars to one-hot vectors.""" num_labels = labels_dense.shape[0] index_offset = np.arange(num_labels) * num_classes labels_one_hot = np.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 ...
40,826
def expanded_velocities_from_line_vortices( points, origins, terminations, strengths, ages=None, nu=0.0, ): """This function takes in a group of points, and the attributes of a group of line vortices. At every point, it finds the induced velocity due to each line vortex. Citatio...
40,827
def normcase(path): """Normalize the case of a pathname. On Unix and Mac OS X, this returns the path unchanged; on case-insensitive filesystems, it converts the path to lowercase. On Windows, it also converts forward slashes to backward slashes.""" return 0
40,828
def typeof(obj, t): """Check if a specific type instance is a subclass of the type. Args: obj: Concrete type instance t: Base type class """ try: return issubclass(obj, t) except TypeError: return False
40,829
def test_cipher_execution_zero_hash_requires_empty_txs( executor_contract: Any, config_contract: Any, mock_batcher_contract: Any, chain: Chain, config_change_heads_up_blocks: int, owner: Account, keypers: List[Account], ) -> None: """test that cipher execution works for a batch, which on...
40,830
def get_all_clusters(cluster_type, client_id): """Get a list of (cluster_name, cluster_config) for the available kafka clusters in the ecosystem at Yelp. :param cluster_type: kafka cluster type (ex.'scribe' or 'standard'). :type cluster_type: string :param client_id: name of the client maki...
40,831
def plot(x, y, show=True, **kwargs): """ Create a 2D scatter plot. :param x: A numpy array describing the X datapoints. Should have the same number of rows as y. :param y: A numpy array describing the Y datapoints. Should have the same number of rows as x. :param color: The color to use. :param tag...
40,832
def CreateImagesForWeb(case_name, testFailed, baseimg, testimg, diffimg): """ Given test image set create corresponding thumbnails for web consumption """ thumbsize = (100,100) # full size baseline baseimg.save(out_path("html","b_%s.png"%case_name)) # thumb size baseline oldthumb = ...
40,833
def get_transform_ids(workprogress_id, request_id=None, workload_id=None, transform_id=None, session=None): """ Get transform ids or raise a NoObject exception. :param workprogress_id: Workprogress id. :param session: The database session in use. :raises NoObject: If no transform is founded. ...
40,834
def get_link(hub_name: Optional[str] = None, link_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetLinkResult: """ The link resource format. Latest API Version: 2017-04-26. :param s...
40,835
def rest_scaffold(context, model, app="", api_root="", **kwargs): """ Take name of app and model, return context for template that includes a single variable: the configuration for the rest scaffold. """ # get paging details is_paged = kwargs.pop("is_paged", None) if is_paged is None: ...
40,836
def selection_elites_random(individuals : list, n : int = 4, island=None) -> list: """ Completely random selection. Args: individuals (list): A list of Individuals. n (int): Number to select (default = 4). island (Island): The Island calling the method (default = None). Returns...
40,837
def ekssum(handle, segno): """ Return summary information for a specified segment in a specified EK. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekssum_c.html :param handle: Handle of EK. :type handle: int :param segno: Number of segment to be summarized. :type segno: int :...
40,838
def compare_prices_for_same_urls( source_df: pd.DataFrame, target_df: pd.DataFrame, tagged_fields: TaggedFields ): """For each pair of items that have the same `product_url_field` tagged field, compare `product_price_field` field Returns: A result containing pairs of items with same `product_ur...
40,839
def _check_param(dict_): """ check dictionary elements and reformat if need be :return: dictionary reformat """ # default empty dictionary _ = {} if "google_users" in dict_: _["google_users"] = _check_param_google_users(dict_["google_users"]) else: _logger.exception(f"N...
40,840
def fetch_dataset_insistently(url: str, link_text_prefix: str, user_agent: str) -> dict: """Fetch the approved routes dataset.""" proxies = get_proxies_geonode() + get_proxies() print(f'{len(proxies)} proxies found.') for i, proxy in enumerate(proxies): print(f'Fetching dataset, try with proxy [...
40,841
def _dense_to_one_hot(labels_dense): """Convert class labels from scalars to one-hot vectors.""" num_classes = len(set(labels_dense)) num_labels = labels_dense.shape[0] labels_to_numbers = {label: i for i, label in enumerate(list(set(labels_dense)))} labels_as_numbers = numpy.asarray([labels_to_numb...
40,842
def test_sky_device(obs_sky: dict[str, Any]) -> None: """Test handling of a sky device.""" device = SkyDevice(serial_number=SKY_SERIAL_NUMBER, data=obs_sky) assert device.model == "Sky" assert device.serial_number == SKY_SERIAL_NUMBER assert device.hub_sn == HUB_SERIAL_NUMBER assert device.batt...
40,843
def message_display(game_display, text, position, text_size, color=(0, 0, 0)) -> None: """ Display text on pygame window. :param game_display: Which canvas text will be rendered upon :param text: string text :param position: coordinates on canvas where text will be displayed :param text_size: .....
40,844
def clean_test(): """clean test artifacts""" clean_env() shell('rm', '-rf', '.coverage', 'coverage.xml', 'testresults.xml', 'htmlcov', 'pylint.out')
40,845
def trainer(request): """ Generate a class instance with minimal configurations """ params = request.param model = DummyNet(3) with tempfile.TemporaryDirectory(prefix="output") as path: params["root"] = path c = Trainer(model=model, **params) yield c
40,846
def swish(x): """Swish activation function. For more info: https://arxiv.org/abs/1710.05941""" return tf.multiply(x, tf.nn.sigmoid(x))
40,847
def fatorial(n=1): """ -> Calcúla o fatorial de um número e o retorna :param n: número """ f = 1 for i in range(1, n + 1): f *= i return f
40,848
def retrieve_context_nw_topology_service_name_name_by_id(value_name): # noqa: E501 """Retrieve name by ID Retrieve operation of resource: name # noqa: E501 :param value_name: ID of value_name :type value_name: str :rtype: NameAndValue """ return 'do some magic!'
40,849
def to_xml(csv_df, file_name): """ Creates XML with the json object received :param csv_df: dataframe containing CSV data :param file_name: XML file to be created :return: Null """ try: csv_df.to_xml(file_name) logging.info('XML file has been generated : Filename - {}'.format...
40,850
def print_sklearn_grid_scores(dataset_name, algorithm_name, param_grid, grid_scores): """ This function does a prettier print of a grid of parameters and scores, used in Scikit-Learn's GridSearchCV. Only works for 1 or 2 parameters. Parameters ---------- dataset_name : string The name of th...
40,851
def conv1x1(in_planes, out_planes, wib, stride=1): """1x1 convolution""" # resnet_wib = False resnet_wib = True resnet_alpha = 1E-3 if not wib: return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) else: return WibConv2d(alpha=resnet_alpha, ...
40,852
def simplify_weights(path, target=None, fast=True, deformer=None, start=None, end=None, steps=1): """ Simplify weighting on the mesh so that each vertice may only have a single influence. :param path: The path to the mesh to simplify the weights on :param target: The target mesh to compare weights agai...
40,853
def get_rules(fault_block, zone): """Get rules for fault block and zone names. In this model the rules depend only on the zone; they do NOT vary from fault block to fault block for a given zone. Args: fault_block (str) Name of fault block. zone (str) Zone name. ...
40,854
def conv_cond_concat(x, y): """Concatenate conditioning vector on feature map axis.""" x_shapes = tf.shape(x) y_shapes = tf.shape(y) return concat([ x, y*tf.ones([x_shapes[0], x_shapes[1], x_shapes[2], y_shapes[3]])], 3)
40,855
def get_clusters(cloud_filtered): """ Get clusters from the cloud. Parameters: ----------- cloud: pcl.PointCloud() Returns: ----------- clusters: pcl.PointCloud() array N """ clusters = [] tree = cloud_filtered.make_kdtree() ec = cloud_filtered.make_EuclideanCl...
40,856
def errorResult(request, response, error, errorMsg, httpStatus = 500, result = None, controller = None): """ set and return the error result @param controller: pylon controller handling the request, where cal context is injected and later retrieved by trackable """ response.status_int = httpStatus ...
40,857
def parse_main(text: str = "") -> Dict: """ A loop for processing each parsing recipe. Returns a dict of parsed values. """ if text == "": logging.warning("Empty string provided for parsing") parsed_data = {} for recipe in parser_recipe: field = recipe["field"] parsed_d...
40,858
def main(): """ Returns the answer. """ return 42
40,859
def sub_proc_launch(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE): """Launch a subprocess and return the Popen process object. This is non blocking. This is useful for long running processes. """ proc = subprocess.Popen(cmd.split(), stdout=stdout, stderr=stderr) return proc
40,860
def collect_accuracy(path): """ Collects accuracy values in log file. """ r1 = None r5 = None mAP = None r1_content = 'Rank-1 ' r5_content = 'Rank-5 ' map_content = 'mAP:' with open(path) as input_stream: for line in input_stream: candidate = line.strip() ...
40,861
def recursively_get_annotations(ty: Type) -> Mapping[str, Type]: """Given a type, recursively gather annotations for its subclasses as well. We only gather annotations if its subclasses are themselves subclasses of Deserializable, and not Deserializable itself. This is bad evil code that uses internal ...
40,862
def sector_model(): """SectorModel requiring precipitation and cost, providing water """ model = EmptySectorModel('water_supply') model.add_input( Spec.from_dict({ 'name': 'precipitation', 'dims': ['LSOA'], 'coords': {'LSOA': [1, 2, 3]}, 'dtype': '...
40,863
def set_default_order(kwargs): """ Set order parameter in kwargs for scikit-image functions. Default order is 1, which performs a linear interpolation of pixel values when images are rotated, resized and sheared. This is fine for images but causes unwanted pixel values in masks. This function set t...
40,864
def maybe_flip_x_across_antimeridian(x: float) -> float: """Flips a longitude across the antimeridian if needed.""" if x > 90: return (-180 * 2) + x else: return x
40,865
def contour_check(check_points, random_walk): """check_points have dim (n, ndim) random_walk has 3 elements. [0] is boundary unit vectors (can be in any space), [1] is boundary ls (relative to origin) [2] is origin returns: indexer of [True,..... etc.] of which points are in or not ...
40,866
def _get_erroneous_call(report_text: str) -> str: """.""" erroneous_line = [ line for line in report_text.splitlines() if line.startswith('> ') and RAISES_OUTPUT_SIGNAL_IN_CONTEXT in line ][0] erroneous_assertion = erroneous_line.lstrip('> ') erroneous_assertion = string_remove_from_start(er...
40,867
def write_output(features, forecast_hours, poly, line, point): """ writes output to OUTDATA dict depending on query type :param features: output from clipping function :param forecast_hours: list of all queried forecast hours :param poly: boolean to identify a polygon query :param line: boolean...
40,868
def index(): """ Index set as main route """ return render_template('index.html', title='Home')
40,869
def plus_one(digits): """ Given a non-empty array of digits representing a non-negative integer, plus one to the integer. :param digits: list of digits of a non-negative integer, :type digits: list[int] :return: digits of operated integer :rtype: list[int] """ result = [] carry ...
40,870
def run_experiment(input_frame, n_samples=1, temperature=1, npartitions=1): """ Runs experiment given inputs. Takes `n_samples` samples from the VAE Returns a list of size `n_samples` of results for each input """ encoder_data = a.get_encoder() decoder_data = a.get_decoder() vae = a.g...
40,871
def to_angle(s, sexagesimal_unit=u.deg): """Construct an `Angle` with default units. This creates an :class:`~astropy.coordinates.Angle` with the following default units: - A number is in radians. - A decimal string ('123.4') is in degrees. - A sexagesimal string ('12:34:56.7') or tuple ...
40,872
def simpleBlocking(rec_dict, blk_attr_list): """Build the blocking index data structure (dictionary) to store blocking key values (BKV) as keys and the corresponding list of record identifiers. A blocking is implemented that simply concatenates attribute values. Parameter Description: r...
40,873
def main(): """ FYI: This takes ~10-15 seconds to run on my laptop. """ download_data() graph = read_graph() print('graph has %d nodes and %d edges' % (graph.order(), graph.number_of_edges())) subgraph = get_subgraph(graph, 2) print('subgraph has %d nodes and %d edges' % ...
40,874
def get_marker_obj(plugin, context, resource, limit, marker): """Retrieve a resource marker object. This function is used to invoke plugin._get_<resource>(context, marker) and is used for pagination. :param plugin: The plugin processing the request. :param context: The request context. :param ...
40,875
def is_dict_like(obj: Dict[str, List[Union[float, numpy.float64]]]): """ usage.modin: 2 """ ...
40,876
def run(routing, endpoints, discovery, rulemgr, ip_owner, rules_owner): """Manage ring rules based on discovery info. :param routing: The map between logical endpoint name and internal container port that is used for this endpoint. :param endpoints: The set of endpoints to monitor. ...
40,877
def test_check_max_parents(): """Test checking maximum number of parent nodes for variables.""" variable_names = ['a', 'b', 'c'] result = rdu.check_max_parents(variable_names, None) expected = {'a': None, 'b': None, 'c': None} for v in variable_names: assert result[v] == expected[v] ...
40,878
def import_project_module(project_name, project_dir): """Import project module, from the system of from the project directory""" if "--installed" in sys.argv: try: module = importlib.import_module(project_name) except Exception: logger.error("Cannot run tests on installed...
40,879
def generative(max_value: int = FIBONACCI_MAX) -> int: """ This is the fully generative method for the Fibonacci sequence. The full sequence list is generated, the even ones are sought out, and summed --> benchmark: 8588 ns/run :param max_value: The ceiling value of Fibonacci numbers to be added ...
40,880
def add_vendor_cves(ms_directory, neo4jpasswd, logger=structlog.get_logger()): """ Adds CVEs to database. :param ms_directory: directory where the microsoft files are downloaded :param neo4jpasswd: password to neo4j database :param logger: logger for the method :return: output message """ ...
40,881
def enc_net(num_classes, pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = Net(num_classes, **kwargs) # if pretrained: # model.load_state_dict(model_zoo.load_url(model_urls['resne...
40,882
def get_bytes(data): """ Helper method to get the no. of bytes in the hex""" data = str(data) return int(len(sanatize_hex(data)) / 2)
40,883
def _group_by(input_list, key_fn): """Group a list according to a key function (with a hashable range).""" result = collections.defaultdict(list) for x in input_list: result[key_fn(x)].append(x) return result
40,884
def set_parameters_in_cookie(response: Response) -> Response: """Set request parameters in the cookie, to use as future defaults.""" if response.status_code == HTTPStatus.OK: data = { param: request.args[param] for param in PARAMS_TO_PERSIST if param in request.args ...
40,885
def test_wild_dlq_error(mock_handler: MagicMock, mock_rsmq: MagicMock, caplog: LogCaptureFixture) -> None: """test error level logs when message fails to successfully reach DLQ""" mock_handler.return_value = False, False mock_rsmq.return_value.sendMessage.return_value.execute = lambda: False m = {"uuid...
40,886
def teleport_reduce(g: BaseGraph[VT,ET], quiet:bool=True, stats:Optional[Stats]=None) -> BaseGraph[VT,ET]: """This simplification procedure runs :func:`full_reduce` in a way that does not change the graph structure of the resulting diagram. The only thing that is different in the output graph are the locat...
40,887
def map_coords_to_scaled(coords, orig_size, new_size): """ maps coordinate indices relative to the original 3-D image to indices corresponding to the re-scaled 3-D image, given the coordinate indices and the shapes of the original and "new" scaled images. Returns integer indices of the voxel that con...
40,888
def _PromptToUpdate(path_update, completion_update): """Prompt the user to update path or command completion if unspecified. Args: path_update: bool, Value of the --update-path arg. completion_update: bool, Value of the --command-completion arg. Returns: (path_update, completion_update) (bool, bool)...
40,889
def answer_cells_of_dir(submission_dir): """ get the contents of all solution cells of all ipynb files in a directory """ cells = {} files = os.listdir(submission_dir) for filename in files: if not filename.endswith(".ipynb"): continue noext = filename[:-6] ...
40,890
def _get_static_covariate_df(trajectories): """The (static) covariate matrix.""" raw_v_df = ( trajectories.static_covariates.reset_coords(drop=True).transpose( 'location', 'static_covariate').to_pandas()) # This can then be used with, e.g. patsy. # expanded_v_df = patsy(raw_v_df, ...patsy detail...
40,891
def answer_cells_of_nb(a_ipynb): """ get the contents of all answer cells (having grade_id) in an a_ipynb file """ cells = {} with open(a_ipynb) as ipynb_fp: content = json.load(ipynb_fp) for cell in content["cells"]: meta = cell["metadata"] nbg = meta.get...
40,892
def test_the_is_invalid_method_of_user_repository_missing_password(app): """ GIVEN the UserRepository class WHEN the method is_invalid(user) is called with a invalid user THEN check return false """ from app.model import UserRepository, User user_repository = UserRepository() user_repository.session = ...
40,893
def _transpose_augment(img_arr): """ 对称扩增 """ img = Image.fromarray(img_arr, "L") return [np.asarray(img.transpose(Image.FLIP_LEFT_RIGHT))]
40,894
def test_list_any_uri_length_4_nistxml_sv_iv_list_any_uri_length_5_4(mode, save_output, output_format): """ Type list/anyURI is restricted by facet length with value 10. """ assert_bindings( schema="nistData/list/anyURI/Schema+Instance/NISTSchema-SV-IV-list-anyURI-length-5.xsd", instance...
40,895
def test_property_vector(): """Test that a vector gets pulled out""" sys = System(properties=[Property(name="foo", units="bar", vectors=[[Scalar(value="spam"), Scalar(value="eggs")]])]) user_data = _to_user_defined(sys) assert user_data["foo_bar"] == ["spam", "eggs"]
40,896
def main(): """ Experiment main entry point (adaption from HuggingFace Transformers) """ if len(sys.argv) == 1: config_path = "./bert_classifier_config.json" else: config_path = sys.argv[1] print("Loading configuration: " + config_path) # ARGUMENTS wit...
40,897
def handle_gpu_compatibility(): """Handling of GPU issues for cuDNN initialize error and memory issues.""" try: gpus = tf.config.experimental.list_physical_devices("GPU") for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) except Exception as e: print(e)
40,898
def open_sciobj_file_by_path(abs_path, write=False): """Open a SciObj file for read or write. If opened for write, create any missing directories. For a SciObj stored in the default SciObj store, the path includes the PID hash based directory levels. This is the only method in GMN that opens SciObj fil...
40,899