content
stringlengths
22
815k
id
int64
0
4.91M
async def test_age_gate_error(): """ Should show the error message on incorrect input """ u = User(addr="27820001001", state=StateData(name="state_age_gate"), session_id=1) app = Application(u) msg = Message( content="invalid", to_addr="27820001002", from_addr="2782000100...
16,800
def load_config(filepath: str) -> DictStrAny: """Read config file. The config file can be in yaml, json or toml. toml is recommended for readability. """ ext = os.path.splitext(filepath)[1] if ext == ".yaml": with open_read_text(filepath) as fp: config_dict = yaml.load(fp.re...
16,801
def _expected_datatypes(product_type): """ Aux function. Contains the most current lists of keys we expect there to be in the different forms of metadata. """ if product_type == "SLC": # Only the datetimes need to be parsed. expected_dtypes = { "acquisition_start_utc": "pars...
16,802
def browser(): """The browser driver We launch the SHEBANQ site in preparation of doing many tests. We do not only deliver a driver, but also a wait object. """ with Safari() as driver: yield driver print("Closing test browser")
16,803
def convert_vecs_to_var( c_sys: CompositeSystem, vecs: List[np.ndarray], on_para_eq_constraint: bool = True ) -> np.ndarray: """converts hs of povm to vec of variables. Parameters ---------- c_sys : CompositeSystem CompositeSystem of this state. vecs : List[np.ndarray] list of v...
16,804
def run_tests(): """ This methods dinamically create tests based on the contents of the 'qgis' subfolder. The structure of files in the subfolder must be as follows: - For each dataset that you want to use, create a subfolder under 'qgis' - Add the layer file in that subfolder. It must be named ...
16,805
def test_validate_without_code(superuser, collection): """Attempt editing entry without a code.""" form = EditForm(superuser, collection.code, friendly_name='The old books', category='library') assert form.validate() is False assert _('This field is required.') in form.code.errors
16,806
def convert_CSV_into_df(file_loc): """ Generate Panda dataframe from CSV data (rotation and position). """ df = pd.DataFrame() for directory in glob.glob(file_loc): # Selecting all the folders in dataset directory. d = [] # Empty list....
16,807
def ziw2md(md_file, export_md_path, tmp_path, abs_img_path=False): """将.md.ziw文件转为标准md文件,导出图片和附件文件到本地目录""" ziw_zip = zipfile.ZipFile(md_file) ziw_zip.extractall(tmp_path) ziw_zip.close() print(f"正在转换《{md_file.stem}》……") export_md_file = export_md_path.joinpath(md_file.parent.stem, md_file.stem....
16,808
def timetable_to_subrip(aligned_timetable): """ Converts the aligned timetable into the SubRip format. Args: aligned_timetable (list[dict]): An aligned timetable that is output by the `Aligner` class. Returns: str: Text representing a SubRip file. """ #...
16,809
def add(a: T.Tensor, b: T.Tensor) -> T.Tensor: """ Add tensor a to tensor b using broadcasting. Args: a: A tensor b: A tensor Returns: tensor: a + b """ return a + b
16,810
def integrate(que): """ check if block nears another block and integrate them @param que: init blocks @type que: deque @return: integrated block @rtype: list """ blocks = [] t1, y, x = que.popleft() blocks.append([y, x]) if t1 == 2: blocks.append([y, x + 1]) elif ...
16,811
def handler(sig, frame) -> None: """Handles Ctrl+c by letting the Collector() know to shut down""" current_pid = os.getpid() if current_pid == parent_pid: reason = f"Received shutdown signal {sig}" log.debug(f"Parent caught signal {sig} - dispatching shutdown event") # Dispatch shutd...
16,812
def test_check_size_human_correct(docker_client, image_name): """Checks size with human readable limit.""" overflow = check_image_size(docker_client, image_name, '10 GiB') assert overflow < 0
16,813
def test_binary_query(cbcsdk_mock): """Testing Binary Querying""" called = False def post_validate(url, body, **kwargs): nonlocal called if not called: called = True assert body['expiration_seconds'] == 3600 else: assert body['expiration_seconds']...
16,814
def parse_struct_encoding(struct_encoding: bytes) -> typing.Tuple[typing.Optional[bytes], typing.Sequence[bytes]]: """Parse an array type encoding into its name and field type encodings.""" if not struct_encoding.startswith(b"{"): raise ValueError(f"Missing opening brace in struct type encoding: {struct_encoding!...
16,815
def split_train_crops(project_name, center, crops_dir='crops', subset=0.15, by_fraction=True, train_name='train', seed=1000): """ :param project_name: string Name of dataset. for example, set this to 'dsb-2018', or 'bbbc010-2012' :param center: string Set this to...
16,816
def _comp_point_coordinate(self): """Compute the point coordinates needed to plot the Slot. Parameters ---------- self : Slot19 A Slot19 object Returns ------- point_list: list A list of Points """ Rbo = self.get_Rbo() # alpha is the angle to rotate Z0 so ||Z1...
16,817
def getargspec(func): """Like inspect.getargspec but supports functools.partial as well.""" if inspect.ismethod(func): func = func.__func__ if type(func) is partial: orig_func = func.func argspec = getargspec(orig_func) args = list(argspec[0]) defaults = list(argspec[...
16,818
def empirical_kernel_fn(f: ApplyFn, trace_axes: Axes = (-1,), diagonal_axes: Axes = () ) -> EmpiricalKernelFn: """Returns a function that computes single draws from NNGP and NT kernels. Args: f: the function whose NTK we are computin...
16,819
def read_image_batch(image_paths, image_size=None, as_list=False): """ Reads image array of np.uint8 and shape (num_images, *image_shape) * image_paths: list of image paths * image_size: if not None, image is resized * as_list: if True, return list of images, else return np.ndarray ...
16,820
def dc_vm_backup(request, dc, hostname): """ Switch current datacenter and redirect to VM backup page. """ dc_switch(request, dc) return redirect('vm_backup', hostname=hostname)
16,821
def compute_total_distance(path): """compute total sum of distance travelled from path list""" path_array = np.diff(np.array(path), axis=0) segment_distance = np.sqrt((path_array ** 2).sum(axis=1)) return np.sum(segment_distance)
16,822
def get_relative_positions_matrix(length_x, length_y, max_relative_position): """Generates matrix of relative positions between inputs.""" range_vec_x = tf.range(length_x) range_vec_y = tf.range(length_y) # shape: [length_x, length_y] distance_mat = tf.expand_dims(range_vec_x, -1) - tf.expand_dims(...
16,823
def func_split_item(k): """ Computes the expected value and variance of the splitting item random variable S. Computes the expression (26b) and (26c) in Theorem 8. Remember that r.v. S is the value of index s such that $\sum_{i=1}^{s-1} w(i) \leq k$ and $\sum_{i=1}^s w(i) > k$. Args: k: Int. T...
16,824
def watch_less(): """watch less""" local('watchmedo shell-command --patterns="*.less" ' + "--recursive --command='lessc %s/web/static/style.less "%CURRENT_PATH + "> %s/web/static/style.css'"%CURRENT_PATH )
16,825
def eq(equation: str) -> int: """Evaluate the equation.""" code = compile(equation, "<string>", "eval") return eval(code)
16,826
def is_client_in_data(hass: HomeAssistant, unique_id: str) -> bool: """Check if ZoneMinder client is in the Home Assistant data.""" prime_config_data(hass, unique_id) return const.API_CLIENT in hass.data[const.DOMAIN][const.CONFIG_DATA][unique_id]
16,827
def parse_date(datestr): """ Given a date in xport format, return Python date. """ return datetime.strptime(datestr, "%d%b%y:%H:%M:%S")
16,828
def unconfigure_l2vpn_evpn(device): """ unconfig l2vpn evpn Args: device (`obj`): Device object Returns: None Raises: SubCommandFailure """ log.info( "Unconfiguring 'l2vpn evpn' globally" ) configs = [] configs.append("no ...
16,829
def generate_database(m, n, uni_range_low=None, uni_range_high=None, exact_number=False): """ - Generate Universe by picking n random integers from low (inclusive) to high (exclusive). If exact_number, then Universe.size == n - Generate a Database of m records, over the Universe """ # generat...
16,830
def interface_style(): """Return current platform interface style (light or dark).""" try: # currently only works on macOS from Foundation import NSUserDefaults as NSUD except ImportError: return None style = NSUD.standardUserDefaults().stringForKey_("AppleInterfaceStyle") if style ...
16,831
def get_num_forces(cgmodel): """ Given a CGModel() class object, this function determines how many forces we are including when evaluating the energy. :param cgmodel: CGModel() class object :type cgmodel: class :returns: - total_forces (int) - Number of forces in the coarse grained model ...
16,832
def cybrowser_dialog(id=None, text=None, title=None, url=None, base_url=DEFAULT_BASE_URL): """Launch Cytoscape's internal web browser in a separate window Provide an id for the window if you want subsequent control of the window e.g., via cybrowser hide. Args: id (str): The identifier for the new ...
16,833
def main(): """ Main function where you can test how VideoCameraServer works """ # Placing imports here so it will be imported only if user want to test algorithm, not when importing # Class DepthCameraServer import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import...
16,834
def initialize_stat_dict(): """Initializes a dictionary which will hold statistics about compositions. Returns: A dictionary containing the appropriate fields initialized to 0 or an empty list. """ stat_dict = dict() for lag in [1, 2, 3]: stat_dict['autocorrelation' + str(lag)] = [] stat_dict...
16,835
def nrrd_to_nii(file): """ A function that converts the .nrrd atlas to .nii file format Parameters ---------- file: tuples Tuple of coronal, sagittal, and horizontal slices you want to view Returns ------- F_im_nii: nibabel.nifti2.Nifti2Image A nifti file format that is...
16,836
def reqeustVerifyAuthhandler(request): """ 본인인증 전자서명을 요청합니다. - 본인인증 서비스에서 이용기관이 생성하는 Token은 사용자가 전자서명할 원문이 됩니다. 이는 보안을 위해 1회용으로 생성해야 합니다. - 사용자는 이용기관이 생성한 1회용 토큰을 서명하고, 이용기관은 그 서명값을 검증함으로써 사용자에 대한 인증의 역할을 수행하게 됩니다. """ try: # Kakaocert 이용기관코드, Kakaocert 파트너 사이트에서 확인 clientCode =...
16,837
def _file_name_to_valid_time(bulletin_file_name): """Parses valid time from file name. :param bulletin_file_name: Path to input file (text file in WPC format). :return: valid_time_unix_sec: Valid time. """ _, pathless_file_name = os.path.split(bulletin_file_name) valid_time_string = pathless_f...
16,838
def cidr_validator(value, return_ip_interface=False): """Validate IPv4 + optional subnet in CIDR notation""" try: if '/' in value: ipaddr, netmask = value.split('/') netmask = int(netmask) else: ipaddr, netmask = value, 32 if not validators.ipv4_re.ma...
16,839
def rh2a(rh, T, e_sat_func=e_sat_gg_water): """ Calculate the absolute humidity from relative humidity, air temperature, and pressure. Parameters ---------- rh: Relative humidity in Pa / Pa T: Temperature in K e_sat_func: func, optional Function to estimate the s...
16,840
def container(): """ Container management, type maple container --help for more info """ pass
16,841
def encoder_decoder_generator(start_img): """ """ layer1 = Conv2D(64, kernel_size=4, strides=2, activation='elu', padding='same')(start_img) layer2 = Conv2D(64, kernel_size=4, strides=2, activation='elu', padding='same')(layer1) layer3 = Conv2D(64, kernel_size=4, strides=1, activation='elu', paddin...
16,842
def off(): """ Turns the buzzer off (sets frequency to zero Hz) Returns: None """ return _rc.writeAttribute(OPTYPE.BUZZER_FREQ, [0])
16,843
def contentBrowser(*args, **kwargs): """ This command is used to edit and query a Content Browser. Returns: `string` The name of the panel """ pass
16,844
def data_preprocess(dataset, data_dir, dest_base_dir, predictor_path): """ Parameters ---------- dataset: str KDEF or Rafd, dataset names data_dir: str path to data directory to fetch images dest_base_dir: directory to store all outputs predictor_path: predictor for computing dlib landmarks Downl...
16,845
def generateLicence(expires, file=licenceFile, key=settings.SECRET_KEY, client=client, provider=provider, created=datetime.datetime.now()): """ Creates a licence file. Parameters: - expires (datetime): the licence expiration date. - file (string): the path to the licence file. - key (string)...
16,846
def ircelsos_data_dir(): """Get the data directory Adapted from jupyter_core """ home = os.path.expanduser('~') if sys.platform == 'darwin': return os.path.join(home, 'Library', 'ircelsos') elif os.name == 'nt': appdata = os.environ.get('APPDATA', os.path.join(home, '.local', '...
16,847
def get_shodan_dicts(): """Build Shodan dictionaries that hold definitions and naming conventions.""" risky_ports = [ "ftp", "telnet", "http", "smtp", "pop3", "imap", "netbios", "snmp", "ldap", "smb", "sip", "rdp", ...
16,848
def safe_download(f): """ Makes a download safe, by trapping any app errors and redirecting to a default landing page. Assumes that the first 2 arguments to the function after request are domain and app_id, or there are keyword arguments with those names """ @wraps(f) def _safe_download(...
16,849
def Moebius(quaternion_or_infinity, a,b=None,c=None,d=None): """ The Moebius transformation of a quaternion (z) with parameters a,b,c and d >>> import qmath >>> a = qmath.quaternion([1,1,1,0]) >>> b = qmath.quaternion([-2,1,0,1]) >>> c = qmath.quaternion([1,0,0,0]) >>> d = qmath....
16,850
def init_full_x(setup_pickleddb_database, monkeypatch): """Init original experiment""" monkeypatch.chdir(os.path.dirname(os.path.abspath(__file__))) name = "full_x" orion.core.cli.main( ( "hunt --init-only -n {name} --config orion_config.yaml ./black_box.py " "-x~uniform(...
16,851
def _passthrough_zotero_data(zotero_data): """ Address known issues with Zotero metadata. Assumes zotero data should contain a single bibliographic record. """ if not isinstance(zotero_data, list): raise ValueError('_passthrough_zotero_data: zotero_data should be a list') if len(zotero_d...
16,852
def telebot(): """endpoint responsible to parse and respond bot webhook""" payload = json.loads(request.data) message = payload.get('message', payload.get('edited_message','')) msg_from = message.get('from') user_id = msg_from.get('id') user_first_name = msg_from.get('first_name','') user_la...
16,853
def pkg_config(cfg): """Returns PkgConfig pkg config object.""" pkg_config_py = os.path.join(get_vta_hw_path(), "config/pkg_config.py") libpkg = {"__file__": pkg_config_py} exec(compile(open(pkg_config_py, "rb").read(), pkg_config_py, "exec"), libpkg, libpkg) PkgConfig = libpkg["PkgConfig"] retu...
16,854
def run(*options, cfg=None, debug=False): """Run training and validation of model Notes: Options can be passed in via the options argument and loaded from the cfg file Options from default.py will be overridden by options loaded from cfg file Options from default.py will be overridden b...
16,855
def main_xss(start_url, proxy=None, agent=None, **kwargs): """ main attack method to be called """ tamper = kwargs.get("tamper", None) verbose = kwargs.get("verbose", False) batch = kwargs.get("batch", False) force = kwargs.get("force_ssl", False) question_msg = ( "it appears th...
16,856
def _np_copy(a, out=None): """ Return an array copy of the given object. Parameters ---------- a : ndarray Input data. out : ndarray or None, optional Alternative output array in which to place the result. It must have the same shape and dtype as the expected output. ...
16,857
def root(tmpdir): """Return a pytest temporary directory""" return tmpdir
16,858
def _check_storage(log_fn: tp.Callable) -> bool: """See if the storage system is alive.""" from app.crud.core import ready try: log_fn('Attempting to contact storage system', depth=1) result = ready() return result except Exception as ex: log_fn(ex, level=logging.WARN, d...
16,859
def ignore_ip_addresses_rule_generator(ignore_ip_addresses): """ generate tshark rule to ignore ip addresses Args: ignore_ip_addresses: list of ip addresses Returns: rule string """ rules = [] for ip_address in ignore_ip_addresses: rules.append("-Y ip.dst != {0}".fo...
16,860
def readmission(aFileName): """ Load a mission from a file into a list. The mission definition is in the Waypoint file format (http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format). This function is used by upload_mission(). """ print "\nReading mission from file: %s"...
16,861
def remove_stop_words(words): """Remove all stop words. Args: words (list): The list of words Returns: list: An updated word list with stopwords removed. """ # http://stackoverflow.com/questions/5486337/ # how-to-remove-stop-words-using-nltk-or-python return [w for w in wor...
16,862
def plotSpikes(spkt,spkid=0,newFigure=False,color='b'): """Plot spikes instants.""" start_plot = time.time() doPlot = False #if len(spkt[:,:]) > 0: print "\n Plotting Raster..." if newFigure: plt.figure() if len(spkt.shape)==2 and spkid==0: try: for i in range(le...
16,863
def table_triples(tables, include_type=True): """Make triples based on table predictions""" for table in tables: table["triples"] = list(triples.yield_triples(table, include_type=True)) yield table
16,864
def task_gather_quiver(self): """We wrote the "gathered" files during task construction. """ job_done_fn = fn(self.job_done) touch(job_done_fn)
16,865
def synthetic_costs_1(): """ Uncertainty in 5 points at [0,0] on X1 can cause it to flip to [1,0] if needed to misclassify Uncertainty in 1 point at [1,1] on X2 can cause it to flip to [1,0] if needed to misclassify All other points certain """ costs = np.array([[1,4],[1,4],[...
16,866
def task(ctx, config): """ Run all cram tests from the specified paths on the specified clients. Each client runs tests in parallel. Limitations: Tests must have a .t suffix. Tests with duplicate names will overwrite each other, so only the last one will run. For example:: tasks: ...
16,867
def example_one(request, context=None): """ Return web page for example one. """ if context is None: context = {} session = request.session.get("ApiSession", None) if session is None: return no_session_set(request) session = Session.deserialize(session) origin_codes = get_codes...
16,868
def decode(cls: Any, value: bytes) -> Any: """Decode value in katcp message to a type. If a union type is provided, the value must decode successfully (i.e., without raising :exc:`ValueError`) for exactly one of the types in the union, otherwise a :exc:`ValueError` is raised. Parameters ------...
16,869
def ensure_parent(path): """Ensure that the parent directory of the given path exists. """ parent = os.path.dirname(path) if parent and not os.path.exists(parent): os.makedirs(parent)
16,870
def test_HarSanitizer_load_wordlist(): """Test successful HarSantizer.load_wordlist()""" hs = HarSanitizer() word_list = hs.load_wordlist(wordlist=['word1', u'word2', 'word3']) assert isinstance(word_list, list) assert word_list[2] == "word3"
16,871
def load_f0(fhandle: TextIO) -> annotations.F0Data: """Load an ikala f0 annotation Args: fhandle (str or file-like): File-like object or path to f0 annotation file Raises: IOError: If f0_path does not exist Returns: F0Data: the f0 annotation data """ lines = fhandle.r...
16,872
def excepthook(exc_type, exc_value, exc_traceback): """Handle unhandled exceptions, default exception hook.""" if isinstance(exc_value, OSError): # Handle OSError differently by giving more details. message = ( f'Error inesperado del sistema operativo.\n' '[' ...
16,873
def media_to_csv(media: Union[List[Media], Movie, LimitedSeries, Podcast, TVShow]): """Exports the specified media into a CSV file :param media: The Media object to convert into CSV """ __media_to(media, as_csv=True)
16,874
def remove_fallen(lst): """removes fallen orcs from a list""" return [x for x in lst if x.standing]
16,875
def register(linter): """required method to auto register this checker""" linter.register_checker(ExceptionsChecker(linter))
16,876
def gc_resnet152(num_classes): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(GCBottleneck, [3, 8, 36, 3], num_classes=num_classes) model.avgpool = nn.AdaptiveAvgPool2d(1) return model
16,877
def consume_entropy(generated_password: str, quotient: int, max_length: int) -> str: """ Takes the entropy (quotient) and the length of password (max_length) required and uses the remainder of their division as the index to pick a character from the characters list. This process occurs recursively ...
16,878
def randomNormal(n, height, baseshape=[]): """ Generate random positions, normally distributed along z. Base shape can be: [] (1D sim) [Ly] (2D sim) [Lx, Ly] (3D sim) Where Lx, Ly are lengths along x, y. """ nDim = len(baseshape) + 1 pos = np.zeros([n,...
16,879
def index(model_name=None): """ Index page. """ registered_models = mdb.registered_models if model_name: model = next((m for m in registered_models if m.__name__.lower() == model_name.lower()), None) elif registered_models: model = registered_models[0] if not model: a...
16,880
def download(names, tempdir=None, extra_args=None): """Gather pip packages in `tempdir` Arguments: names (list): Names of packages to install, in pip-format, e.g. ["six==1"] tempdir (str, optional): Absolute path to where pip packages go until they've been installed as R...
16,881
def _parseCellContentsSection(fileAsList, lineIdx): """ returns fractCoords from Cell Contents section of castep Args: fileAsList(str list): Each entry is 1 line of the castep input file lineIdx(int): The index containing the line "cell contents" Returns fractCoords: nx4 iter with each contain...
16,882
def dev_update(obj, directory): """Update plugin parts which have changed since previous update. Optionally pass in the DIRECTORY of the plugin (defaults to cwd). """ directory = Path(directory) plugin_toml_path = directory / "plugin.toml" if not plugin_toml_path.exists(): lib.log_erro...
16,883
def write_tester(format, layer, out_file): """Write plate with these keys to this file.""" plato = FORMAT_CLASSES[format]( out_file, width_in_units=15, height_in_units=2, unit_mm=19, case_thickness=3.5, padding=1, corner_radius=2, kerf=0.18) plato.draw_outside() for i in range(15...
16,884
def get_avg_no_of_feat_values(contents): """ Helper to calculate numbers of different values of categorical features, averaged for all features """ total = 0 for i in range(0, len(contents[0])): total += len(set([x[i] for x in contents])) return float(total) / float(len(contents[0])...
16,885
def plot_trend_line(axes_, xd, yd, c='r', alpha=1, cus_loc = None, text_color='black', return_params=False, extra_text='', t_line_1_1=True, fit_function=None, fontsize_=12, add_text=True): """Make a line of best fit""" #create clean series x_, y_ = coincidence(xd,yd) if fi...
16,886
def get_oil_type_atb( oil_attrs, origin, destination, transport_data_dir, random_generator ): """Randomly choose type of cargo oil spilled from an ATB (articulated tug and barge) based on AIS track origin & destination, and oil cargo attribution analysis. Unlike traditional tank barges, the vessels wit...
16,887
def get_jwt(): """ Get Authorization token and validate its signature against the application's secret key, . """ expected_errors = { KeyError: WRONG_PAYLOAD_STRUCTURE, AssertionError: JWK_HOST_MISSING, InvalidSignatureError: WRONG_KEY, DecodeError: WRONG_JWT_STRUCTU...
16,888
def start_volume(name, force=False): """ Start a gluster volume name Volume name force Force the volume start even if the volume is started .. versionadded:: 2015.8.4 CLI Example: .. code-block:: bash salt '*' glusterfs.start mycluster """ cmd = "volu...
16,889
def hist_equal(img, z_max=255): """ 直方图均衡化,将暗的地方变量,亮的地方变暗 :param img: :param z_max: 原图像最亮的地方减去最暗的地方的值 :return: """ if len(img.shape) == 2: height, width = img.shape n_chan = 1 elif len(img.shape) == 3: height, width, n_chan = img.shape print(img[:, :, 0].s...
16,890
def combine(*indices_lists): """ Return all the combinations from lists of indices :param indices_lists: each argument is a list of indices (it must be a list) :return: The combined list of indices """ if len([*indices_lists]) > 1: return [i for i in product(*indices_lists)] else: ...
16,891
def get_endpoint(query): """ Regex to parse domain and API endpoint from a SoQL query via FROM statement :param query: str, SoQL-formatted query :return url, endpoint, query: str objects, domain, endpoint, and original query sans FROM statemen...
16,892
def load_data(filename: str) ->pd.DataFrame: """ Load house prices dataset and preprocess data. Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector (prices) - either as a single DataFrame or a Tuple[DataFrame, Se...
16,893
def expect_returns( signature: Signature, *types: Optional[Type], allow_unannotated: bool = True, ): """ Check if the function signature returns one of the given types """ if signature.return_annotation == Signature.empty: if not allow_unannotated: raise InvalidReturnType...
16,894
def version_match(required, candidate): """Test that an available version is a suitable match for a required version. To be suitable a version must be of the same major version as required and be at least a match in minor/patch level. eg. 3.3 is a match for a required 3.1 but 4.1 is not. :par...
16,895
def get_last_upgraded_at(module: base.Module) -> Optional[datetime.datetime]: """ Get the timestamp of the last time this module was upgraded. """ return settings.get_last_upgraded_at(module.name)
16,896
def parse_header_file(header_file): """Parse a single header file to get all defined constants out of it.""" resolved_values = collections.OrderedDict() raw_matches = {} with open(header_file, "r") as fd: all_file_lines = collections.OrderedDict( [ (lineno, line.stri...
16,897
def get_linux_distribution(get_full_name, supported_dists): """Abstract platform.linux_distribution() call which is deprecated as of Python 3.5 and removed in Python 3.7""" try: supported = platform._supported_dists + (supported_dists,) osinfo = list( platform.linux_distributi...
16,898
def update( name: str, git: bool = False, local: bool = False, url: str = "", head: str = "", tag: str = "", commit_hash: str = "", location: str = "", ): """Update a package """ target_location = ".refl" p = Project.load("project.refl") dependencies = [x for x in p.project.dependencies if x....
16,899