content
stringlengths
22
815k
id
int64
0
4.91M
def load_indice_file(file, net_config): """Take the idlfile, data mean and net configuration and create a generator that outputs a jittered version of a random image from the annolist that is mean corrected.""" indice_list = [] with open(file, 'r') as f: while True: line = f.read...
5,342,500
def test_valid_args(voltage, expected_byte): """ Test if the return value of voltage_to_byte() is correct when passing a valid voltage. """ byte = voltage_to_byte(voltage) assert type(byte) is int assert byte == expected_byte
5,342,501
def context_list_entities(context): """ Returns list of entities to be displayed in list view """ # log.info(context['List_rows']) if 'List_rows' in context: return context['List_rows']['field_value'] elif 'entities' in context: return context['entities'] log.warning("No enti...
5,342,502
def run(arg): """Entry point""" error_map = {} validate_path(arg, None, error_map) if len(error_map) > 0: error_count = 0 for file, errors in error_map.items(): print(f"Error in {file}:") for error in errors: print(f" {error}") e...
5,342,503
def test_retrieve_events_where_is_admin_only_includes_events_where_is_admin( user, member_of_organizer, organizer_type, membership_type, expected_events_amount ): """When retrieving events where is admin, only events where is admin should be returned""" hs = GroupFactory(type=GroupType.BOARD, name=AdminGro...
5,342,504
def _bitcode_symbols_partial_impl( *, actions, binary_artifact, bitcode_symbol_maps, dependency_targets, label_name, output_discriminator, package_bitcode, platform_prerequisites): """Implementation for the bitcode symbols processing partial.""...
5,342,505
def _str_trim_left(x): """ Remove leading whitespace. """ return x.str.replace(r"^\s*", "")
5,342,506
def fabric_host(docker_client): """Keep this session scoped to save time""" container = docker_client.containers.run( "efagerberg/pytest-fabric-sshd:latest", name="pytest-fabric-test-container", ports={'22': '2222'}, detach=True, ) env.disable_known_hosts = True env.p...
5,342,507
def zipcompress(items_list, flags_list): """ SeeAlso: vt.zipcompress """ return [compress(list_, flags) for list_, flags in zip(items_list, flags_list)]
5,342,508
def test_config_file_fails_missing_value(monkeypatch, presence, config): """Check if test fails with missing value in database configuration.""" def mock_file_config(self): return {'database': {}} monkeypatch.setattr(presence.builder, "fetch_file_config", mock_file_config) status, msg = presen...
5,342,509
def construct_run_config(iterations_per_loop): """Construct the run config.""" # Parse hparams hparams = ssd_model.default_hparams() hparams.parse(FLAGS.hparams) return dict( hparams.values(), num_shards=FLAGS.num_shards, num_examples_per_epoch=FLAGS.num_examples_per_epoch, resnet_ch...
5,342,510
def bezier_curve(points, nTimes=1000): """ Given a set of control points, return the bezier curve defined by the control points. Control points should be a list of lists, or list of tuples such as [ [1,1], [2,3], [4,5], ..[Xn, Yn] ] nTimes is ...
5,342,511
def _compact_temporaries(exprs): """ Drop temporaries consisting of isolated symbols. """ # First of all, convert to SSA exprs = makeit_ssa(exprs) # What's gonna be dropped mapper = {e.lhs: e.rhs for e in exprs if e.lhs.is_Symbol and (q_leaf(e.rhs) or e.rhs.is_Function)} ...
5,342,512
def print_formula(elements): """ The input dictionary, atoms and their amount, is processed to produce the chemical formula as a string Parameters ---------- elements : dict The elements that form the metabolite and their corresponding amount Returns ------- formula : str ...
5,342,513
def try_get_code(url): """Returns code of URL if exists in database, else None""" command = """SELECT short FROM urls WHERE full=?;""" result = __execute_command(command, (url,)) if result is None: return None return result[0]
5,342,514
def is_chinese_char(cc): """ Check if the character is Chinese args: cc: char output: boolean """ return unicodedata.category(cc) == 'Lo'
5,342,515
def _get_ec2_on_demand_prices(region_name: str) -> pd.DataFrame: """ Returns a dataframe with columns instance_type, memory_gb, logical_cpu, and price where price is the on-demand price """ # All comments about the pricing API are based on # https://www.sentiatechblog.com/using-the-ec2-price-li...
5,342,516
def resize_image(image, min_dim=None, max_dim=None, padding=False): """ Resizes an image keeping the aspect ratio. min_dim: if provided, resizes the image such that it's smaller dimension == min_dim max_dim: if provided, ensures that the image longest side doesn't exceed this value. ...
5,342,517
def _handle_add_fifo(pool, to_add: transaction.Transaction): """ FIFO is defined by putting the BUY transactions at the end. For split coins, they need to be sold first. """ if to_add.operation == transaction.Operation.SPLIT: pool.insert(0, to_add) else: assert to_add.operation i...
5,342,518
def save_gradients_images(gradients, file_name): """ Exports the original gradients image Args: gradients (np arr): Numpy array of the gradients with shape (3, 224, 224) file_name (str): File name to be exported """ if not os.path.exists('results'): os.makedirs('results')...
5,342,519
def _set_no_data(gdal_ds, no_data): """ Set no data value into gdal dataset Description ----------- Parameters ---------- gdal_ds: gdal.Dataset gdal dataset no_data: list or tuple list of no data values corresponding to each raster band """ for band in range(gdal_d...
5,342,520
def idwt(approx, wavelets, h=np.array([1.0 / np.sqrt(2), -1.0 / np.sqrt(2)]), g=np.array([1.0 / np.sqrt(2), 1.0 / np.sqrt(2)])): """ Simple inverse discrete wavelet transform. for good reference: http://www.mathworks.com/help/wavelet/ref/dwt.html @param approx: approximation of signal at low re...
5,342,521
def app_durations(): """Generate JavaScript for appDurations.""" return 'appDurations = ' + json.dumps(supported_durations)
5,342,522
def generic_cc(mag=10,dmag=8,band='K'): """Returns a generic contrast curve. Keyword arguments: mag -- magnitude of target star in passband dmag -- can currently be either 8 or 4.5 (two example generic cc's being used) band -- passband of observation. """ if dmag==8: return fpp.Con...
5,342,523
def read_routes(*, db: Session = Depends(deps.get_db),data_in: schemas.DictDataCreate,current_user: models.User = Depends(deps.get_current_active_user)) -> Any: """ Retrieve Mock Data. """ db.add(models.Dict_Data(**jsonable_encoder(data_in))) return { "code": 20000, "data": "", ...
5,342,524
def plotTruePreds(tr_gamma, pred_gamma, tr_ele, pred_ele, tr_pi0, pred_pi0, tr_chPi, pred_chPi): """ Plots 4 True X Pred energy plots, one for each kind of particle :parameter tr_gamma: array containing the true values of the energy for photons. :parameter pred_gamma: array containing the predicted ener...
5,342,525
def get_companies_pagination_from_lagou(city_id=0, finance_stage_id=0, industry_id=0, page_no=1): """ 爬取拉勾公司分页数据 :param city_id: 城市 id :param finance_stage_id: 融资阶段 id :param industry_id: 行业 id :param page_no: 页码 :return: 拉勾公司分页数据 :rtype: utils.pagination.Pagination """ url = co...
5,342,526
def test_d3_3_10v01_d3_3_10v01i(mode, save_output, output_format): """ A day is a calendar (or "local time") day in each timezone, including the timezones outside of +12:00 through -11:59 inclusive. """ assert_bindings( schema="ibmData/valid/D3_3_10/d3_3_10v01.xsd", instance="ibmData...
5,342,527
def _onTextReceive(iface, asDict): """Special text auto parsing for received messages""" # We don't throw if the utf8 is invalid in the text message. Instead we just don't populate # the decoded.data.text and we log an error message. This at least allows some delivery to # the app and the app can deal...
5,342,528
def is_quant_contam(contam_model): """Get the flag for quantitative contamination""" # the list of quantitative models quant_models = ['GAUSS', 'FLUXCUBE'] # set the default value isquantcont = True # check whether the contamination is not quantitative if not contam_model.upper() in quant_...
5,342,529
def nms_wrapper(scores, boxes, threshold = 0.7, class_sets = None): """ post-process the results of im_detect :param scores: N * K numpy :param boxes: N * (K * 4) numpy :param class_sets: e.g. CLASSES = ('__background__','person','bike','motorbike','car','bus') :return: a list of K-1 dicts, no b...
5,342,530
def Rbf( gamma: float = 1.0) -> InternalLayer: """Dual activation function for normalized RBF or squared exponential kernel. Dual activation function is `f(x) = sqrt(2)*sin(sqrt(2*gamma) x + pi/4)`. NNGP kernel transformation correspond to (with input dimension `d`) `k = exp(- gamma / d * ||x - x'||^2) = e...
5,342,531
def upgrade_state_dict_with_xlm_weights( state_dict: Dict[str, Any], pretrained_xlm_checkpoint: str, ) -> Dict[str, Any]: """ Load XLM weights into a Transformer encoder or decoder model. Args: state_dict: state dict for either TransformerEncoder or TransformerDecoder pretr...
5,342,532
def test_get_current(client): """Assert that the business info for regular (not xpro) business is correct to spec.""" rv = client.get('/api/v1/businesses/CP0001965/directors') assert 200 == rv.status_code is_valid, errors = validate(rv.json, 'directors', validate_schema=True) if errors: for...
5,342,533
def create_returns_tear_sheet(returns, positions=None, transactions=None, live_start_date=None, cone_std=(1.0, 1.5, 2.0), benchmark_rets=None, bootstrap=False, ...
5,342,534
def vectorize_text(text_col: pd.Series, vec_type: str = 'count', **kwargs): """ Vectorizes pre-processed text. Instantiates the vectorizer and fit_transform it to the data provided. :param text_col: Pandas series, containing preprocessed text. :param vec_type: ...
5,342,535
def creation_LS(X,y,N): """Generates a random learning set of size N from the data in X (containing the input samples) and in y (containing the corresponding output values). Parameters ---------- X: array containing the input samples y: arr...
5,342,536
def init_logger(): """将日志信息输出到控制台 Params: asctime: 打印日志的时间 levelname: 打印日志级别 name: 打印日志名字 message: 打印日志信息 """ logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO )
5,342,537
def print_summary(show="all", blocks=False, cid=True, blobs=True, size=True, typ=False, ch=False, ch_online=True, name=True, title=False, path=False, sanitize=False, start=1, end=0, channel=None, invalid=False, r...
5,342,538
def nice_number_en(number, speech, denominators=range(1, 21)): """ English helper for nice_number This function formats a float to human understandable functions. Like 4.5 becomes "4 and a half" for speech and "4 1/2" for text Args: number (int or float): the float to format speech (bo...
5,342,539
def test_unexpected_response(requests_mock_get, invalid_response): """ Check that the corresponding exception is raised if the response body is unexpected """ _, response = requests_mock_get response.status_code = 200 response.json = lambda: invalid_response with raises(TemperatureSourceExc...
5,342,540
def read_dataframe_by_substring(directory, substring, index_col=None, parse_dates=False, **kwargs): """Return a dataframe for the file containing substring. Parameters ---------- directory : str substring : str identifier for output file, must be unique in directory index_col : str | in...
5,342,541
def load_embeddings(path): """ Load embeddings from file and put into dict. :param path: path to embeddings file :return: a map word->embedding """ logging.info('Loading embeddings...') embeddings = dict() with open(path, 'r') as f: for line in f: line = line.split('...
5,342,542
def helm_preserve(preserve): """Convert secret data to a "--set" string for Helm deployments. Args: preserve (Iterable): Set of secrets we wish to get data from to assign to the Helm Chart. Returns: str: String containing variables to be set with Helm release. """ env_vars = [] ...
5,342,543
def format_component_descriptor(name, version): """ Return a properly formatted component 'descriptor' in the format <name>-<version> """ return '{0}-{1}'.format(name, version)
5,342,544
def dbconn(): """ Initializing db connection """ sqlite_db_file = '/tmp/test_qbo.db' return sqlite3.connect(sqlite_db_file, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
5,342,545
def md5(fname): """ Compute the md5 of a file in chunks. Avoid running out of memory when hashing large files. """ hash_md5 = hashlib.md5() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest()
5,342,546
def _create_comments_revisions(connection, obj_type): """Creates delete revisions for comments. Args: connection: An instance of SQLAlchemy connection. obj_type: String representation of object type. """ result = _get_comments_ids_by_obj_type(connection, obj_type) if result: result = [row[0] for...
5,342,547
def get_r(x, y, x1, y1): """ Get r vector following Xu et al. (2006) Eq. 4.2 x, y = arrays; x1, y1 = single points; or vice-versa """ return ((x-x1)**2 + (y-y1)**2)**0.5
5,342,548
def test_pylintrc_file_toml(testdir): """Verify that pyproject.toml can be used as a pylint rc file.""" rcfile = testdir.makefile( '.toml', pylint=""" [tool.pylint.FORMAT] max-line-length = "3" """ ) testdir.makepyfile('import sys') result = testdir.runpytest(...
5,342,549
def replace_empty_bracket(tokens): """ Remove empty bracket :param tokens: List of tokens :return: Fixed sequence """ merged = "".join(tokens) find = re.search(r"\{\}", merged) while find: merged = re.sub(r"\{\}", "", merged) find = re.search(r"\{\}", merged) return l...
5,342,550
def presentation(): """ This route is the final project and will be test of all previously learned skills. """ return render_template("")
5,342,551
def extra_credit(grades,students,bonus): """ Returns a copy of grades with extra credit assigned The dictionary returned adds a bonus to the grade of every student whose netid is in the list students. Parameter grades: The dictionary of student grades Precondition: grades has netids as keys, i...
5,342,552
def get_geo_signal_combos(data_source): """ Get list of geo type-signal type combinations that we expect to see. Cross references based on combinations reported available by COVIDcast metadata. """ meta = covidcast.metadata() source_meta = meta[meta['data_source'] == data_source] # Need to ...
5,342,553
def absolute_(x, track_types = True, **kwargs): """Compute the absolute value of x. Parameters ---------- x : :obj:`xarray.DataArray` Data cube containing the values to apply the operator to. track_types : :obj:`bool` Should the operator promote the value type of the output object, based ...
5,342,554
def upconv(path): """Check a 24bit FLAC file for upconversion""" if os.path.isfile(path): _upconvert_check_handler(path) elif os.path.isdir(path): for root, _, figles in os.walk(path): for f in figles: if f.lower().endswith(".flac"): filepath =...
5,342,555
def any_input(sys_, t, input_signal=0, init_cond=None, *, plot=True): """ Accept any input signal, then calculate the response of the system. :param sys_: the system :type sys_: TransferFunction | StateSpace :param t: time :type t: array_like :param input_signal: input signal accepted by th...
5,342,556
def get_combinations(suite_dir, fields, subset, limit, filter_in, filter_out, include_facet): """ Describes the combinations of a suite, optionally limiting or filtering output based on the given parameters. Includes columns for the subsuite and facets when incl...
5,342,557
def cli(ctx, dry_run, stack_resources, stack_exports): """Print stack status and resources. Also includes parameters, resources, outputs & exports.""" # shortcut if we only print stack key (and names) if dry_run: for context in ctx.obj.runner.contexts: ctx.obj.ppt.secho(context.sta...
5,342,558
def search(api: ApiClient, context: UserContext, search_string, as_csv): """ Search for a user """ if as_csv: fieldnames = ['id', 'title_before', 'first_name', 'last_name', 'title_after', 'avatar_url'] csv_writer = csv.DictWriter(sys.stdout, fieldnames=fieldnames) csv_writer.wri...
5,342,559
def mnext_mbv2_cfg(pretrained=False,in_chans=3,drop_rate=0.2,drop_connect_rate=0.5,bn_tf=False,bn_momentum=0.9,bn_eps=0.001, global_pool=False, **kwargs): """Creates a MNeXt Large model. Tensorflow compatible variant """ from .mnext import mnext model = mnext(**kwargs) return model
5,342,560
def _embeddings_from_arguments(column, args, weight_collections, trainable, output_rank=2): """Returns embeddings for a column based on the computed arguments. Args: column: the co...
5,342,561
def stuw_laagstedoorstroombreedte(damo_gdf=None, obj=None, damo_doorstroombreedte="DOORSTROOMBREEDTE", damo_kruinvorm="WS_KRUINVORM"): """ als LAAGSTEDOORSTROOMHOOGTE is NULL en WS_KRUINVORM =3 (rechthoek) dan LAAGSTEDOORSTROOMBREEDTE = DOORSTROOMBREEDTE """ return damo...
5,342,562
def manage_categories(): """ Display all categories to manage categories page (admin only) """ # Denied user access to manage_categories page if session["user"] != "admin": return redirect(url_for('error', code=403)) # query for all categories from categories collection manage_categ...
5,342,563
def callback(id): """ 获取指定记录 """ # 检查用户权限 _common_logic.check_user_power() _positions_logic = positions_logic.PositionsLogic() # 读取记录 result = _positions_logic.get_model_for_cache(id) if result: # 直接输出json return web_helper.return_msg(0, '成功', result) else: ...
5,342,564
def setup_exps_rllib(flow_params, n_cpus, n_rollouts): """Return the relevant components of an RLlib experiment. Parameters ---------- flow_params : dict flow-specific parameters (see flow/utils/registry.py) n_cpus : int number of CPUs to ru...
5,342,565
def sort_cluster(x: list, t: np.ndarray) -> list: """ sort x according to t :param x: :param t: :return: """ return [x[i] for i in np.argsort(t)]
5,342,566
def virtualenv(ctx: DoctorContext): """Check that we're in the correct virtualenv.""" try: venv_path = pathlib.Path(os.environ['VIRTUAL_ENV']).resolve() except KeyError: ctx.error('VIRTUAL_ENV not set') return # When running in LUCI we might not have gone through the normal envi...
5,342,567
def gettof(*args): """gettof(flags_t F) -> ushort""" return _idaapi.gettof(*args)
5,342,568
def test_parse_new_order(): """Test parsing raw new order data.""" args = { "limit_price": 1, "max_quantity": 2, "client_id": 3, "side": Side.Sell, "order_type": OrderType.PostOnly, } expected = bytes.fromhex( "000100000001000000010000000000000002000000000...
5,342,569
def generate(temp): """ Wrapper that checks generated names against the base street names to avoid a direct regurgitation of input data. returns list """ is_in_dict = True while is_in_dict: result = textgen.generate(temperature=temp, return_as_list=True) str = ' '.jo...
5,342,570
def __create_pyramid_features(backbone_dict, ndim=2, feature_size=256, include_final_layers=True, lite=False, upsample_type='upsamplelike', ...
5,342,571
def graphviz(self, filename=None, directory=None, isEdge=False,showLabel=True, **kwargs): """Return graphviz source for visualizing the lattice graph.""" return lattice(self, filename, directory, isEdge, showLabel, **kwargs)
5,342,572
def plotDecisionBoundary(theta, X, y, Lambda): """ Plots the data points X and y into a new figure with the decision boundary defined by theta PLOTDECISIONBOUNDARY(theta, X,y) plots the data points with + for the positive examples and o for the negative examples. X is assumed to be a...
5,342,573
def test_get_tot_pop(): """Testing """ scenario_drivers = {'heating': ['population']} classobject1 = dw_stock.Dwelling( 2015, {'longitude': 10, 'latitude': 10}, 1000, ['heating'], scenario_drivers, population=2.2 ) classobject2 = dw_stock.Dwelling...
5,342,574
def get_rectangle(origin, end): """Return all points of rectangle contained by origin and end.""" size_x = abs(origin[0]-end[0])+1 size_y = abs(origin[1]-end[1])+1 rectangle = [] for x in range(size_x): for y in range(size_y): rectangle.append((origin[0]+x, origin[1]+y)) retu...
5,342,575
def corr_list(df, target, thresh=0.1, sort=True, fill=True): """ List Most Correlated Features Returns a pandas Series with the most correlated features to a certain target variable. The function will return features with a correlation value bigger than some threshold, which can be adjusted. P...
5,342,576
def test_positive_change_license_status(assignment_type, license_handler, assignment_handler, create_environment_for_assignment_type): """Positive test: test all valid status changes (+ if status was set correct)""" object_type = _ASSIGNMENT_TYPE_TO_OBJECT_TYPE[assignment...
5,342,577
def compute_epsilon(steps): """Computes epsilon value for given hyperparameters.""" if FLAGS.noise_multiplier == 0.0: return float('inf') orders = [1 + x / 10. for x in range(1, 100)] + list(range(12, 64)) sampling_probability = FLAGS.batch_size / NUM_TRAIN_EXAMPLES rdp = compute_rdp(q=sampling_probabilit...
5,342,578
def get_native_includes(object): """ After method association, check which native types an object uses and return a corresponding string list of include file This will also add the include needed for inheritance """ includes = set() for proc in object.procs: for argname,arg in proc....
5,342,579
def libraries_data_path(): """ Path to Packages/User/Deviot/pio/libraries.json """ user_data = user_pio_path() return path.join(user_data, 'libraries.json')
5,342,580
def dice_coeff(input, target): """Dice coeff for batches""" if input.is_cuda: s = torch.FloatTensor(1).to(device_f).zero_() else: s = torch.FloatTensor(1).zero_() for i, c in enumerate(zip(input, target)): s = s + DiceCoeff().forward(c[0], c[1]) return s / (i + 1)
5,342,581
def group_error_rates(labels, predictions, groups): """Returns a list containing error rates for each protected group.""" errors = [] for jj in range(groups.shape[1]): if groups[:, jj].sum() == 0: # Group is empty? errors.append(0.0) else: signed_labels_jj = 2 * labels[groups[:, jj] == 1] - 1...
5,342,582
def lnprior(theta): """ Parameters ---------- theta : np.ndarray Array of parameters. Returns ------- Value of log-prior. """ pass
5,342,583
def get_emails_by_user_names(user_names): """Get emails by user names.""" emails_service = emails_digest_service.DailyEmailsService() emails_service.open_emails_digest() user_emails_dict = dict.fromkeys(user_names) for user_name in user_names: user_emails_dict[user_name] = emails_service.get_email_by_user...
5,342,584
def get_match_results(depc, qaid_list, daid_list, score_list, config): """ converts table results into format for ipython notebook """ # qaid_list, daid_list = request.get_parent_rowids() # score_list = request.score_list # config = request.config unique_qaids, groupxs = ut.group_indices(qaid_list)...
5,342,585
def inbound_and_outbound_node_sets(C, CT): """ Returns the set of nodes that can reach an event and can be reached by an event, and the difference between those sets (outbound / inbound). """ inbound = defaultdict(set) for node, event in zip(*np.nonzero(C)): inbound[event].add(node) outbound = defaultdic...
5,342,586
def policy(Q): """Hard max over prescriptions Params: ------- * Q: dictionary of dictionaries Nested dictionary representing a table Returns: ------- * policy: dictonary of states to policies """ pol = {} for s in Q: pol[s] = max(Q[s].items(), key=lambda...
5,342,587
def test_should_generate(fixture, color, result, expected): """Only return True if existing badge needs updating""" output = os.path.join(FIXTURES, "default-style", fixture) actual = badge_gen.should_generate_badge(output, color, result) assert actual is expected
5,342,588
def main(argv=sys.argv) -> None: # pragma: no cover """Run type coverage check.""" parser = argparse.ArgumentParser( usage=("python type_coverage.py coverage=80 file=typecov/linecount.txt \n") ) parser.add_argument( "coverage", type=float, metavar="<coverage>", h...
5,342,589
def fft(series): """ FFT of a series Parameters ---------- series Returns ------- """ signal = series.values time = series.index dt = np.mean(np.diff(time)) #n = 11*len(time) n = 50000 frequencies = np.fft.rfftfreq(n=n, d=dt) # [Hz] dft = np.abs(np.fft.rf...
5,342,590
def local_variance(V, tsize=5): """ local non-linear variance calculation Parameters ---------- V : numpy.array, size=(m,n), dtype=float array with one velocity component, all algorithms are indepent of their axis. Parameters ---------- sig_V : numpy.array, size=(m,n), dtyp...
5,342,591
def get_virtual_device_configuration(device): """Get the virtual device configuration for a PhysicalDevice. Returns the list of VirtualDeviceConfiguration objects previously configured by a call to `tf.config.experimental.set_virtual_device_configuration()`. For example: >>> physical_devices = tf.config.ex...
5,342,592
def user_directory_path(instance, filename): """Sets path to user uploads to: MEDIA_ROOT/user_<id>/<filename>""" return f"user_{instance.user.id}/{filename}"
5,342,593
def process_command_line(): """Process the file on the command line when run as a script or entry point.""" args = parse_command_line() code_file = args.code_file[0] processed_code = strip_file_to_string(code_file, args.to_empty, args.strip_nl, args.no_ast, args.no_colon_move,...
5,342,594
def not_none_to_dict(args_dict, key, value): """ Если значение не None, кладем его в словарь. """ if not (value is None): args_dict[key] = value
5,342,595
async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Load Tradfri switches based on a config entry.""" gateway_id = config_entry.data[CONF_GATEWAY_ID] tradfri_data = hass.data[DOMAIN][config_entry.entry_id] api = ...
5,342,596
def setup(app): """Setup the Sphinx extension.""" # Register builder. app.add_builder(BeamerBuilder) # Add setting for allowframebreaks. app.add_config_value("beamer_allowframebreaks", True, "beamer") # Add setting for Beamer theme. app.add_config_value("beamer_theme", "Warsaw", "beamer") ...
5,342,597
def select_object_by_name_no_context(name): """ This is an attempt to deal with an incorrect context error """ obj = bpy.data.objects[name] for o in bpy.context.view_layer.objects: if (is_blender_28()): o.select_set(False) else: o.select = False if (is_blender_28()):...
5,342,598
def EndorseConnections(browser): """ Endorse skills for your connections found. This only likes the top three popular skills the user has endorsed. If people want this feature can be further expanded just post an enhancement request in the repository. browser: """ print("Gathering your conn...
5,342,599