content
stringlengths
22
815k
id
int64
0
4.91M
def register_error(self, name, error): """ During development we track errors in the cache. This could be moved inside a class later. """ if 'errors' not in self.cache: self.cache['errors'] = {} self.cache['errors'][name] = error
5,348,100
def test_frozen(): """Test `frozen`.""" f = _frozen.frozen # -------------- # check has all constants assert f.__all_constants__ == data.__all_constants__ # -------------- # check equality C = data.read_constants() name: str for name in data.__all_constants__: assert ...
5,348,101
def get_spot_market_price(facility: Optional[str] = None, plan: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSpotMarketPriceResult: """ Use this data source to get Packet Spot Market Price. ## Example Usage ```pyt...
5,348,102
def _get_cluster_id(emr: boto3.client("emr"), clusterName: str) -> str: """ Returns the id of a running cluster with given cluster name. """ clusters = emr.list_clusters()["Clusters"] # choose the correct cluster clusters = [c for c in clusters if c["Name"] == clusterName and c["Status"]["State...
5,348,103
def seed_student(request, i): """Returns the properties for a new student entity. """ gsoc2009 = Program.get_by_key_name('google/gsoc2009') user = User.get_by_key_name('user_%d' % i) if not gsoc2009: raise Error('Run seed_db first') if not user: raise Error('Run seed_many for at least %d ...
5,348,104
def add_parm_value_multiplier(kwargs, add_exponent=False): """Adds a value/multipler parameter pair to the specified parameter. (Called from PARMmenu.xml) """ p = kwargs['parms'][0] try: n = p.node() v = p.eval() t = p.parmTemplate() g = n.parmTemplateGroup() ...
5,348,105
def get_route(routes): """ Запросить данные о маршруте. """ destination = input("Пункт назначения? ") number = input("Номер поезда? ") time = input("Время отправления?(формат чч:мм) ") route = { 'destination': destination, 'number': number, 'time': time } rou...
5,348,106
def apply(effect: List[float], signal: List[float]): """Given effect interpolated to length of given signal. Args: effect: effect to interpolate to signal length. signal: length of which effect is interpolated to. """ max_len = max(len(effect), len(signal)) # Signal indices to effe...
5,348,107
def cli_cosmosdb_sql_trigger_update(client, resource_group_name, account_name, database_name, container_name, trigger_name, ...
5,348,108
def evaluate_features(features: np.ndarray, labels: np.ndarray, train_frac: float = 0.8) -> List[int]: """ Evaluates the marginal impact of each feature in the given array (by retraining). Args: features: A [N, T, D] array of input features for each sequence element labels: A [N] array of l...
5,348,109
def pad_for_tpu(shapes_dict, hparams, max_length): """Pads unknown features' dimensions for TPU.""" padded_shapes = {} def get_filler(specified_max_length): if not specified_max_length: return max_length return min(specified_max_length, max_length) inputs_none_filler = get_filler(hparams.max_inp...
5,348,110
def sample(x_axes, y_axes) -> None: """ Basic Sample File """ if not isinstance(x_axes, int): print("Please enter a number for the X axis") sys.exit() if not isinstance(y_axes, int): print("Please enter a number for the Y axis") sys.exit() try: cam = cv2....
5,348,111
def test_logrotate_binary_file(host): """ Tests if logrotate binary is a file type. """ assert host.file(PACKAGE_BINARY).is_file
5,348,112
def _get_child_query_node_and_out_name( ast: Union[FieldNode, InlineFragmentNode], child_type_name: str, child_field_name: str, name_assigner: IntermediateOutNameAssigner, ) -> Tuple[SubQueryNode, str]: """Create a query node out of ast, return node and unique out_name on field with input name. ...
5,348,113
def test_call(paired_inputs_v0, group_v0, kernel_ak_v0): """Test call.""" inputs_0 = paired_inputs_v0[0] inputs_1 = paired_inputs_v0[1] kernel = kernel_ak_v0 outputs = kernel([inputs_0, inputs_1, group_v0]) desired_outputs = np.array([ 0.4206200260541147, 0.4206200260541147, ...
5,348,114
def has_balanced_parens(exp: str) -> bool: """ Checks if the parentheses in the given expression `exp` are balanced, that is, if each opening parenthesis is matched by a corresponding closing parenthesis. **Example:** :: >>> has_balanced_parens("(((a * b) + c)") False :par...
5,348,115
def _is_binary(c): """Ensures character is a binary digit.""" return c in '01'
5,348,116
def get_interface_ib_name(hosts, interface, verbose=True): """Get the InfiniBand name of this network interface on each host. Args: hosts (NodeSet): hosts on which to detect the InfiniBand name interface (str): interface for which to obtain the InfiniBand name verbose (bool, optional): ...
5,348,117
def merge(files_in, file_out, delete_files_in=False): """ Merges several alignment files (cesAlign format) into a single alignment file :param files_in: the input files :param file_out: the output file, with all alignments merged into one file :param delete_files_in: whether or not to delete the inp...
5,348,118
def _get_script(args_file): """compiled contents of script or error out""" DEFAULT_SCRIPT = 'build.jfdi' script_path = None if args_file != None: script_path = args_file elif os.path.exists(DEFAULT_SCRIPT): script_path = DEFAULT_SCRIPT script_path = None if os.path....
5,348,119
def render(img, result, classes=None, score_thr=None, show=True, wait_time=0, path=None): """Visualize the detection on the image and optionally save to a file. Args: img(BGR): CV2 BGR. result(Tensor[K, 6] or List[(tid, Tens...
5,348,120
def check_python_import(package_or_module): """ Checks if a python package or module is importable. Arguments: package_or_module -- the package or module name to check Returns: True or False """ logger = logging.getLogger(__name__) logger.debug("Checking python import '%s'....
5,348,121
def read_frame_positions(lmp_trj): """ Read stream positions in trajectory file corresponding to time-step and atom-data. """ ts_pos, data_pos = [], [] with open(lmp_trj, 'r') as fid: while True: line = fid.readline() if not line: break ...
5,348,122
async def async_setup_entry(hass, config_entry): """Set up Enedis as config entry.""" hass.data.setdefault(DOMAIN, {}) pdl = config_entry.data.get(CONF_PDL) token = config_entry.data.get(CONF_TOKEN) session = async_create_clientsession(hass) enedis = EnedisGateway(pdl=pdl, token=token, session=...
5,348,123
def get_file_list(prefix): """ Get file list from http prefix """ print("Fetching file list from", prefix) k = requests.get(prefix) if not k.ok: raise Exception("Unable to get http directory listing") parser = HRefParser() parser.feed(k.content.decode()) k.close() return par...
5,348,124
def train_model(model: nn.Module, trainDataLoader: DataLoader, testDataLoader: DataLoader, epochs: int, optimizer, lossFuction, metric, device) -> dict: """ Training model function: it will train the model for a number of epochs, with the corresponding optimizer. It will return the corresponding losses an...
5,348,125
def _has_profile(): """Check whether we have kernprof & kernprof has given us global 'profile' object.""" return kernprof is not None and hasattr(builtins, 'profile')
5,348,126
def get_video_info(url): """ adapted from https://www.thepythoncode.com/article/get-youtube-data-python Function takes a YouTube URL and extracts the different parts of the video: title, view number, description, date-published, likes, dislikes, channel name, channel url, and channel subscr...
5,348,127
def routing_tree_to_tables(routes, net_keys): """Convert a set of :py:class:`~rig.place_and_route.routing_tree.RoutingTree` s into a per-chip set of routing tables. .. warning:: A :py:exc:`rig.routing_table.MultisourceRouteError` will be raised if entries with identical keys and masks b...
5,348,128
def extract_response_objects(image_file, mask_file, stim_file, input_dict): """inputs are file names for aligned images, binary mask, and unprocessed stimulus file outputs a list of response objects""" # read files I = read_tifs(image_file) mask = read_tifs(mask_file) labels = segment_ROIs(mask) ...
5,348,129
def get_top_diff_loc(imgs, ref_imgs, crop_size, grid_size, device, topk=10): """Randomly get a crop bounding box.""" assert imgs.shape == ref_imgs.shape batches = imgs.size(0) img_size = imgs.shape[2:] crop_size = _pair(crop_size) grid_size = _pair(grid_size) stride_h = (img_size[0] - crop_s...
5,348,130
def decode(file): """ This function creates a dictionnary out of a given file thanks to pre-existing json functions. :param file: The file to decode. :return: The corresponding Python dictionnary or None if something went wrong (i.e: the given file \ is invalid). """ # Json to diction...
5,348,131
def kron_compact(x): """Calculate the unique terms of the Kronecker product x ⊗ x. Parameters ---------- x : (n,) or (n,k) ndarray If two-dimensional, the product is computed column-wise (Khatri-Rao). Returns ------- x ⊗ x : (n(n+1)/2,) or (n(n+1)/2,k) ndarray The "compact"...
5,348,132
def record_speech_sequentially(min_sound_lvl=0.01, speech_timeout_secs=1.): """Records audio in sequential audio files. Args: min_sound_lvl: The minimum sound level as measured by root mean square speech_timeout_secs: Timeout of audio after that duration of silence as measured by min_sound_lvl ...
5,348,133
def test_ga_sync_sample(ga_config: Optional[dict]): """Test class creation.""" tap = SampleTapGoogleAnalytics(config=ga_config, parse_env_config=True) tap.sync_all()
5,348,134
def test_charsets_attribute_warning(attributes, warning): """Validates the warning message displayed for charset attribute in anchor tag. """ with warnings.catch_warnings(record=True) as expected_warning: A(**attributes) assert len(expected_warning) == 1 assert issubclass(expected_warni...
5,348,135
def home(): """ Display Hello World in a local-host website """ return 'Hello World'
5,348,136
def build_cinder(args): """Build the cinder client object.""" (os_username, os_password, os_user_domain_name, os_auth_url, os_auth_type, os_region_name, os_project_name, os_project_id, os_project_domain_name, os_project_domain_id, os_region_name, os_user_domain_...
5,348,137
def harvest_channel(channel, start_date, end_date, exclude_nicks=None, exclude_posts=None): """Pull all matching irc posts :param channel: the irc channel to search :param start_date: the starting date of irc entries :param end_date: the ending date of irc entries :p...
5,348,138
def selecaoEscalar(Mcorr, criterios, N=0, a1=0.5, a2=0.5): """ Performs a scalar feature selection which orders all features individually, from the best to the worst to separate the classes. INPUTS - Mcorr: Correlation matrix of all features. - criterios: - N: Number of best features to be returned. - a1: Weig...
5,348,139
def sum_by_letter(list_of_dicts, letter): """ :param list_of_dicts: A list of dictionaries. :param letter: A value of the letter keyed by 'letter'. """ total = 0 for d in list_of_dicts: if d['letter'] == letter: total += d['number'] return total
5,348,140
def gate_settle(gate): """ Return gate settle times """ return 0
5,348,141
def parse_csr_domains(csr_pem=None, csr_pem_filepath=None, submitted_domain_names=None): """ checks found names against `submitted_domain_names` This routine will use crypto/certbot if available. If not, openssl is used via subprocesses `submitted_domain_names` should be all lowecase """ l...
5,348,142
def test(name=None): """ Args: name (str): The name of the test (the string after 'test_'). When a name isn't specified all tests will be done. """ if name: assert(run('python tests/test_%s.py' % name) == 0) else: devLinks.clear() # clear all the dev links to avoid module mixing install() ...
5,348,143
def fov_gc(lons, lats): """Field of view great circle. Properties ---------- lons: [float] Field of view longitudes (degE). lats: [float] Field of view latitudes (degN). Return ------ geojson.Feature GeoJSON field of view polygon. """ return geo_polygon...
5,348,144
def return_covid_data() -> tuple[dict, dict]: """A function that acts as a getter method, allowing for functions in main to get the national and local COVID data and then display the values on the dashboard. Returns: tuple: (england_data, local_data). A tuple of two values (England and ...
5,348,145
def request_publication(request, name): """Request publication by RFC Editor for a document which hasn't been through the IESG ballot process.""" class PublicationForm(forms.Form): subject = forms.CharField(max_length=200, required=True) body = forms.CharField(widget=forms.Textarea, require...
5,348,146
def start(connection) -> None: """Start the local websever for auth callbacks.""" # Allow Ctrl-C break signal.signal(signal.SIGINT, signal.SIG_DFL) global SERVER, CON CON = connection app = bottle.app() try: SERVER = MyWSGIRefServer(host="localhost", port=5000) app.run(serv...
5,348,147
def def_op_rdf_header(): """eReefs legacy WQ def Test for redirection based on header content type """ source = "http://environment.data.gov.au/def/op" target = "http://sissvoc.ereefs.info/repo/vocab/op.rdf" r = requests.get( source, headers={"Accept": "application/rdf+xml"}, allow_redir...
5,348,148
def strip_trailing_characters(unstripped_string, tail): """ Strip the tail from a string. :param unstripped_string: The string to strip. Ex: "leading" :param tail: The trail to remove. Ex: "ing" :return: The stripped string. Ex: "lead" """ if unstripped_string.endswith(str(tail)): ...
5,348,149
def is_prime(x): """ Prove if number is prime """ if x == 0 or x == 1: return 0 for i in range(2, x//2 +1): if x % i == 0: return 0 return 1
5,348,150
def test_boundary_inversion(reparameterisation, is_invertible, boundary_inversion): """Test the different options for rescale to bounds""" reparam = reparameterisation({'boundary_inversion': boundary_inversion}) assert is_invertible(reparam)
5,348,151
def obj_to_str(obj, encoding='utf8') -> str: """ Examples: >>> d = dict(a=1, b=2) >>> assert isinstance(obj_to_str(d), str) """ b = pickle.dumps(obj) return bytes_to_str(b, encoding=encoding)
5,348,152
def deploy_sqlfiles(engine: Engine, directory: str, message: str, display_output: bool = False, scripting_variables: dict = None) -> bool: """Run every SQL script file found in given directory and print the executed file names. If any file in directory cannot be deployed after multiple tries, raise an exeption...
5,348,153
def compare_methode_corpus(corpus): """la fonction pour la comparaison entre Bleu score et la distance d'édition au niveu des directions entieres """ list_DA_corpus=[] list_bleu_corpus=[] list_DIST_corpus=[] list_bleu_corpus_z=[] list_DIST_corpus_z=[] list_bleu_corpus_scale=[] list_DIST_corpus_scale=[] list_...
5,348,154
def sample_ellipsoid(p0, covmat, size=1): """ Produce an ellipsoid of walkers around an initial parameter value, according to a covariance matrix. :param p0: The initial parameter value. :param covmat: The covariance matrix. Must be symmetric-positive definite or it will raise the ...
5,348,155
def test_index_name_none(df): """Test expand_grid output for a pandas Index without a name.""" A = pd.Index(df["a"].array, name=None) B = df["cities"] others = {"A": A, "B": B} result = expand_grid(others=others) A = df.loc[:, ["a"]] B = df.loc[:, ["cities"]] expected = A.assign(key=1).m...
5,348,156
def test_gaussian_blur(): """ Feature: Test image gaussian blur. Description: Add gaussian blur to image. Expectation: success. """ context.set_context(mode=context.GRAPH_MODE, device_target="CPU") image = np.random.random((32, 32, 3)) trans = GaussianBlur(ksize=5) dst = trans(image)...
5,348,157
def avg_pool_2d(x, size=(2, 2), stride=(2, 2), name='avg_pooling', padding='VALID'): """ Average pooling 2D Wrapper :param x: (tf.tensor) The input to the layer (N,H,W,C). :param size: (tuple) This specifies the size of the filter as well as the stride. :param name: (string) Scope na...
5,348,158
def train_eval(arg_params): """ A simple train and eval for PPO agent :param arg_params: parsed command-line arguments :return: """ """ initialize distribution strategy use_gpu=False means use tf.distribute.get_strategy() which uses CPU use_gpu=True mean use tf.dist...
5,348,159
def patch_base_handler(BaseHandler, log=None): """Patch HubAuthenticated into a base handler class so anything inheriting from BaseHandler uses Hub authentication. This works *even after* subclasses have imported and inherited from BaseHandler. .. versionadded: 1.5 Made available as an importa...
5,348,160
def get_username_field() -> str: """Get custom username field. Returns: str: username field. """ from django.contrib.auth import get_user_model user_model = get_user_model() return getattr(user_model, "USERNAME_FIELD", "username")
5,348,161
def get_edited_file_name(): """ Gets the current open file in xcode """ script = ''' tell application "Xcode" set last_word_in_main_window to (word -1 of (get name of window 1)) set current_document to document 1 whose name ends with last_word_in_main_window set current_d...
5,348,162
def p_metadata(p): """metadata : '(' metadata_seq ')' |""" if len(p) > 2: p[0] = p[2] else: p[0] = []
5,348,163
def get_header(yaml_dict): """ Header merely comprises the access token :return: """ headers = {"Authorization": "Bearer {}".format(get_access_token(yaml_dict)), "Content-Type": "application/json"} return headers
5,348,164
def change_filename_extension(filename: str, old_ext: str, new_ext: str) -> str: """ Change extension of a filename (e.g. "data.csv" to "data.json"). :param filename: the old filename (including extension) :param old_ext: the extension of the old filename :param new_ext: the extension to replace th...
5,348,165
def parseArgPairToBoundaryArray(pair, mesh): """ Parse boundary related pair argument to create a list of [ :gimliapi:`GIMLI::Boundary`, value|callable ]. Parameters ---------- pair: tuple - [marker, arg] - [marker, [callable, *kwargs]] - [marker, [arg_x, arg_y, arg_z]] ...
5,348,166
def get_niter(outcarfile): """ Get the number of ionic steps that were run Args: outcarfile (string): full path to OUTCAR file Returns: niter (int): number of ionic iterations """ with open(outcarfile,'r') as rf: for line in rf: if '- Iteration' in line: niter = line.split('(')[0].split('n')[-1]....
5,348,167
def bucket_contvar(ex, ctrl, num_buckets): """ Given ex, which contains a continuous value for a particular control variable, return the bucketed version of that control value. Inputs: ex: message dictionary. Assume it has key ctrl, mapping to the value. ctrl: string. The name of the CT con...
5,348,168
def handle_exception(error): """ Flask error handler for Exception Parameters ---------- error : Exception An Exception error Returns ------- string A JSON string of the Exception error response """ response = create_error_response(error) return response, 50...
5,348,169
def isphone(value, locale='en-US'): """ Return whether or not given value is valid mobile number according to given locale. Default locale is 'en-US'. If the value is valid mobile number, this function returns ``True``, otherwise ``False``. Supported locales are: ``ar-DZ``, ``ar-SY``, ``ar-SA``, ``en-US...
5,348,170
def _darken(color): """ Takes a hexidecimal color and makes it a shade darker :param color: The hexidecimal color to darken :return: A darkened version of the hexidecimal color """ # Get the edge color darker = "#" hex1 = color[1:3] hex2 = color[3:5] hex3 = color[5:7] for val...
5,348,171
def commit_datetime(author_time: str, author_tz: str): """ Convert a commit's timestamp to an aware datetime object. Args: author_time: Unix timestamp string author_tz: string in the format +hhmm Returns: datetime.datetime object with tzinfo """ # timezone info looks l...
5,348,172
def flatten_acfg_list(acfg_list): """ Returns a new config where subconfig params are prefixed by subconfig keys """ flat_acfg_list = [] for acfg in acfg_list: flat_dict = { prefix + '_' + key: val for prefix, subdict in acfg.items() for key, val in subdic...
5,348,173
def happy_birthday(name: hug.types.text, age: hug.types.number): """Says happy birthday to a user""" return "Happy {0} Birthday {1}!".format(name, age)
5,348,174
def train(epoch): """ DOCSTRING """ model.train() if epoch == 6: for param_group in optimizer.param_groups: param_group['lr'] = 0.001 if epoch == 16: for param_group in optimizer.param_groups: param_group['lr'] = 0.0001 for data in train_loader: ...
5,348,175
def emit_end_time_duration(start_time, activity_name, signals): """Emits the end time and duration of something that has started before.""" end_time = time.time() signals.message.emit( "End time: {}".format(time.strftime("%X", time.localtime(end_time))), True ) signals.message.emit( ...
5,348,176
def _format_d10_singlecell(row): """ Format the D10 input data for a single cell (corresponds to a single row in the input csv file). """ nlayers = int(row['nlayer']) if nlayers == 0: # This means this cell cannot be run in HELP. return None try: title = str(int(row['...
5,348,177
def logical_and(x, y, out=None, name=None): """ :alias_main: paddle.logical_and :alias: paddle.logical_and,paddle.tensor.logical_and,paddle.tensor.logic.logical_and :old_api: paddle.fluid.layers.logical_and logical_and Operator It operates element-wise on X and Y, and returns the Out. X, Y and Out a...
5,348,178
def _create_tileZeros(): """ Create a function mapping to the Scala implementation.""" def _(cols, rows, cellType = 'float64'): jfcn = RFContext.active().lookup('tile_zeros') return Column(jfcn(cols, rows, cellType)) _.__name__ = 'tile_zeros' _.__doc__ = "Create column of constant tiles ...
5,348,179
def load_modules(): """ Dynamically loads all the modules in the modules folder and sorts them by the PRIORITY key. If no PRIORITY is defined for a given module, a priority of 0 is assumed. """ # logger = logging.getLogger(__name__) locations = [marvin.support.path.PLUGIN_PATH] ...
5,348,180
def get_merge_image(location_list, url): """ 根据图片位置合并还原 :param location_list: 图片位置数组 :param url: 图片 url :return: """ save_path = os.path.abspath('...') + '\\' + 'images' if not os.path.exists(save_path): os.mkdir(save_path) filename = _pic_download(url, 'all') im = Image...
5,348,181
def _rbe_autoconfig_impl(ctx): """Core implementation of _rbe_autoconfig repository rule.""" bazel_version_debug = "Bazel %s" % ctx.attr.bazel_version if ctx.attr.bazel_rc_version: bazel_version_debug += " rc%s" % ctx.attr.bazel_rc_version print("%s is used in rbe_autoconfig." % bazel_version_d...
5,348,182
def cli(): """ Entrypoint for Zelt. """ # Disable deprecation warning coming from Kubernetes client's YAML loading. # See https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation yaml.warnings({"YAMLLoadWarning": False}) config = _load_config(docopt(__doc__, version=_version...
5,348,183
def test_update_market_value_of_asset_earlier_date(): """ Test update_market_value_of_asset for asset with current_trade_date in past """ start_dt = pd.Timestamp('2017-10-05 08:00:00', tz=pytz.UTC) earlier_dt = pd.Timestamp('2017-10-04 08:00:00', tz=pytz.UTC) later_dt = pd.Timestamp('2017-10...
5,348,184
def property_fragment(): """Builds and returns a random Property init fragment.""" return _build_property_fragment()
5,348,185
def create_person_node(author): """ Parameters ---------- author : dict author field of JSON file. Returns ------- ID : str Document _id from 'Person' collection. """ given = author.get('given', '') family = author.get('family', '') ID = search_person(given, f...
5,348,186
def test_reaction_pattern_match_complex_pattern_ordering(): """Ensure CP equivalence is insensitive to MP order.""" Monomer('A', ['s1', 's2']) cp0 = A(s1=1, s2=2) % A(s1=2, s2=1) cp1 = A(s1=2, s2=1) % A(s1=1, s2=2) rp0 = cp0 + cp1 rp1 = cp1 + cp0 rp2 = cp0 + cp0 assert rp0.matches(rp1) ...
5,348,187
def create_date_list(startDt='2020-11-01', endDt='2020-12-01'): """ Create a date list ranging from start to end dates. Date output format = yyyy_mm :startDt = beginning date for the range :endDt = end date for the range To run the current method requires a minimum one month difference between dates...
5,348,188
def create_sequences(data, seq_len, forward, stride, debug=False): """ Create training and test sequences. Args: data (numpy.array): Assumed to be of shape (N, T, M). seq_len (int): Sequence length. forward (int): Predict forward N periods. stride (int): Shift by k amounts. """ X =...
5,348,189
def batch_distance_metrics_from_coords(coords, mask): """ Given coordinates of neighboring atoms, compute bond distances and 2-hop distances in local neighborhood """ d_mat_mask = mask.unsqueeze(1) * mask.unsqueeze(2) if coords.dim() == 4: two_dop_d_mat = torch.square(coords.unsqueeze(1...
5,348,190
def ComputeHash256(buf: bytes) -> bytes: """ComputeHash256 Compute a cryptographically strong 256 bit hash of the input byte slice.""" return ComputeHash256Array(buf)
5,348,191
def acf_std(x, maxlag=None, periodogram=True, confidence=0.6826895, simplified=True, acf_cached=None): """Computes the approximate standard deviation of the autocorrelation coefficients. Parameters ---------- x : ndarray Input data. maxlag : {None, int} optional Maximum lag bey...
5,348,192
def traverse_map(map, x_step, y_step): """ iterates over a "map" (array of strings) starting at the top left until reaching the bottom of the map. every iteration advances position by <x_step,y_step> and checks if a tree is hit returns: the total number of Trees hit rtype: int """ trees...
5,348,193
def q_to_res(Q: float) -> Optional[float]: """ :param Q: Q factor :return: res, or None if Q < 0.25 """ res = 1 - 1.25 / (Q + 1) if res < 0.0: return None return res
5,348,194
def list_document_classifier(): """[Lists Document Classifiers for Text Classification on AWS] Raises: error: [description] Returns: [list]: [List of Document Classifiers] """ try: logging.info(f"List Document Classifiers") return client.list_document_classifiers() ...
5,348,195
def id_str_to_bytes(id_str: str) -> bytes: """Convert a 40 characters hash into a byte array. The conversion results in 160 bits of information (20-bytes array). Notice that this operation is reversible (using `id_bytes_to_str`). Args: id_str: Hash string containing 40 characters. Returns...
5,348,196
def facts_domain(junos, facts): """ The following facts are required: facts['hostname'] The following facts are assigned: facts['domain'] facts['fqdn'] """ # changes done to fix issue #332 domain_filter_xml = E('configuration', E('system', E('domain-name'))) domain =...
5,348,197
def add_or_update_user(username): """ Takes a username and adds them to our DB from the twitter DB. Get user and get up to 2000 of their tweets and add to our SQLAlchemy database. """ # Error handling # How do we deal with the possibility of getting a user that doesn't exist? # Will brea...
5,348,198
def transform(data): """Transform words and tags to ids """ new_data = [] unknown_word_count = 0 total_word_count = 0 for words, tags in data: word_ids = [word_to_ix.get(w, word_to_ix[UNK]) for w in words] tag_ids = [tag_to_ix.get(t) for t in tags] new_data.append((word_i...
5,348,199