content
stringlengths
22
815k
id
int64
0
4.91M
def send_email(orm, user, reset_url, mail_type): """ mail_type: register ro resetpw """ secret = user.secret if mail_type=="register" else user.resetpw logger.debug(secret) auth = OtpAuth(secret) uri = auth.to_uri('totp', user.email, 'userga') qrurl = "?".join(['https://chart.googleapis....
5,307,500
def collect_args(): """ Sets up and collects necessary arguments using ArgumentParser. Returns ------- args : argparse.Namespace Namespace containing the arguments and their values specified by the user. """ parser = ArgumentParser('python intensity.py') parser.add_arg...
5,307,501
def get_losses(model, dataset, criterion, device): """ calculates loss for each item """ model.eval() loader = DataLoader(dataset, batch_size=1) losses = [] for i,data in enumerate(loader): data = Variable(data).to(device) # ===================forward===================== ...
5,307,502
def get_dnac_jwt_token(dnac_auth): """ Create the authorization token required to access DNA C Call to Cisco DNA Center - /api/system/v1/auth/login :param dnac_auth - Cisco DNA Center Basic Auth string :return: Cisco DNA Center JWT token """ url = DNAC_URL + '/dna/system/api/v1/auth/t...
5,307,503
def test_get_routes(): """ Test to return the contents of the interface routes script. """ with patch.object(os.path, "join", return_value="A"), patch.object( suse_ip, "_read_file", return_value=["A"] ): assert suse_ip.get_routes("iface") == ["A"]
5,307,504
def managestring(string): """Reads the initial ecuation string provided by the user and isolates the variables for correct value asignations Args: string (string): Formmula entered by the user """ for x in string: lista.append(x) if x.isalpha() a...
5,307,505
def get_reconstruction_origin(r): """Compute the origin of a reconstruction.""" s = r.scale pose = types.Pose([r.rx, r.ry, r.rz], [r.tx / s, r.ty / s, r.tz / s]) return pose.get_origin()
5,307,506
def train_loop(net, optimizer, criterion, train_data, valid_data, n_epochs, batch_size, task='mimic-mortality', save_dir=None, verbose=False, scheduler=None, eval_every=10000, save_every=40, writer=None): """ net: nn.Module we are training optimizer: pytorch optimizer object criterion: ...
5,307,507
def is_empty(table: Map[Key, Value]) -> bool: """Is the map empty? Args: table: The input map. Returns: True if the map is empty. """ return table.is_empty()
5,307,508
def to_latex(circuit: Program, settings: Optional[DiagramSettings] = None) -> str: """ Translates a given pyQuil Program to a TikZ picture in a LaTeX document. Here are some high points of the generation procedure (see ``pyquil/latex/_diagram.py``): - The most basic building block are the TikZ operato...
5,307,509
def autodetect_filename(fn): """Guess based on filename. """ for k in EXT_MAP: if fn.endswith(k): return EXT_MAP[k] return None
5,307,510
def get_password_hash(password): """ Se calcula el hash de un string Parameters ---------- password : str Texto al que se le calculara el hash. Returns ------- out : str String con el hash correspondiente al texto. """ return pwd_context.hash(password)
5,307,511
def render_meta_yaml(text): """Render the meta.yaml with Jinja2 variables. Parameters ---------- text : str The raw text in conda-forge feedstock meta.yaml file Returns ------- str The text of the meta.yaml with Jinja2 variables replaced. """ env = jinja2.Environm...
5,307,512
def transform_function(fromsys, tosys, copyobstime=True, priority=1): """ A function decorator for defining transformations between coordinate systems. .. note:: If decorating a static method of a class, ``@staticmethod`` should be added *above* this decorator. Parameters ----...
5,307,513
def unique(values: numpy.ndarray): """ usage.seaborn: 3 """ ...
5,307,514
def remove_empty_boxes(boxes, labels): """Removes bounding boxes of W or H equal to 0 and its labels Args: boxes (ndarray): NP Array with bounding boxes as lines * BBOX[x1, y1, x2, y2] labels (labels): Corresponding labels with boxes Returns: ndarray: ...
5,307,515
def add_hr_zones(df): """Add columns with the time spent at each zone.""" df_zones = create_df_with_zones(df['file']) out = pd.concat([df, df_zones], axis=1) out.loc[:, 'z1/z2':'z5'] = round(out.loc[:, 'z1/z2':'z5']/60, 1) return out
5,307,516
def check_data(ctx, datasets): """ checks the data of the current experiment folder; note: must follow before data aggregation :return True if all OK; False otherwise """ print('### checking data ###') experiment = 'r_' + ctx['experiment_folder'] run = create_or_get_dict(datasets, experiment...
5,307,517
def test_list_nmtokens_min_length_3_nistxml_sv_iv_list_nmtokens_min_length_4_3(mode, save_output, output_format): """ Type list/NMTOKENS is restricted by facet minLength with value 8. """ assert_bindings( schema="nistData/list/NMTOKENS/Schema+Instance/NISTSchema-SV-IV-list-NMTOKENS-minLength-4.x...
5,307,518
def request(message, track=0): """ Request a sysex dump from the Digitone :param message: type of message to be required. Currently supports: patch :param track: Which track or pattern to request. Currently defaults to 0 :return: None """ try: outport = mido.open...
5,307,519
def _ParseJobIds(job_ids, sparse_log, error_log): """Parse job ids.""" if ':' in job_ids: job_ids = job_ids.split(':') assert len(job_ids) == 3 job_ids = [int(x) for x in job_ids] job_ids = np.arange(job_ids[0], job_ids[1], job_ids[2]) job_ids = [str(x) for x in job_ids] elif ',' in job_ids: ...
5,307,520
def model_fn(batch, model, criterion, device): """Forward a batch through the model.""" mels, labels = batch mels = mels.to(device) labels = labels.to(device) outs = model(mels) loss = criterion(outs, labels) # Get the speaker id with highest probability. preds = outs.argmax(1) #...
5,307,521
def tree_is_to_be_used(tree): """ discard the input tree if: 1) the root is FRAG 2) it contains empty category such as *T* 3) a node with more than two children """ def rec(node): if isinstance(node, Tree): if len(node.children) > 2: # logger.warn(f'more t...
5,307,522
def score_gene_sets(ds, gs, method='mean_z_score', permutations=None, random_state=0, smooth_p_values=True, progress=False): """Score gene sets. Note that datasets and gene sets must be aligned prior to invoking this method. No check is done. mean_z_score: Compute the z-score for each ...
5,307,523
def test_lightcurve_copy(): """Test ``LightCurve.copy()``.""" time = np.array([1, 2, 3, 4]) flux = np.array([1, 2, 3, 4]) error = np.array([0.1, 0.2, 0.3, 0.4]) lc = LightCurve(time=time, flux=flux, flux_err=error) nlc = lc.copy() assert_array_equal(lc.time, nlc.time) assert_array_equal...
5,307,524
def read_image_stack(fn, *args, **kwargs): """Read a 3D volume of images in image or .h5 format into a numpy.ndarray. The format is automatically detected from the (first) filename. A 'crop' keyword argument is supported, as a list of [xmax, xmin, ymax, ymin, zmax, zmin]. Use 'None' for no crop in th...
5,307,525
def iplot(figure_or_data, **plot_options): """Create a unique url for this plot in Plotly and open in IPython. plot_options keyword arguments: filename (string) -- the name that will be associated with this figure sharing ('public' | 'private' | 'secret') -- Toggle who can view this graph - 'pu...
5,307,526
def _fread3_many(fobj, n): """Read 3-byte ints from an open binary file object.""" b1, b2, b3 = np.fromfile(fobj, ">u1", 3 * n).reshape(-1, 3).astype(np.int64).T return (b1 << 16) + (b2 << 8) + b3
5,307,527
def _extract_rel_addr(op_bytes, mnemonic_type): """ Extract the relative address at the level from the binary operation (borrowed from Koo's and Polychronakis' implementation). """ addr = 0x0 mask = 0x0 # Aside from mnemonic bytes, all remaining bytes wou...
5,307,528
def is_transformer(actor): """ Checks whether the actor is a transformer. :param actor: the actor to check :type actor: Actor :return: true if a transformer actor """ return isinstance(actor, OutputProducer) and isinstance(actor, InputConsumer)
5,307,529
def get_base_dir(): """Attempts to locate ariadne's install directory.""" try: d=os.environ['ARIADNE_BASE'] if d[len(d)-1] != '/': d+='/' return d except: # This may be significantly better than using the environment variable. genpath=os.path.realpath(sys....
5,307,530
def generate_directories(args, other_vars, env_vars): """ """ dir_list = [ "nginx/conf.d", "nginx/dhparams", "nginx/https", "nginx/nginx_conf.d", "nginx/scripts", ] # Create required output directories if they're missing for dir in dir_list: ...
5,307,531
def ChoiceToEnum(choice, enum_type, item_type='choice', valid_choices=None): """Converts the typed choice into an apitools Enum value.""" if choice is None: return None name = ChoiceToEnumName(choice) valid_choices = ( valid_choices or [arg_utils.EnumNameToChoice(n) for n in enum_type.names()]) ...
5,307,532
def get_arguments(): """ Parse input arguments """ parser = argparse.ArgumentParser(description="Code for evaluation") parser.add_argument('--best_iter', type=int, default=70000, help='iteration with best mIoU') parser.add_argument('--normalize', type=bool, default=False...
5,307,533
def resubmit_alert(uuid, *args, **kwargs): """Resubmit an alert for analysis. This means the alert will be re-analyzed as-if it was new. :param str uuid: The uuid of the alert to be resubmitted. :return: A result dictionary (has 'result' key). :rtype: dict """ return _execute_api_call('analysis...
5,307,534
def get_context(canvas): """Get ``cairo.Context`` used to draw onto the canvas.""" return canvas.renderer._get_context()
5,307,535
def Font(*args, **metadata): """ Returns a trait whose value must be a GUI toolkit-specific font. .. deprecated:: 6.1.0 ``Font`` trait in this package will be removed in the future. It is replaced by ``Font`` trait in TraitsUI package. """ from traitsui.toolkit_traits import FontTrait ...
5,307,536
def determine_instrument(setup_package_path): """MLZ specific way to find the NICOS instrument from the host name.""" try: # Take the second part of the domain name (machine.instrument.frm2 # or new-style machine.instrument.frm2.tum.de) hostname = socket.gethostname() # can't use...
5,307,537
def post_delete_handler(sender, instance, **kwargs): """ Method to map Django post_delete model signals to custom ones. """ notification_deleted.send(sender=sender, notification=instance, kwargs=kwargs)
5,307,538
def test_file_loader(): """ Test the functions in FileLoader """ # init, no error means passed loader_grouped = FileLoader( dir_paths=["/path/grouped_loader/"], name="grouped_loader", grouped=True ) loader_ungrouped = FileLoader( dir_paths=["/path/ungrouped_loader/"], name="u...
5,307,539
def ArclinkRequestSummary_Meta(): """ArclinkRequestSummary_Meta() -> MetaObject""" return _DataModel.ArclinkRequestSummary_Meta()
5,307,540
def convert_datetime_to_string_date(now: datetime = datetime.now()) -> str: """ Converts now to string format yyyy-dd-yy-hh-mm-ss :param now: datetime. Date in datetime format. Default value is datetime.now(). :return: str. """ year = now.year month = add_zeros_in_front_and_convert_to_string...
5,307,541
def _sin(num): """The sin function. Args: num -- A number. Returns: sin(num) """ if var_type(num) == "number": # This only works with 1D arrays # Just implemented for scalar at this point return math.sin(num) raise ValueError('Could...
5,307,542
def test_server_fixture( loop, aiohttp_client, build_frontend, matlab_port_setup, mock_settings_get, ): """A pytest fixture which yields a test server. This test server is used to test various endpoints. After gaining control back, gracefully shuts down the server. This fixture 'in...
5,307,543
def merge_data_from_gen_files_with_format(root_path: str) -> typing.List[str]: """从生成的多个带格式的文件中读取数据,并返回一个List """ file_list = [os.path.join(root_path, file) for file in os.listdir( root_path) if file.startswith('gpt2_gentext_') and file.endswith('.txt')] tmp = [] for file in file_list: ...
5,307,544
def fahrenheit_from(celsius): """Convert Celsius to Fahrenheit degrees.""" try: fahrenheit = float(celsius) * 9 / 5 + 32 fahrenheit = round(fahrenheit, 3) # Round to three decimal places return str(fahrenheit) except ValueError: return "invalid input"
5,307,545
def test_is_open_on_closed_port(): """ Test if the property is_open returns False on a port which is not open. """ with ShdlcTcpPort('localhost', 0, do_open=False) as port: assert type(port.is_open) is bool assert port.is_open is False
5,307,546
def t2(): """- clear team 2's name""" write(team2F, "") rprint(f"{main_colour}Cleared team {t2_colour}2\'s {main_colour}name.")
5,307,547
def evaluate_task( task: TaskDocument, funct_scores: Dict[str, int] = SETTINGS.QCHEM_FUNCTIONAL_QUALITY_SCORES, basis_scores: Dict[str, int] = SETTINGS.QCHEM_BASIS_QUALITY_SCORES, solvent_scores: Dict[str, int] = SETTINGS.QCHEM_SOLVENT_MODEL_QUALITY_SCORES, task_quality_scores: Dict[str, int] = SETT...
5,307,548
async def test_quickmode_one_day_home_hvac_auto(hass): """Test mode <> hvac.""" SystemManagerMock.init_defaults() zone = SystemManagerMock.data.get("get_zones")[0] await _test_mode_hvac( hass, QuickModes.ONE_DAY_AT_HOME, ActiveFunction.STANDBY, HVAC_MODE_AUTO, zon...
5,307,549
def send_email_reports(email_setting,summary): """ 根据传入的邮件策略发送邮件 :param email_setting: 邮件策略;string;"1"--代表始终发送 :param summary: 测试结果集;dict;{} :return: response: 统一的结果体;dict;{} """ if '@sina.com' in EMAIL_SEND_USERNAME: smtp_server = 'smtp.sina.com' elif '@163.com' in EMAIL_SEND_U...
5,307,550
def compute_q(a, N): """ Given: an vector a in R^m (except for 0 vector), compute the discrete approximation to the convolution q(u) = (p_0 * p_1 * ...)(u) = int p_0(t) p_1(u-t) ... dt where x_i ~ UNIF[-1,1], i.e. p_i = 1/2 if |x_i|<=1 or 0 o.w. Returns (N,) numpy.array, q = [q_0, ..., q_N-...
5,307,551
def flatten(container: IO[IO[_ValueType]]) -> IO[_ValueType]: """Case for ``IO`` container."""
5,307,552
def memory_fast_assign(X, Y): """ X+Y 不需要占用临时内存,直接输出到 Z """ show_subtitle("memory fast assign") Z = Y.zeros_like() before = id(Z) nd.elemwise_add(X, Y, out=Z) after = id(Z) print("before=\t", before) print("after=\t", after) print("(after == before) =", after == before) p...
5,307,553
def align_face(image, coordinates): """ Face detection from dlib landmark detection :param: facial image local path or image of numpy array :return: faces coordinates list and landmarks """ try: d = dlib.rectangle(coordinates[2], coordinates[0], coordinates[3], coordinates[1]) # Det...
5,307,554
def make_s3_client(credentials): """Make a client for uploading to S3. credentials: an orgtup.AwsCredentials object """ return client( 's3', aws_access_key_id=credentials.access_key_id, aws_secret_access_key=credentials.secret_access_key)
5,307,555
def rdkit(function): """ """ def wrapper(self, *args, **kwargs): """ """ if config['extras']['rdkit']: return function(self, *args, **kwargs) else: warn("The RDKit Python wrappers are not installed.", UserWarning) return wrapper
5,307,556
def review_filters_inline(request, review_id, template_name="manage/reviews/review_filters_inline.html"): """Renders the filter section of the review view. """ review_filters = request.session.get("review-filters", {}) review = lfs_get_object_or_404(Review, pk=review_id) return render_to_string(tem...
5,307,557
def get_text(title='Enter a label', default=None): """Prompt the user to enter text using QT :param title: Name of the prompt :param default: Default text to show in prompt Returns: The text the user typed, or None """ result, isok = QtWidgets.QInputDialog.getText( None, title, ...
5,307,558
def register_errors_from_third_parties(app, third_party_errors=None): """Registers the client-side errors from third parties""" if third_party_errors: for error in third_party_errors: app.register_error_handler(error, handle_400_errors)
5,307,559
def is_edge(): """is_edge. """ try: IoTHubModuleClient.create_from_edge_environment() return True except Exception: return False
5,307,560
def isImgPath(path, silent=False): """ 入力されたパスが画像か判定する [in] path: 画像か判定したいパス [in] silent: cv2.imread失敗時にエラーを表示させない場合はTrue [out] 画像ならTrue """ logger.debug('isImgPath({},{})'.format(path, silent)) if not type(path) is str: return False import imghdr if not os.path.isf...
5,307,561
def get_target_supported_toolchains(target): """ Returns target supported toolchains list """ return TARGET_MAP[target].supported_toolchains if target in TARGET_MAP else None
5,307,562
def big_endian_to_int(value): """ Ethereum RLP Utils: Convert big endian to int :param value: big ending value :return: int value """ return int.from_bytes(value, byteorder="big")
5,307,563
def supply(request, page_name): """ Handle the request for viz_chart widget.""" _ = page_name _ = request all_lounges = Team.objects.order_by('name').all() return { "all_lounges": all_lounges, }
5,307,564
def zipdir(path, zip_handle): """Recursively add directory to zip archive""" for root, _, files in os.walk(path): for file in files: path = os.path.join(root, file) # ignore cache if any(word in path for word in ["__pycache__", ".pyc"]): continue ...
5,307,565
def test_server_sent_events_config(): """Test that SERVER_SENT_EVENTS configuration behaves properly""" class ServerSentEventsConfig(TestingConfig): SERVER_SENT_EVENTS = False app = create_ctfd(config=ServerSentEventsConfig) with app.app_context(): register_user(app) client = l...
5,307,566
def human_time(runtime, decimals=2): """Display runtime in a human friendly format.""" if runtime < 1: return str('mms: ' + str('{:f}'.format(rounder(runtime * 1000, decimals)))) elif runtime < 60: return str('sec: ' + str('{:f}'.format(rounder(runtime, decimals)))) else: return ...
5,307,567
def calc_c_s(p, polyol_data_file): """ Estimates the saturation concentration of CO2 in a polyol solution using interpolated measurements of solubility. Parameters ---------- p : float pressure at which to estimate the saturation concentration [Pa] polyol_data_file : string ...
5,307,568
def _read_files(file_names): """ Reads content from all specified file names Args: file_names: set of file names Returns: list of lines from all files """ all_lines = [] for file_name in file_names: try: with open(file_name) as f: lines = f...
5,307,569
def simple_shift_method(ion, n_samples, max_shift, rates_file, xsec_file="", ECORIC=0, NMIN=3, NMAX=15, LMIN=0, LMAX=7, compute_xsec=False, EWIDTH=0.0001, NBIN=1000, EMIN=0.0, EMAX=2.0): """ Calculate the Dielectronic Radiation cross-sections and rates by means of the simple shift method...
5,307,570
def create_track_log(db, sessionID): """ Instantiate the Track History Collection. :param db: The database object. :param sessionID: Current user's session ID. :return: The Track History Collection object. """ collection_name = 'track_history_' + sessionID track_collection = db[collecti...
5,307,571
def _UploadFile(file_upload_task): """Complete one FileUploadTask (safe to run in parallel).""" storage_client = storage_api.StorageClient() bucket_ref = storage_util.BucketReference.FromBucketUrl( file_upload_task.bucket_url) local_path = file_upload_task.local_path retry.Retryer(max_retrials=3).Retry...
5,307,572
def parse_events(handle, blocksz): """ This function reads an events.txt file as it's written by the source engine, returns a list of DemoInfo instances containing demo name, killstreaks and bookmarks. handle : Open file handle to the events file. Must be readable. blocksz : Block size the handle file should be ...
5,307,573
def sum_allcation_from_shimenreservoir(): """ Real Name: Sum Allcation From ShiMenReservoir Original Eqn: Sum Allocation ShiMenReservoir To HouChiWeir+Sum Allocation ShiMenReservoir To ShiMenAgriChannel Units: m3 Limits: (None, None) Type: component Subs: None """ return...
5,307,574
def scale_by_fromage( step_size: float = 1e-3, min_norm: float = 1e-6, step_size_factor_fn: Optional[Callable[[jnp.ndarray], jnp.ndarray]] = None, ) -> GradientTransformation: """Scale updates by Frobenius norm of parameters and grads. References: [Bernstein et. al 2020](https://arxiv.org/abs/2...
5,307,575
def test_error_cb(): """ Test the error callback. """ global seen_all_brokers_down # Configure an invalid broker and make sure the ALL_BROKERS_DOWN # error is seen in the error callback. p = Producer({'bootstrap.servers': '127.0.0.1:1', 'socket.timeout.ms':10, 'error_cb': error_c...
5,307,576
def create_app(configobj=ProdConfig): """ Create and configure Flask Application """ app = Flask(__name__) app.config.from_object(configobj) configure_blueprints(app) configure_extensions(app) configure_callbacks(app) configure_filters(app) configure_error_handlers(app) return app
5,307,577
def istowest(bb1, bb2, north_vector=[0,1,0]): """ Returns True if bb1 is to the west of bb2. For obj1 to be to west of obj2: - obj1 is close to obj2 - The side faces for obj1 and obj2 overlap - obj1 is west obj2 """ #Currently a North Vector of 0,1,0 (North is in the positive Y...
5,307,578
def _generic_dimensions(array, unit, className="Dimension", **kwargs): """Return a dimension object based on the array coordinates.""" # labeled if str(array.dtype)[:2] in [">U", "<U"]: if unit != "": warnings.warn("Ignoring unit argument for LabeledDimension.") return LabeledDim...
5,307,579
def InvertDepthNorm( depth, maxDepth=1000.0, minDepth=10, transform_type='inverse' ): """Renormalizes predictions back to targets space""" if transform_type == 'inverse': return maxDepth / depth elif transform_type == 'scaled': return depth * minDepth elif transform_type == 'log': ...
5,307,580
def rename_columns(df: pd.DataFrame, columns: Dict[str, str]) -> pd.DataFrame: """ Rename columns of given dataframe `df`. """ return df.rename(columns=columns)
5,307,581
def solid_material(color): """Create a material.""" material = rt.StandardMaterial() material.Ambient = color material.Diffuse = color material.Specular = rt.Color(255, 255, 255) material.Shininess = 50.0 material.ShinyStrength = 70.0 material.SpecularLevel = 70.0 return material
5,307,582
def moveTo(x=None, y=None, duration=0.0, tween=linear, pause=None, _pause=True): """Moves the mouse cursor to a point on the screen. The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the bounda...
5,307,583
def patch_dependencies(mocker, monkeypatch): """ This function is called before each test. """ monkeypatch.setattr(SpotifyClient, "init", new_initialize) monkeypatch.setattr(subprocess, "Popen", fake_create_subprocess_exec) monkeypatch.setattr(ffmpeg, "get_ffmpeg_version", lambda *_: (4.4, 2022...
5,307,584
def only_en(x): """ Only keeps English alphabets in a string or a pandas.DataFrame. Args: x: The content to be parsed. Either a string or a pandas.DataFrame. Returns: A new string or a pandas.DataFrame only includes English alphabets. | """ def func(_s): return re....
5,307,585
def pad_array(var, varlen, arr) : #--------------------------------------------------------------------------------------------------- """ Pad out array arr with fill values if it contains fewer elements than are required by the host variable. """ if '_FillValue' in var.ncattrs() : fv = var._FillVa...
5,307,586
def test_reformat_params_reduction(monkeypatch): """reformat_params should remove "%" and convert to float""" yr = datetime.today().year def mock_expr_str_to_datetime(string): return datetime(yr, 12, 31) monkeypatch.setattr(vp, "expiration_str_to_datetime", mock_expr_str_to_datetime) inpu...
5,307,587
def get_cached_connection_stats(return_as='string', memcached_ip='127.0.0.1', memcached_port='11211'): """Obtain connection status string in memcached and return as requested object. Check if memcached has cached connection status for the StorageShares, which would have been uploaded by UGR/Dynafed's perio...
5,307,588
def test_halted(chain, web3, kyc_presale, customer, customer_id, private_key, preico_starts_at, team_multisig, pricing_info, signer_address): """We cannot buy after a halt.""" # Check KYC crowdsale is good to go time_travel(chain, kyc_presale.functions.startsAt().call() + 1) # Check the setup looks go...
5,307,589
def remove_orderlines(stock_change: StockChange): """ Removes orderLines from state arrived to whichever state relevant. :param stock_change: The StockChange to be checked for orderLines :return: """ acted_upon = [StockChangeSet.SOURCE_CASHREGISTER, StockChangeSet.SOURCE_INTERNALISE, StockChange...
5,307,590
def test_parallel_build(qibuild_action): """ Test Parallel Build """ qibuild_action.create_project("a") qibuild_action.create_project("b") qibuild_action.create_project("c", build_depends=["a", "b"]) qibuild_action("configure", "c") qibuild_action("make", "c", "--num-workers=2")
5,307,591
def gen_noise_Gaussian(num_instance, n_dim=2): """generate n-dim Gaussian random noise""" return torch.randn(num_instance, n_dim)
5,307,592
def detect_api_mismatch(ref_api, other_api, *, ignore=()): """Returns the set of items in ref_api not in other_api, except for a defined list of items to be ignored in this check. By default this skips private attributes beginning with '_' but includes all magic methods, i.e. those starting and ending ...
5,307,593
def object_storage_name(instance, filename): """ Create a name spaced file path from the File obejct's checksum property. This path will be used to store the content copy :param instance: File (content File model) :param filename: str :return: str """ return generate_object_storage_name...
5,307,594
def unbatch_padded(x, lens_x): """Make a list of individual batch elements with padded (masked) entries omitted""" x_split = x.chunk(x.shape[0], dim=0) x_clean = [x_split[i].reshape(-1, 2)[:lens_x[i]].detach().cpu().numpy() for i in range(len(lens_x))] return x_clean
5,307,595
def check_pkgs(self, pkgs): """Check rpm packages.""" for pkg in pkgs: ret = 1 cmd = f"rpm -q {pkg}" try: cmd_res = execute_command(self, cmd) ret = cmd_res[1] except MotrError: pass if ret == 0: sys.stdout.write(f"rpm fou...
5,307,596
def test_timespan_args_begin_iso_week_and_thru_str_none(): """Tests timespan arguments: begin iso week, thru_str=None. """ start, end = timespan(begin_str=REF_BEGIN_ISO, thru_str=None) begin = datetime.fromisocalendar(2020, 10, 1).astimezone() end_now = datetime.now(tz.tzlocal()) assert isinsta...
5,307,597
def strip_non_null_and_list_from_type(graphql_type: GraphQLOutputType) -> Any: """Return the GraphQL type stripped of its GraphQLNonNull and GraphQLList annotations.""" while isinstance(graphql_type, (GraphQLNonNull, GraphQLList)): graphql_type = graphql_type.of_type return graphql_type
5,307,598
def _make_p_M_x(p_M_min=5., p_M_max=8.5, M_step=0.1, n_M=None): """ Makes the X values (i.e., the magnitudes) for a p_M distribution. """ if n_M is not None: p_M_x = np.linspace(p_M_min, p_M_max, num=n_M) else: if M_step is None: M_step = 0.1 # in case it's passed a...
5,307,599