content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def index_to_position(index, strides): """ Converts a multidimensional tensor `index` into a single-dimensional position in storage based on strides. Args: index (array-like): index tuple of ints strides (array-like): tensor strides Returns: int : position in storage """ ...
4f31049896b7087cf821feea1878b285559f8ab3
3,604,700
from pathlib import Path def _node_does_not_exist(node_path): """ Determine whether module already exists for node :param node_path: full path to node module :return: bool; True if node does not exist; False if it does exist """ try: # noinspection PyArgumentList Path(node_pa...
242f9895cb6e7ef4441b6d76b013cbdc88f8de45
3,604,701
from sys import version def modern_gfile(): """Check the version number of tensorboard. Cheking to see if it has the gfile compatibility layers needed for remote file operations """ tb_version = version.parse(tensorboard.version.VERSION) modern_gfile = tb_version >= version.parse("2.0") r...
b7ee07c94463539c06042b596d6fbb39f0eb3b92
3,604,702
def mock_config_entry1(opp): """Mock a config entry.""" return create_config_entry()
fd462a8291e3a2f9a9bd92fde97ac58953b6fff0
3,604,703
def choose_question(): """Choose a random answer""" random_index_question = randint(1, question.num_question + 1) random_question = question.question[random_index_question] correct_answer = question.answer[random_index_question] return random_question, correct_answer
7ed6cd12110b5fa8ee5f0baea17a5fa833031d21
3,604,704
def check_for_updates(): """ todo """ update_check = conf['plugins']['updater']['module'].update_check scheduler.add_job(update_check, id='web_ui_updater_update_check') menu_items = [] gossip.trigger('eva.web_ui.menu_items', menu_items=menu_items) success = 'Note that this is currently \...
f1745f74187560a265ba79497196182c2007e7d8
3,604,705
def produtividade(inicio, fim): """ Recebe dois anos e retorna uma lista de strings que informam a quantidade de filmes produzidos em cada ano dentro do intervalo recebido Parâmetros: Dois inteiros -> Um intervalo de anos Retorna: Uma lista de strings com a quantidade de filmes do ano co...
9bc539c5a8bdfe7d63a937e4fb5c716b82e643a1
3,604,706
def db_memory(con, detail=1): """ detail: 0, 1 or 2. """ reports = {x: con._client.get_memory(con._session, x) for x in ["cpu", "gpu"]} # print('reports', reports) d = [] for device_type, report in reports.items(): for i, info in enumerate(report): for node in info.node...
ba5d403500a539ed8dae4fa027a5d719c5b5e5bf
3,604,707
import multiprocessing def acquire_mpi_lock(cpu_count: int) -> bool: """ returns True if successfull Will try to acquire a distributed shared lock. """ reply_queue = multiprocessing.Queue() multiprocessing.Process( target=_process_worker, args=(reply_queue, cpu_count), daemon=True ...
2776394bd4f278e250937258b4bbe9b74b549916
3,604,708
def test_map_methods(webgroup): """Map methods behave as expected""" def func(): return dict(answer=42) @webgroup.register class Fake: name = 'fake' @webgroup.register class TestParent: pass name = 'name' xpath = '/hello' parent = TestParent() w = Com...
18794540aa3569fc575cb63e9caf7a752ed62fd1
3,604,709
import os def _get_home(): """Find user's home directory if possible. Otherwise raise error. :see: http://mail.python.org/pipermail/python-list/2005-February/263921.html """ path='' try: path=os.path.expanduser("~") except: pass if not os.path.isdir(path): for...
2b82e51a8c06ab34b546b117fa1cbc2eec88639f
3,604,710
from datetime import datetime import tqdm def real_section(path): """Downloads section data and runs fibermorph_section analysis. Returns ------- bool True. """ fibermorph_demo_dir = create_results_cache(path) input_directory = get_data(fibermorph_demo_dir, "section") ...
3d9f9da3086feb49f217cb77a2381729a2d5d187
3,604,711
def load_description(): """Return description""" with open("README.md") as buffer: return buffer.read()
b167638602c4d5f662ccc72e34dc042b7d9e63bb
3,604,712
from typing import List def batch_predict(batch_features: List[Features]): """Endpoint for getting scores for a batch of record.""" num_features = len(model.feature_name()) rows = np.zeros((len(batch_features), num_features)) for i, features in enumerate(batch_features): row = np.array([getat...
9990343e7cdd47d58cb8472ddcd40241efe590f5
3,604,713
def check_task(request, tid): """Check the status of a task""" try: slogger.glob.info("check task #{}".format(tid)) response = task.check(tid) except Exception as e: slogger.glob.error("cannot check task #{}".format(tid), exc_info=True) return HttpResponseBadRequest(str(e)) ...
94fa6aad582c2d530d1e743b0093d26577e339d8
3,604,714
def indent(s, depth): # type: (str, int) -> str """ Indent a string of text with *depth* additional spaces on each line. """ spaces = " "*depth interline_separator = "\n" + spaces return spaces + interline_separator.join(s.split("\n"))
69d509761cc6ab2f861f8b8c7fe7097ce8deff13
3,604,715
def get_value(key, obj, default=missing): """Helper for pulling a keyed value off various types of objects""" if isinstance(key, int): return _get_value_for_key(key, obj, default) return _get_value_for_keys(key.split("."), obj, default)
79e58dcadf8adf917dee92cd75a374c803195cb0
3,604,716
def joint_pdf_mean_y(pdf, binsx, binsy): """From a joint PDF, calculate the mean along the y-direction for each x-bin. Parameters ---------- pdf : np.ndarray Array of shape (binsy.size - 1, binsx.size - 1). This is the probability density function binsx : np.ndarray Array of bin edg...
275fcdf920ec23b4ab74e2e48d0af952a3980348
3,604,717
def project_to_image(point_cloud, p): """ Projects a 3D point cloud to 2D points for plotting :param point_cloud: 3D point cloud (3, N) :param p: Camera matrix (3, 4) :return: pts_2d: the image coordinates of the 3D points in the shape (2, N) """ pts_2d = np.dot(p, np.append(point_cloud, ...
e4f81251c4fe2f79277a41fde969e05469a14bcd
3,604,718
import os def add_files_in_dir(distdir, pkgdir, nfile, ndir, output, indent): """ Add file componenents from a directory, recursively adding from subdirs """ output.write('%s<Directory Id="INSTALLDIR%i" Name="%s">\n' % (indent, ndir, os.path.basename(pkgdir))) ndir += 1 for dirName, subdirList...
c735e9b81d78be1abe7f324d672bbae798e11ca9
3,604,719
def prior_transform(u): """Flat prior between -10. and 10.""" return 10. * (2. * u - 1.)
4dd488a76a08361f1c7d833eaef96a7dfdf51ca6
3,604,720
def show_graph(selected_node, selected_edge): """ Based on the selected element this generates the correct dot file for component update. """ # dictionary of all the nodes and if they are selected nodes = {node: node == selected_node for edge in edges for node in edge} lines = [ "di...
bebec227108fa321506ddb6ebc7f9f9b32cf44e2
3,604,721
import numpy def custom_decode(obj): """ Custom function to enchance msgpack decoding. obj::{} A dictionary representition of an object already unwrapped by msgpack return::Object The decoded object if a custom object """ if '__decimal__' in obj: return Decimal(obj['as_str']) if '...
97e09a732a701340b31aeb8b26d093086c1473e8
3,604,722
import importlib def import_from_string(dotted_path): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed. """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: ...
1010e9d3563cec163ff2cad7299f79ffcc39f8fc
3,604,723
def student_tryout_apply_result(): """ swagger-doc: 'do view_homework query' required: [] req: page_limit: description: 'records in one page' type: 'integer' page_no: description: 'page no' type: 'integer' study_appointment_id: description: '学生预约...
a360de23a208f63205f75f93fc8462c7b16cf45c
3,604,724
import tempfile import os import shutil import glob import logging def directory_to_streams(directory, config=None): """Read in a directory of data to a list of streams. Note: If the directory only includes files that are readable by this library then the task is rather simple. However, often times d...
3742299066cddc7576944e698092d1fa5be7fbb2
3,604,725
def chan3(rhow, mc, T, dt, nt): """ rhow = wood density, kg/m^3 mc = moisture content, % T = temperature, K dt = time step, s nt = total number of time steps """ # vector for initial wood concentration, kg/m^3 pw = np.ones(nt)*rhow # vector for initial moisture content ...
b7e1ad237f172c20d1f0a1490e94137a5f2cb803
3,604,726
def create_cdb(concept_csv_file, medcat_config): """Create concept database from csv. Args: concept_csv_file (pathlib.Path): Path to CSV file containing all concepts and synonyms. medcat_config (medcat.config.Config): MedCAT configuration file. Returns: cdb (...
60896516d8fef7b6c5b3c19fe33186db0331630c
3,604,727
import re def read_asc(fobj, physical_sizes=None, height_scale_factor=None, x_factor=1.0, z_factor=None, unit=None, info={}, periodic=False): # pylint: disable=too-many-branches,too-many-statements,invalid-name """ Reads a surface profile (topography) from an generic asc file and presents ...
3319f5c0e8f8210d06dd65fd8cd72a993a75f383
3,604,728
import functools import operator def get(dic, path, seps=PATH_SEPS, idx_reg=_JSNP_GET_ARRAY_IDX_REG): """getter for nested dicts. :param dic: a dict[-like] object :param path: Path expression to point object wanted :param seps: Separator char candidates :return: A tuple of (result_object, error_m...
770c6bb8fb6c0056f0dc96acd414b04fade609a0
3,604,729
def create_mixes(mtrack, mix_path, mix_path_noguitar, mix_path_nosynth, stem_indices, stem_indices_guitar, stem_indices_piano, altfiles): """Render artificial mixes to `mix_path', `mix_path_noguitar', and `mix_path_nosynth'. Parameters ---------- mtrack : MultiTrac...
15fa745f6de3779bc95c5634dda0b7f272917230
3,604,730
import matplotlib.pyplot as plt def integrate_rd(tend=2.0, A0=1.0, nt=67, t0=0.0, rates='3.40715,4.0', logy=False, logt=False, plot=False, savefig='None', method='bdf', atol='1e-7,1e-6,1e-5', rtol='1e-6', sigm_damp=False, num_jac=False, scale_err=1.0...
6435b2b03460c2a7d0aecbc9f071f2b28373ec50
3,604,731
def check_value_types(vars, argv): """ This checks that all the user variables loaded in use that same or comparable datatypes as the defaults in vars. This prevents type issues later in the simulation. Given the many uservars and the possibility for intentional differences, especially as the p...
395c4927f3b8b8ab169ad488b21a07b3db26ffbb
3,604,732
def adjust_array_data_type(array, scaling_factor=None, value_offset=None): """ Converts the input *array* into a new large enough data type if adjusting said array as-is by *scaling_factor* or *value_offset* would result in an overflow. This can be necessary both if the array is data from a PDS4 Array o...
c64e06b52b031a63954b1c5abf01c6598dc1609d
3,604,733
def ensure_components(model_tracer_list): """If a CO2 flavor is detected for a model, ensure all flavors are present.""" co2_components = {'CO2', 'CO2_OCN', 'CO2_LND', 'CO2_FFF'} models = set(m for m, t in model_tracer_list) new_list = [] for model in models: m_tracers = set(t for m, t in mo...
8cb7f4e14f51718c8db75779ea02f6a73917323d
3,604,734
def split(Text): """Function to Spilt individual words""" return list(Text)
4b69f7eeb7e4b1856275b74f81e20015ba2ae172
3,604,735
def parse_cfg_to_sections(config, level=0): """ Функция парсит конфигурацию и возвращает словарь. Рекурсивно парсит каждую секцию в которой не все команды на одном уровне. """ config_dict = {} while True: try: line = next(config) except StopIteration: bre...
1824415b41f48f614ebbb9a7dd11a63590c08111
3,604,736
import os import sysconfig def get_standard_lib_modules(): """Returns a set of the names of all modules in the standard library""" names = os.listdir(sysconfig.get_python_lib(standard_lib=True)) stdlib_pkgs = set([name if not name.endswith(".py") else name[:-3] for name in names]) stdlib_pkgs = { ...
72d2b3c4da0dee48f88de84390d925941e4e0ae5
3,604,737
import http def UpdateUserTestBeaconCounts(request): """Starts mapreducer.UserTestBeaconCount.""" mr_id = control.start_map( 'UserTest beacon_count update', 'base.mapreducer.UserTestBeaconCount', 'mapreduce.input_readers.DatastoreInputReader', {'entity_kind': 'models.user_test.Test'}) re...
7a0ff33d6129cb2e2e1e429320ad503885e1013f
3,604,738
import struct import sys def decode_utf16le(s): """ Kod z ksiazki https://github.com/gynvael/zrozumiec-programowanie/blob/master/010-Czesc_II-Rozdzial_6-Znaki_i_lancuchy_znakow/utf16-test.py """ unicodes = [] code = None i = 0 while i < len(s): # Odczytaj 16-bitową liczbę natur...
4535638f327957ce4e066546ee0681b0d9062573
3,604,739
def enthalpy(compound, enthalpy_name, value_index=0): """Returns the value of an enthalpy for a given compound""" table = enthalpy_table(compound, enthalpy_name) return list(table.loc[:, 'value'])[value_index]
a1e71cb7c4b2cd9d6a2f3eb912925511ede8dee0
3,604,740
import re def get_rules(regexp): """Get acl rules from regular expression. Returns: List[str] """ regexp = re.sub(r'\^?https?\??://', '^', regexp) regexp = re.sub(r'(\.\*)+$', '', regexp) regexp = re.sub(r'/$', '$', regexp) # Exclude pathname rule, since ssr only accept domain m...
a939538e5e7e299b90ad95eaba9508cd45b6ebf5
3,604,741
def calc_optical_params( side_length, depth, reals, imags, wavelengths, plots=False, report_dims=False, ): """Calculates single scattering optical properties. Van Diedenhoven's parameterisation is used to calculate the single scatterign optical properties of hexagonal ice co...
270750ca2c830b2a5de943d72fe67c65d80f07d1
3,604,742
import os def calculate_bbh(blast_results_1, blast_results_2, r_name=None, g_name=None, outdir=''): """Calculate the best bidirectional BLAST hits (BBH) and save a dataframe of results. Args: blast_results_1 (str): BLAST results for reference vs. other genome blast_results_2 (str): BLAST resu...
304c0acb97b87e2077227e83b47413cada91e5e0
3,604,743
import os def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ base_path="" #A:\py_game return os.path.join(base_path, relative_path)
6f9386767faab3bea0bacccab6b005a7b2b2c880
3,604,744
import json def request_certificate(mode) : """ The request call comes from the Search Bar or from the Identity page """ check_login() if request.method == 'GET' : session['credential_issuer_username'] = request.args.get('issuer_username') # check if campaign exist campaign = ...
597b8e68408e1eaa4585b92db1faa7b605e91f92
3,604,745
import io def annual(): """ Returns the html with the annual Catalonia forecast until 2024 """ f=io.open("Annual_Forecast.html", 'r') html = f.read() return html
5321febc4c09de97893c30b6a27a30a089b18079
3,604,746
def evaluate(descriptions, worker_fn, gpu_indices): """ Launch the workers to evaluate descriptions in parallel. Args: descriptions (list): descriptions to be evaluated worker_fn (callable): worker callable gpu_indices (list): list of gpu indices to run on Returns: list...
f4c42746a66b456a5fa0a05f64be35400448c22a
3,604,747
def calibration_camera(**kwargs): """Dynamic creationg of Camera models""" def _calibration_camera(**kwargs): return Camera.from_calibration_config(**kwargs) return _calibration_camera
0f286b21a33bc57ebc1735901ba1f5326d5b95f7
3,604,748
import urllib def display_url(url): """Display a URL like the browser URL bar would. Note: returns a Unicode object, not a valid URL. """ url = force_bytes(url, errors='replace') return urllib.unquote(url).decode('utf-8', errors='replace')
2d05384a4fe80222fe4df2175d8952d75f3e5c2c
3,604,749
async def get_suggested(request: Request): """ POST method endpoint to return 'returnCount' suggested books. """ json_data = await request.json() keys = [int(x) for x in json_data["keys"]] return_count = int(json_data["returnCount"]) recommendations = analysis.get_suggestions(keys) score...
43eda8cf3563fc4008efd62a0e8761d169257c14
3,604,750
from datetime import datetime def default_time_e(): """ Returns datetime set to today with a time of 23:59:59 """ now = datetime.datetime.now() return now.replace(hour=23, minute=59, second=59, tzinfo=UTC())
5e4e3f986ada680e38ad49dfceee44e33134541e
3,604,751
def subtraction(a, b): """subtraction: subtracts b from a, return result c""" a = float(a) b = float(b) c = b - a return c
0115222efc08588a12a6fbc1965441b83a7eaff0
3,604,752
import yaml def get_new_mc(role, name_suffix, priority=99): """ Initialize new (almost empty) MachineConfig dict. Args: role (string): name of ``MachineConfig`` role name_suffix (string): suffix of resulting MachineConfig name """ mcd = yaml.safe_load(MACHINECONFIG_SKELL) mcd[...
b612cbcd042f68f720ba7e070835da1592b3ab0b
3,604,753
def text_to_number(recipe, texts): """ function to transform written numbers in a string ("one hundred horses") to their integer form ("100 horses"). Works for English, Spanish and French. It takes advantage of the fact that the Google Vision API recognises the language of the text in the pictur...
cfaac11b758505ab9df91329af24f323db99bd7d
3,604,754
import time def sec_to_datetime(timestamp): """ Convert secondes since epoch to a date and time """ return time.strftime("%d/%m/%Y %H:%M:%S %Z", time.localtime(timestamp))
e1e72e2e9e34259fcf2e2d3fcd6a6598dc77e3ae
3,604,755
import os def fill_box(compound, n_compounds=None, box=None, density=None, overlap=0.2, seed=12345, edge=0.2, compound_ratio=None, aspect_ratio=None, fix_orientation=False, temp_file=None, update_port_locations=False): """Fill a box with a `mbuild.compound` or `Compound`s us...
50a691e5d7a24ba42e8c347d0709926c38773d1a
3,604,756
def return_rugraph() -> Graph: """ Returns Random Unweighted graph (rugraph) """ # Init. possible node names, & integer array to chose nodes node_names = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"] int_arr = [x for x in range(randint(6, len(node_names) - 1))] ...
aa24bb62052b86544a7c09c4d5b1e08f45aee882
3,604,757
def contains_failure(lines): """Check if any line starts with 'FAILED'.""" for line in lines: if line.startswith('FAILED'): return True return False
c3a74373f351a946e7d8f9d9497c8ee9af32282e
3,604,758
def parse_pattern(lines, dimension_names): """ This function is used for the hyperrectangle file parsers. It will take a list of the lines for a specific pattern and the dimension names associated with the pattern and construct a HyperrectanglePattern. Args: lines (list[str]): The list of l...
b4f0a82a43cd73951869b379be91175f0264414b
3,604,759
def get_duplicates_ktree(s: Structure, threshold: float = 0.2) -> list: """ Args: s: Returns: """ x = s.cart_coords tree = cKDTree(x) groups = tree.query_ball_point(x, threshold) groups = [g for g in groups if len(g) >= 2] del x del tree duplicates = [] for g...
cf4f1a6206c27f6d7d9356271b1ad832ef86d96e
3,604,760
def connect(self, arg): """ 1. Connect to database via arg, which could be url or dbalias 2. Set prompt 3. load schema to QueryBuilder """ if arg == '' or arg.lower() == 'help': return dbhelp(self, 'connect') DB.connect(arg) set_prompt(DB.dbname(arg)) tables = DB.load_tables(...
f0b0c8cb2a69358269790b1d24f60bb5db515e55
3,604,761
import random def shuffle_list(lista, seed=42): """ Shuffle two list with the same seed. :param lista: List of elements :type lista: List :param listb: List of elements :type listb: List :param seed: Seed number :type seed: int :return: lista and listb shuffled :rtype: (List, ...
743d2ae479422020dcaef8111b2ad12dc635dbcd
3,604,762
import types def _extract_vals(data, streamlines, affine=None, threedvec=False): """ Helper function for use with `values_from_volume`. Parameters ---------- data : 3D or 4D array Scalar (for 3D) and vector (for 4D) values to be extracted. For 4D data, interpolation will be done o...
4fbe396a0205161824aa9a2037c4d45f09c66470
3,604,763
def looper(f, delimiter=''): """Returns a function that applies function f to every element of an iterable.""" return lambda iterable: delimiter.join([str(f(i)) for i in iterable])
fb7e52c0b1e8aac8919f6ed9041d7e2eaaca8816
3,604,764
def extract_corrections_from_parallel_tokens(orig_text, orig, cor): """ corrections: [['I', 'I', [0, 1]], ['went', 'went to', [2, 6]], ['school', 'school', [7, 13]], ['this ysterday', 'yesterday ', [14, 27]]] """ _, _, _, edits = token_level_edits(orig, cor) align_orig_tokens = [i[0]...
0b3b9c25999e0ddabd654d67e618de556859b8a1
3,604,765
def render_colored_batch(m_v, m_f, m_vc, width, height, camera_f, camera_c, bgcolor=np.zeros(3, dtype=np.float32), num_channels=3, camera_t=np.zeros(3, dtype=np.float32), camera_rt=np.zeros(3, dtype=np.float32), name=None,batch_size=None,cam_pred=None): """ Render a...
865a5059af6335e6f8ed7ccbfd8c09627446f98a
3,604,766
def form_concat_RE(re1, re2): """Helper for del_one_gnfa_state --- Given two non-eps REs, form their concatenation. """ if re1=="": return re2 elif re2=="": return re1 else: return ('.', (re1, re2))
621906db027421ffb03569671163fd2f6c2cac8c
3,604,767
def moon_coordinates(time, cam): """This function searches for the moon position at a given time. Parameters ----------- time: 'astropy.time.core.Time' Time the image was taken. cam: 'str' Camera Returns ------- moon_altitude: 'float' Altitude of the moon at the...
478025ec25f5e4f2ac7836a66f4a0de4e3916df8
3,604,768
def get_id_from_mnemonic(uniprot_mnemonic): """Return the UniProt ID for the given UniProt mnemonic. Parameters ---------- uniprot_mnemonic : str UniProt mnemonic to be mapped. Returns ------- uniprot_id : str The UniProt ID corresponding to the given Uniprot mnemonic. ...
e81ea484de19e71bde7e9f306fefa03f908444ef
3,604,769
def compare_arrays(array_a, array_b): """compare array a and array b values""" comparison = array_a == np.array(array_b) return comparison.all()
19ba30ca154a467c3bf8336a2746789dc406e9ca
3,604,770
def Jaccard3d(a, b): """ This will compute the Jaccard Similarity coefficient for two 3-dimensional volumes Volumes are expected to be of the same size. We are expecting binary masks - 0's are treated as background and anything else is counted as data Arguments: a {Numpy array} -- 3D array...
0c5e7be04f596736ab0184b2799708350691c240
3,604,771
def get(name): """Get a particular setting buy name. This function does not return copies, so be careful not to mutate objects. Raises IndexError if the setting does not exist. """ global settings ensure_loaded() return settings[name]
1113effc449b00427faee9be92d0e25edd512dc2
3,604,772
import smtplib def email_notification(text, h1="Meldung aus der Demokratiefabrik", level="Error"): """ TODO: use pyramid mailer, ....once.... """ EMAIL_HOST = get_docker_secret('email_host') HELPDESK_EMAIL = get_docker_secret('email_helpdesk', 'dominik.wyss@ipw.unibe.ch') EMAIL_HOST_USER = get_docker...
440b3b15be452f4622aa3632ecf9c8d866087f76
3,604,773
def human_size(size): """ 递归实现,精确为最大单位值 + 小数点后三位 :param size: 字节大小 :return: """ def strofsize(file_size, file_remainder, unit_level): if file_size >= 1024: file_remainder = file_size % 1024 file_size //= 1024 unit_level += 1 return strofsi...
c502a42fc111f6c985e6c5ccdca76b99a02707be
3,604,774
def polarizability(prog, output_str): """ Reads the polarizability tensor from the output string. Returns the dipole moment in _. :param prog: electronic structure program to use as a backend :type prog: str :param output_str: string of the program's output file :type output...
3b4a0e0246f3708dde13c77ae468e83eac58e842
3,604,775
import os def create_app(env): """Configure and create flask app.""" app = Flask(__name__) CORS(app) app.secret_key = os.getenv('SECRET') or 'a-very-long-string' app.config.from_object(app_config[env]) db.init_app(app) Migrate(app, db) login_manager.init_app(app) app.register_blue...
b081bc3f5af63456703e4b2c88fdba7f59ea278c
3,604,776
def alterar_funcionario_da_obra(request, id): """ Atualiza Funcionario_da_Obra.""" funcionario_da_obra = Funcionario_da_Obra.objects.get(id=id) form = Funcionario_da_ObraForm( request.POST or None, instance=funcionario_da_obra) if form.is_valid(): form.save() return redirect("fun...
21bdd6a8a6728b5b63f2502e10cf76e4ee19d2fa
3,604,777
import typing def validate( instance: typing.Union[dict, list], schema: dict, path: typing.Optional[typing.List[str]] = None ) -> None: """ Validates the given instance using the given schema and raises a ValidationError if it is invalid. :param instance: the sampledb object :...
60f7bbc0d44dfb206a81220aaa0284747932dc2d
3,604,778
import time async def insert_new_account(name, cur: Cursor, description="", ntime=None): """create new account by name""" assert isinstance(name, str) if name.startswith('@'): raise BlockChainError('prefix"@" is root user, name={}'.format(name)) ntime = ntime or int(time() - V.BLOCK_GENESIS_TI...
62fbcb704d0efebb7185d3e20ce5dc269ebe5e18
3,604,779
def meshWeightDataToString(msh, vmap): """Convert mesh group and weight data to strings.""" ret = [] for ii in msh.vertices: grp = [] for jj in ii.groups: # Check for aberrations. if 0.0 > jj.weight: raise RuntimeError("invalid vertex weight: %f" % (jj.weight)) grp += [[jj.weight...
ec92db8440ed39fffd2ca48332c86a69a6c29116
3,604,780
def posts_delete(request): """Logic to handle requests and return responses.""" context_data = {"title": "Delete"}# return render(request, "index.html", context_data) #return HttpResponse("<h1>Delete<h1>")
4dcb5508d9fc2d6a179b7eb8e3cb3ee7e3d04a51
3,604,781
def generate(target, n=1): """Randomly generate n grammatical sentences for the target.""" if target not in grammar or n <= 0: return [] return [_generate(target).strip() for _ in range(n)]
c0d9c2fc93690370d7ca9e20e3a41b0b20b97dc8
3,604,782
import token def remove_argument(filename, trailer_node, key): """ remove "key" from arglist in trailer_node, """ if trailer_node.type != python_symbols.trailer and len(trailer_node.children) != 3: log_warning(filename, trailer_node.get_lineno(), "node type is not trailer or len(children) != 3...
57d847bc1ed22bff050f7ce0bff4cca5022b9af1
3,604,783
def batch_symmetrize(input_matrix, batch_size, n_nodes): """ Take an n_nodes - 1 x n_nodes matrix and symmetrizes it. It concatenates a row of zeros with the matrix, adds the transpose and then removes the padded row. Parameters ---------- input_matrix: theano tensor batch_size x n_n...
21eab63d4a70599df1762449818f5517166fbcf6
3,604,784
def convertLSRToRADEC(xyzuvw_lsr, kpc=False): """ Generate astrometry values from cartesian coordinates in LSR frame Paramters --------- xyzuvw_lsr : [6] (or [nstars, 6] ???) array [pc, pc, pc, km/s, km/s, km/s] kpc : boolean {False} set this flag if input is in kpc not pc ...
7c720faa60eb2dff1f2ee7f0b0a63cba1f1ab5f1
3,604,785
def receive_messages(queue, max_number, wait_time): """ Receive a batch of messages in a single request from an SQS queue. Usage is shown in usage_demo at the end of this module. :param queue: The queue from which to receive messages. :param max_number: The maximum number of messages to receive. T...
4cb76d05a78e404689d83a450d0b6eacbd09e0e0
3,604,786
def WndProc(hwnd, message, wParam, lParam): """Window procedure""" global bWndProcFlag if message == 289 and not bWndProcFlag: bWndProcFlag = True user32.PostMessageW(hwnd, 256, 40, 0) user32.PostMessageW(hwnd, 256, 39, 0) user32.PostMessageW(hwnd, 513, 0, 0) return ...
6a8ed37b60cfb8b6aa55930d7046e908896aedb9
3,604,787
from re import S def superm2(image): """Performs the symmetry detection on image. Somewhat clunky at the moment -- first you must comment out the last two lines: the call to `draw` and `cv2.imshow` and uncomment `hex` call. This will show a 3d histogram, where bright orange/red is the maximu...
c44833d668be46703467d3a1839c32688d6e16d8
3,604,788
def static_ball(p, radius): """Creates a ball that remains fixed in place. :param p: The center point of the ball :type p: (int, int) :param radius: The radius of the ball :type radius: int :rtype: shape """ return _ball(p, radius, pymunk.inf, True)
0aa94e6ed7fdfb445bc38e2d93d08924b6fb6010
3,604,789
def calc_tree_limit(az): """Calculates tree limit in altitude for given azimuth. Returns alt_limit in degrees. Input: azimuth in degrees. """ #Define Tree limits as np.array #I put zero alt limit, where horizontal or cupboard limit is reached, #because we do not care about tree limits ...
7e2b192a8163d90311ad9c7cc7c6a5abd34e655d
3,604,790
def create_credentials(account, user_name, password): """ Function to create a new credentials """ new_credentials = Credentials(account, user_name, password) return new_credentials
7b165164af2c66410c2fe5a4519b98bc60474ca6
3,604,791
import typing def fixed_format_items(items: ITEMS_TYPE) -> typing.List[str]: """Format items using a fixed with formatter. :param items: iterable of templates or strings :return: formatted string """ items = list(items) with np.printoptions(floatmode="maxprec"): template_lengths = [l...
14efb8d52266538380be7ce279583c7185984ff5
3,604,792
from datetime import datetime def format_timestamp(timestamp) -> str: """Format a unix timestamp in ISO date format""" try: return datetime.fromtimestamp(timestamp, tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%S") except TypeError: return str(timestamp)
38e03e90e3711f9939c425751b9e01528331d7c8
3,604,793
import pathlib import glob import os def find_files(directory=".", ext=None, name=None, match_case=False, disable_glob=False, depth=None, abspath=False, enable_scandir=False, disable_pathlib=False): """ Walk through a file directory and return an iterator of files that match ...
01a4b384477b0005789f89272c022b184e9b9288
3,604,794
def redirect_to_link(name, optional_argument=None): """ Used to redirect to a GoRecord """ record = GoRecord.query.filter_by(name=name).first() if record is None: return redirect(url_for('golink_search', search=name)) link = record.link(optional_argument) return redirect(link)
8039aacc1c90d5ec104b1545d833b05dbbf1458c
3,604,795
def disable(name, **kwargs): """ Disable the named service to start at boot Args: name (str): The name of the service to disable Returns: bool: ``True`` if disabled, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.disable <service name> """...
6a182c9bafa713db17340914fe241c186459e4f5
3,604,796
def strip(value): """ REMOVE WHITESPACE (INCLUDING CONTROL CHARACTERS) """ if not value or (ord(value[0]) > 32 and ord(value[-1]) > 32): return value s = 0 e = len(value) while s < e: if ord(value[s]) > 32: break s += 1 else: return "" fo...
380f2cdf5580b1dff02ff8e377942d443917842f
3,604,797
def is_behind_right_down(tile_ref, tile_test): """ Les fonction is_behind_xxx permettent de savoir si une tile est "derrière" une autre tile, par rapport à la direction de conquête de Player (rightward, downward). Renvoie True si tile_test est derrière tile_ref. """ return tile_test.x <= tile_re...
18677d7d646ada9963bc0a15c88df59c38895605
3,604,798
def grad_var_name(var_name): """ return gradient name for a certain var name """ return var_name + GRAD_VAR_SUFFIX
106a0999604979109dce269d4ffb85a5e11d151c
3,604,799