content
stringlengths
22
815k
id
int64
0
4.91M
def assign_material(obj, materialname): """This function assigns a material to an objects mesh. :param obj: The object to assign the material to. :type obj: bpy.types.Object :param materialname: The materials name. :type materialname: str """ if materialname not in bpy.data.materials: ...
5,292,100
def make_fcc(nx=1, ny=1, nz=1, scale=1.0, noise=0.0): """Make a FCC crystal for testing Args: nx: Number of repeats in the x direction, default is 1 ny: Number of repeats in the y direction, default is 1 nz: Number of repeats in the z direction, default is 1 scale: Amount to sca...
5,292,101
def getfname(chapelfile, output, prefix): """Compute filename for output""" if output == 'rst': filename = os.path.split(chapelfile)[1] basename, _ = os.path.splitext(filename) rstname = ''.join([basename, '.rst']) rstfile = os.path.join(prefix, rstname) return rstfile ...
5,292,102
def load_pickle(pickle_path: str) -> object: """Avoid boilerplate pickle loading. Args: pickle_path (str): Path of pickle file Returns: object: Python object unpickled """ assert_file_exists(pickle_path) with open(pickle_path, "rb") as pf: return pickle.load(pf)
5,292,103
def post_build(service: str, debug: bool): """Deletes config files generated in pre-build""" delete_file('./.ssh/id_rsa') delete_file('./config.yml') delete_file('./.gitconfig') delete_file(f'{service}-public.app') delete_file('./repositories.txt') delete_file('./runtime_install.sh') ...
5,292,104
def create_files(data: np.ndarray, nyq_f: float, priors: List[List[float]], kwargs: Dict): """ Creates all files for a DIAMONDS run :param data: Lightcurve dataset :param nyq_f: Nyquist frequency :param priors: List of priors :param kwargs: Run configuratio """ print_int(f"Path: {full_re...
5,292,105
def test_score_best_matches_compiled(matching_pairs, expected_score): """Test finding expected peak matches for given tolerance.""" matching_pairs = numpy.array(matching_pairs) spec1 = numpy.array([[100, 200, 300, 500], [0.1, 0.1, 1.0, 1.0]], dtype="float").T spec2 = numpy.arra...
5,292,106
def add_to_list(str_to_add, groups): """ This will add a string to the groups array if it does not exist. It will then return the index of the string within the Array """ if str_to_add.replace(".", REPLACE_CHAR) not in groups: groups.append(str_to_add.replace(".", REPLACE_CHAR)) return g...
5,292,107
def analyze_channel(blobfiles=None, channel=None, start=1, end=0, print_msg=True, server="http://localhost:5279"): """Obtain usage information from a channel by analyzing its blobs. If the channel is not specified, it will analyze all blobs from all v...
5,292,108
def get_centroid(coords): """ Function: get centroids of given coordinates. Input: - coords: numpy array. mx2xn. m = number of centroids; n = number of points per centroid. Output: - new_coords: numpy array (mx2). centroids. """ new_coords = np.zeros((coords.shape[0], coords.shape[1])) for i in range(...
5,292,109
def towers_of_hanoi(n: int) -> List[Move]: """This is a classic CS problem that's often used as an introduction to recursion. """ return towers_helper(n, 1, 3, 2)
5,292,110
def copy_with_rename(src_dir, dst_dir, accept_pred=None, rename=None): """Copy files from src_dir to dst_dir that match accept_pred (all if None) and rename using rename (if not None), replacing existing files. accept_pred takes the filename and returns True if the file should be copied, rename takes the f...
5,292,111
def fill_metrictypes(apps, schema_editor): """ Fill MetricType model to predefined values if not already filled with fixtures. """ MetricType = apps.get_model('poem', 'MetricType') if MetricType.objects.count() == 0: m = MetricType(name='Active') m.save() m = Metr...
5,292,112
def update_Sx(S_old, n_old, d_old, d_new, d_min): """ Update on the sum of log degrees S_d and n based on degree distribution resulting from inserting or deleting a single edge. Parameters ---------- S_old: float Sum of log degrees in the distribution that are larger than or equal to d...
5,292,113
def cumprod(mod: int, a: typing.List[int]) -> typing.List[int]: """Compute cummulative product over Modular.""" a = a.copy() for i in range(len(a) - 1): a[i + 1] = a[i + 1] * a[i] % mod return a
5,292,114
def is_skin_cluster(skin_cluster): """ Checks if the given node is a valid skinCluster :param skin_cluster: str, name of the node to be checked :return: bool, True if the given node is a skin cluster node """ if not maya.cmds.objExists(skin_cluster): logger.error('SkinCluster "{}" does...
5,292,115
def update(letter, a_word, a_list): """update the printed version of the word""" for let in range(len(a_word)): if a_word[let] == letter: a_list[let] = letter
5,292,116
def opp_move(player: Player) -> (bool, bool): """ Utility function to simulate opponent's moves on your board. :param player: Player object :return: (Bool, Bool) : change_turn and game_on booleans indicating whether to reverse the turn and whether the game is not over. ""...
5,292,117
def get_v50(line,epoch,velocity,evelocity): """ Eg: In [1]: from epm.velocity import get_v50,vHbetatovFeII,vph50tovFe In [2]: v50_hbeta,ev50_hbeta=get_v50("Hbeta",18.,10350,500) In [3]: vFeII50,evFeII50=vHbetatovFeII(v50_hbeta,ev50_hbeta) In [4]: vFeII50,evFeII50 Out[4]: (4853.111318324523,...
5,292,118
def is_retfp(*args): """ is_retfp(ea) -> bool """ return _ida_nalt.is_retfp(*args)
5,292,119
def outbound(): """Returns a function that generates a matrix out of bounds a given range""" def _outbound(low, high, size, tol=1000, nums=100): """Generates a matrix that is out of bounds""" low_end = -np.random.uniform(tol, low, (nums,)) high_end = np.random.uniform(tol, high, (nu...
5,292,120
def trans_in_lang(string, lang): """ Translate a string into a specific language (which can be different than the set language). Usage: {{ var|trans_in_lang:"fr" }} """ if check_for_language(lang): return translation(lang).ugettext(string) return string
5,292,121
async def async_set_config_parameter( node: Node, new_value: Union[int, str], property_or_property_name: Union[int, str], property_key: Optional[Union[int, str]] = None, ) -> Tuple[ConfigurationValue, CommandStatus]: """ Set a value for a config parameter on this node. new_value and propert...
5,292,122
def black_out(x, t, W, samples, reduce='mean'): """BlackOut loss function. BlackOut loss function is defined as .. math:: -\\log(p(t)) - \\sum_{s \\in S} \\log(1 - p(s)), where :math:`t` is the correct label, :math:`S` is a set of negative examples and :math:`p(\\cdot)` is likelihood of a ...
5,292,123
def has_instance(cls, typeclass): """Test whether a class is a member of a particular type-class. :param cls: The class or type to test for membership. :param typeclass: The typeclass to check. Must be a subclass of `Typeclass`:class:. :returns: True if cls is a member of typeclass, and F...
5,292,124
def monitor_system(): """ This task used by scheduler to monitor state of the system. :return: """ for p in models.DVAPQL.objects.filter(completed=False): if models.TEvent.objects.filter(parent_process=p, completed=False).count() == 0: p.completed = True p.save() ...
5,292,125
def install_dev(session, extras: str = ""): """ Install all package and dev dependencies. """ session.install(f".{extras}") session.install("-r", DEV_REQUIREMENTS)
5,292,126
def two_fermion(emat, lb, rb): """ Build matrix form of a two-fermionic operator in the given Fock basis, .. math:: <F_{l}|\sum_{ij}E_{ij}\hat{f}_{i}^{\dagger}\hat{f}_{j}|F_{r}> Parameters ---------- emat : 2d complex array The impurity matrix. lb : list or array ...
5,292,127
def leakyRelu(X): """ Apply Leaky Rectified Linear Unit on X Vector. PARAMETERS ========== X: ndarray(dtype=float, ndim=1) Array containing Input Values. RETURNS ======= ndarray(dtype=float,ndim=1) Output Vector after Vectorised Operation. """ return np.maximu...
5,292,128
def box_read(path_out, sim_id): """Read in ChemEvol instance from box<sim_id>.pck file. Args: path_out (str): directory of pickle file. sim_id (str): simulation ID number. Returns: object: instance of ChemEvol class ('box' object). """ fname = _make_sim_path(path_out, sim_i...
5,292,129
def plot_projection_data(X, y, mu, nclasses, figure_num): """ 2d data is visualized with their respective symbol and color and the centroids of the data are plotted with black filled-in color. """ # To match the Hastie color scheme lightblue = [55, 155, 255] orange = [255, 128, 0] magen...
5,292,130
def second(str_number): """ :param str_number: str :return int """ list_number = list(str_number) total = list_number.__len__() half = total/2 result = 0 for key, x in enumerate(list_number): index_y = int((key + half) % total) if x == list_number[index_y]: ...
5,292,131
def get_active_psupport(): """ Returns all active prod support tests """ results = [] experiences = get_experiences() for exp in experiences: if len(exp["splits"]) == 1: exp_name = exp["experience_name"] external_link = create_external_link(exp_name, exp["id"]) ...
5,292,132
def is_valid_ipv4(address): """Check an IPv4 address for validity""" try: ip = ipaddress.ip_address(address) except ValueError: return False if not isinstance(ip, ipaddress.IPv4Address): return False warning = None if ip.is_loopback: warning = "loopback address" ...
5,292,133
def two_pts_to_line(pt1, pt2): """ Create a line from two points in form of a1(x) + a2(y) = b """ pt1 = [float(p) for p in pt1] pt2 = [float(p) for p in pt2] try: slp = (pt2[1] - pt1[1]) / (pt2[0] - pt1[0]) except ZeroDivisionError: slp = 1e5 * (pt2[1] - pt1[1]) a1 =...
5,292,134
def cut_into_multiple_parts(src: Union[str, Path], dst: Union[str, Path], *, durations: List[float], vcodec="libx264", enable_cuda=True, overwrite=True): """Cut the video or audio into multiple parts. Example: avutils.cut_into_multiple_parts("vide...
5,292,135
def unstandardize_set(var_list, sample_array): """ Inputs: var_list- list of variables sample_array- array with one sample corresponding to each variable Takes an array of standardized values, unstandardizes them, and returns the array of unstandardized values. """ var_count, i...
5,292,136
def get_policy(request, log, tenantId, groupId, policyId): """ Get a scaling policy which describes an id, name, type, adjustment, and cooldown, and links. This data is returned in the body of the response in JSON format. Example response:: { "policy": { "id": ...
5,292,137
def loss(*, target_sfs, events, n, key, nreps=20): """ Mean squared error between ``target_sfs`` and simulated sfs when simulating with the given ``events``, averaged over ``nreps`` replicate simulations. """ avg_sfs = jnp.zeros(n + 1) for key in jax.random.split(key, nreps): pi, tau...
5,292,138
def profile(func: Callable) -> Callable: """ A decorator that uses cProfile.Profile class to profile a function. :param func: function :return: function """ def inner(*args, **kwargs): pr = Profile() pr.enable() result = func(*args, **kwargs) pr.disable() ...
5,292,139
def yield_function(E,species='W'): """ use: Y = yield_function(E,species='W') This method implements the modified Bohdansky formula for physical sputtering with incidence angle 0. See for example Y. Marandet et. al. PPCF 58 (2016) 114001 input: E: Energy of incoming projetiles. ... (1xN...
5,292,140
def ts2gis(square, line_spacing, velocity = None, outdir = None): """Plot timeslice contours to polygons and rectify; the resulting plot contains holes""" import tempfile from PIL import Image, ImageChops import gdal, osr import geopandas as gpd import matplotlib.pyplot as plt # loa...
5,292,141
def test_gift_card_create_code(): """Tests the API endpoint to create a Binance Code""" response = client.gift_card_create_code(**params) response.should.equal(mock_item)
5,292,142
def get_current_day(): """ return the current day number value from (1-7). """ from datetime import date return date.today().isocalendar()[2]
5,292,143
def test_musician_solo(): """ Each kind of Musician instance should have a play_solo method that returns string. """ actual = [jon.play_solo(), cersei.play_solo(), little_finger.play_solo()] expected = ['*shreds guitar with pick*', '*slaps bass*', '*badum ch*'] assert actual == expected
5,292,144
def _load_with_pydub(file, audio_format=None): """ Open compressed audio or video file using pydub. If a video file is passed, its audio track(s) are extracted and loaded. Parameters ---------- file : str path to audio file. audio_format : str, default: None string, audio/vi...
5,292,145
def findpath(name): """Resolves absolute path of module""" path = import_module(name).__file__ # adjust file extension path = re.sub('.pyc$', '.py', path) # strip trailing "__init__.py" path = re.sub('__init__.py$', '', path) return path
5,292,146
def sets_k_fold_pattern(rdms, pattern_descriptor='index', k=5, random=False): """ generates training and test set combinations by splitting into k similar sized groups. This version splits in the given order or randomizes the order. For k=1 training and test_set are whole dataset, i.e. no crossvalidatio...
5,292,147
def lambda_handler(event, context): """This is a sample Annotation Consolidation Lambda for custom labeling jobs. It takes all worker responses for the item to be labeled, and output a consolidated annotation. Parameters ---------- event: dict, required Content of an example event ...
5,292,148
def convert_dtypes(df: DataFrame, keys: Iterable[str]) -> DataFrame: """ Wrapper around df.astype(), cast DataFrame columns to the appropriate type for each key. Use mapping from TX_KEY_DTYPES global. """ return df.astype({key: TX_KEY_DTYPES[key] for key in keys}, copy=False)
5,292,149
def diff_param_values_by_id(left_id: RunId, right_id: RunId) -> ParameterDiff: """ Given the IDs of two datasets, returns the differences between parameter values in each of their snapshots. """ # Local import to reduce load time and # avoid circular references. from qcodes.dataset.data_set ...
5,292,150
def query(client: Client, service_code: str, header: dict = HEADER, check_query: bool = True, check_response: bool = True, **params) -> OrderedDict: """Query Elexon API. Parameters ---------- client : Client service_code : str header : dict ...
5,292,151
def get_band_num(color, satellite): """Get the image band # from the color and satellite Parameters ---------- color: string color band name i.e. red, green, nir1 satellite: string code for satellite (supports quickbird, geoeye 1 and worldview 2/3) Returns ------- int ...
5,292,152
def ResNet50(parameters, num_channel=3, num_classes=10, att=False, mean=False): """ Function that creates a ResNet 50 model :param parameters (list or tuple): List of parameters for the model :param num_channel (int): Number of channels in input specimens :param num_classes (int): Number of classes...
5,292,153
def read_file_list(path: str) -> List[str]: """读取文件列表(包含\\n字符)""" with open(path, 'r', encoding='utf-8') as f: content = f.readlines() # 包含\n字符 return content
5,292,154
def test_ridge_regression(): """ Test a simple linear function f(x) = 4x + 2, and checks that Ridge regression obtains the coefficients 4 and 2 (+/- 0.1). """ x = np.linspace(-2,2,1000) X = np.column_stack((np.ones(1000), x)) y = 4*x + 2 + np.random.normal(0,0.2,1000) LinReg = LinearRegr...
5,292,155
def letterbox_resize_tensor(src, dst_h, dst_w): # https://stackoverflow.com/a/66539730 # It seems GPU is not helpful in this case """Resize with same aspect ratio as source image. Args: src: `torch.tensor`, source image which has a size of (N, C, H, W). dst_h: `int`, height of target im...
5,292,156
def get_target(words, idx, window_size=5): """ Get a list of words in a window around an index Input: * words: the dictionary of words * idx: the index for the word of interest * window_size: (Optional) the number of words to include Output: * returns the words of interest that fall into the window ""...
5,292,157
def all(ctx): """ """ with open("config.json") as file: config = json.load(file) if ctx.obj["PREPROCESS"]: datasets = ["vesselfinder", "helcom"] for d in datasets: reduce_ais(d, config) merge_ais(config) calculate_routes(config) calculate_emissions...
5,292,158
def define_inputs(): """ In this function, the user must define all the inputs that are required to run a simulation. Returns: """ # Define the required inputs. req_inputs = {'B': 0.0467, 'Lambda': 1., 'E0': 0.99, 'C_R': 1e3, ...
5,292,159
def FSeek(params, ctxt, scope, stream, coord): """Returns 0 if successful or -1 if the address is out of range """ if len(params) != 1: raise errors.InvalidArguments( coord, "{} args".format(len(params)), "FSeek accepts only one argument", ) pos = PYV...
5,292,160
def processFocusNVDAEvent(obj,force=False): """Processes a focus NVDA event. If the focus event is valid, it is queued. @param obj: the NVDAObject the focus event is for @type obj: L{NVDAObjects.NVDAObject} @param force: If True, the shouldAllowIAccessibleFocusEvent property of the object is ignored. @type force:...
5,292,161
def record_non_dicts(subject, memo): """Find all the things in subject that are not string or dicts and fill memo with {id(thing): thing}""" for key, val in subject.items(): if not isinstance(val, dict) and not isinstance(val, string_types): memo[id(val)] = val elif isinstance(val, ...
5,292,162
def filter_results(TAP_df, print_targets=True): """ Add a few new useful columns to the pandas.DataFrame with the query results from the PyVO TAP service and return the full query DataFrame and optionally a summary of the results. Parameters ---------- TAP_df : pandas.DataFrame This is...
5,292,163
def node_list(request): """Retrieve a list of nodes. :param request: HTTP request. :return: A list of nodes. http://docs.openstack.org/developer/python-ironicclient/api/ironicclient.v1.node.html#ironicclient.v1.node.NodeManager.list """ node_manager = ironicclient(request).node return node...
5,292,164
def delete_credentials(credentials): """ A function that deletes a Credential from credentials list """ credentials.delete_credentials()
5,292,165
def auto_message(name, message): """Searches for friend on Google Hangouts and messages them.""" print("Make sure the Google Hangout 'Conversations' page is visible and " "your cursor is not currently on the page.") time.sleep(3) search_bar = pyautogui.locateOnScreen('search.png') pyautog...
5,292,166
def random_input(in_features: int) -> ByteTensor: """Return a random bit tensor of length 'in_features.'""" state = np.random.randint(0, 2, (in_features, )).astype(np.int32) return torch.from_numpy(state).byte()
5,292,167
def download_urls(urls: Iterable[str], path: str, session: ASFSession = None, processes: int = 1): """ Downloads all products from the specified URLs to the specified location. :param urls: List of URLs from which to download :param path: Local path in which to save the product :param session: The ...
5,292,168
def semi_split(s): """ Split 's' on semicolons. """ return map(lambda x: x.strip(), s.split(';'))
5,292,169
def get_implementation() -> Optional[PythonImplementation]: """Determine the current Python implementation. :return: The appropriate :class:`~PythonImplementation` instance if found :rtype: Optional[PythonImplementation] """ try: return PythonImplementation(python_implementation().lower())...
5,292,170
def sample_passwds(): """Pre-generates password hashes for `sample_users`. This drastically speeds up any tests relying on sample users, as bcrypt is intentionally very slow.""" pwds = dict( admin='a', mod='b', arch='c', user='d', ) for k, pwd in pwds.items(): ...
5,292,171
def well_formed(expr): """Check that each Var is only bound once (well formed). Parameters ---------- expr : tvm.relay.Expr The input expression Returns ------- well_form : bool Whether the input expression is well formed """ return _ffi_api.well_formed(expr)
5,292,172
def call_function(ctx, node, func_var, args, fallback_to_unsolvable=True, allow_noreturn=False): """Call a function. Args: ctx: The abstract context. node: The current CFG node. func_var: A variable of the possibl...
5,292,173
def login(): """Log user in.""" # forget any user_id session.clear() # if user reached route via POST (as by submitting a form via POST) if request.method == "POST": # ensure username was submitted if not request.form.get("username"): return apology("Must pr...
5,292,174
def _system_mat3d(fmatin, cmat, fmatout): """Computes a system matrix from a characteristic matrix Fin-1.C.Fout""" fmatini = inv(fmatin) out = bdotdm(fmatini,cmat) return bdotmd(out,fmatout)
5,292,175
def grad(phit): """Returns the spatial derivatives of a Fourier transformed variable. Returns (∂/∂x[F[φ]], ∂/∂y[F[φ]]) i.e. (ik F[φ], il F[φ])""" global ik, il phixt = ik*phit # d/dx F[φ] = ik F[φ] phiyt = il*phit # d/dy F[φ] = il F[φ] return (phixt, phiyt)
5,292,176
def csv_reader(data_file): """returns np.array(time), np.array(voltage) This function reads in csv files. The for loop reads each row of the time and voltage lists and converts them from strings to floats. If a string can't be converted, a ValueError is raised and that index is skipped. The er...
5,292,177
def KS_bucket(score, target, bucket = 10, method = 'quantile', **kwargs): """calculate ks value by bucket Args: score (array-like): list of score or probability that the model predict target (array-like): list of real target bucket (int): n groups that will bin into method (str)...
5,292,178
def create_input_data(): """Utility function for creating input data.""" position = Coordinate2d(3.0, 4.0) speed = Coordinate2d(2.0, 5.0) sample_time = 0.1 return {'position': position, 'speed': speed, 'sample_time': sample_time}
5,292,179
def get_metadata(**kwargs): """ Metadata Account metadata Reference: https://iexcloud.io/docs/api/#metadata Data Weighting: ``Free`` """ return Metadata(**kwargs).fetch()
5,292,180
def polyConvMatrix(n, trans=(0, 1)): """ Return the upper triangular matrix (i,k) * b**k * a**(i-k), that converts polynomial coeffs for x~:=a+b*x (P~ = a0~ + a1~*x~ + a2~*x~**2 + ...) in polynomial coeffs for x (P = a0 + a1*x + a2*x**2 + ...). Therefore, (a,b)=(0,1) gives identity. """ fro...
5,292,181
def rank_2d_float64(*args, **kwargs): # real signature unknown """ Fast NaN-friendly version of scipy.stats.rankdata """ pass
5,292,182
def get_user_activity(session): """Create a plot showing the inline usage statistics.""" def running_window(session, subquery): # Create a running window which sums all users up to this point for the current millennium ;P users = ( session.query( subquery.c.creation_...
5,292,183
def git_version(file, version=None): """ Fetch from Git: {tag} {distance-from-tag} {current commit hash} Return as semantic version string compliant with PEP440 """ root = os.path.dirname(os.path.realpath(file)) try: tag, distance, commit = g.gitDescribe(root) # 5.6b2, 55, e1...
5,292,184
def test_pycode_no__context_throw(): """No pycode in context should throw assert error.""" with pytest.raises(KeyNotInContextError) as err_info: context = Context({'blah': 'blah blah'}) pypyr.steps.py.run_step(context) assert str(err_info.value) == ("context['py'] " ...
5,292,185
def get_log_from_policy(policy: Policy, policy_id: PolicyID) -> dict: """ Gets the to_log var from a policy and rename its keys, adding the policy_id as a suffix. """ to_log = {} if hasattr(policy, "to_log"): for k, v in policy.to_log.items(): to_log[f"{k}/{policy_id}"] = v ...
5,292,186
def show_ridge_plot(df: pd.DataFrame, name="naked") -> sns.FacetGrid: """Shows the distribution of the data for different categories. Using the output from `generate_df_for_theo_correlation_comparison` we group the data per quantile and display it in several different distribution plots. Taken alm...
5,292,187
def f2n( fig ): """ @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it @param fig a matplotlib figure @return a numpy 3D array of RGBA values """ # draw the renderer fig.canvas.draw() data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uin...
5,292,188
def error(bot, update, err): # pylint: disable=unused-argument """Log any error""" logger.warning("Update \"%s\" caused error \"%s\"", update, err)
5,292,189
def main(): """Handle command line and generate a file.""" parser = argparse.ArgumentParser(description='Bindings generator.') parser.add_argument( 'bindings', help='Bindings file to use') parser.add_argument( 'output', type=str, nargs='+', help='Output file, uses the name to cho...
5,292,190
def windows_details(request): """Get available connection details for windows hosts""" return connection_details_for(request.param)
5,292,191
def exclude_jobs(jobs, project, tag) -> list: """Returns list of jobs filtered by exclude map variables. Args: jobs: List of jobs project: A project name string tag: A tag string Returns: List of of jobs after being filtered with the exclude maps """ included_jobs =...
5,292,192
def getImage(matrix): """ Convert the 3d numpy array back into an image. """ return Image.fromarray(np.uint8(matrix)).convert('RGB')
5,292,193
def test_pgtest_compatibility(): """Test using a temporary postgres cluster set up via PGTest. """ with PGTest() as cluster: pgsu = PGSU(dsn=cluster.dsn) # make sure we've connected to the right cluster assert cluster.dsn['port'] == pgsu.dsn['port'] # we should be connectin...
5,292,194
def _get_additional_sign_content_plan(device_type): """ Get AdditionalSignContentPlan instance and set its related models interfering device_types to universal one. """ universal_device_type = get_traffic_control_device_type( code="123", target_model=None ) obj = get_additional_sign_...
5,292,195
def convert_all(base_path: Path, dest_path: Path, count: int, max_size: int) -> None: """ Start converting in some processes. Processes count is equal to count of cpu cores - 1 (or 1 if there's only one cpu core). :param base_path: Path to the folder...
5,292,196
def get_org_link_by_short_link(session, short_link): """ Get origin link from short link :param session: this param is session to connect to database :param short_link: Short link """ origin_link = session.query(models.Url).filter(models.Url.short_link == ...
5,292,197
def _design(n, p, rho, equicorrelated): """ Create an equicorrelated or AR(1) design. """ if equicorrelated: X = (np.sqrt(1 - rho) * np.random.standard_normal((n, p)) + np.sqrt(rho) * np.random.standard_normal(n)[:, None]) def equi(rho, p): if ('equi', p,...
5,292,198
def unidades_medida(): """ Muestra las configuraciones para las unidades de medida """ grid = webgrid.WebGrid(crud) grid.datasource = db(db.unidades_medida).select() grid.pagesize = 20 #grid.fields = ['db.catmod.id', 'db.catmod.nombre', 'db.catmod.posicion'] #grid.filters = ['db.catmod.c...
5,292,199