content
stringlengths
22
815k
id
int64
0
4.91M
def pointCoordsDP2LP(dpX, dpY, dptZero, lPix = 1.0): """Convert device coordinates into logical coordinates dpX - x device coordinate dpY - y device coordinate dptZero - device coordinates of logical 0,0 point lPix - zoom value, number of logical points inside one device point (...
5,349,200
def geocode_input(api_key, input, geolocator): """ Use parallel processing to process inputted addresses as geocode Parameters: api_key (string): Google API key input (string): user inputted addresses geolocator: object from Google Maps API that generate geocode of address Returns:...
5,349,201
def satContact(sat_R, gs_R): """ Determines if satellite is within sight of a Ground Station Parameters ---------- sat_R : numpy matrix [3, 1] - Input radius vector in Inertial System ([[X], [Y], [Y]]) gs_R : numpy matrix [3, 1] - Input radius vector in Inertial System ([[X], [Y...
5,349,202
def save_metadata(hparams): """Saves FLAGS and hparams to output_dir.""" output_dir = os.path.expanduser(FLAGS.output_dir) if not tf.gfile.Exists(output_dir): tf.gfile.MakeDirs(output_dir) # Save FLAGS in txt file if hasattr(FLAGS, "flags_into_string"): flags_str = FLAGS.flags_into_string() t2t_f...
5,349,203
def processFolder(abfFolder): """call processAbf() for every ABF in a folder.""" if not type(abfFolder) is str or not len(abfFolder)>3: return files=sorted(glob.glob(abfFolder+"/*.abf")) for i,fname in enumerate(files): print("\n\n\n### PROCESSING {} of {}:".format(i,len(files)),os.path....
5,349,204
def load_tlm_output_npz(pytorch_tlm: nn.Module, npz: str, embeddings_keys: List[str] = None, name: str = "TLM"): """Restore a TLM-like model (possibly a `nn.Module` for fine-tuning We just populate the `TransformerEncoderStack` and the embeddings from weights, all other values remain uninitialized :pa...
5,349,205
def insertOrUpdateTweetBatch( profileRecs, tweetsPerProfile=200, verbose=False, writeToDB=True, campaignRec=None, onlyUpdateEngagements=True, ): """ Get Twitter tweet data from the Twitter API for a batch of profiles and store their tweets in the database. The verbose and writeT...
5,349,206
def determine_visible_field_names(hard_coded_keys, filter_string, ref_genome): """Determine which fields to show, combining hard-coded keys and the keys in the filter string. """ fields_from_filter_string = extract_filter_keys(filter_string, ref_genome) return list(set(hard_coded_keys) | set...
5,349,207
def get_data_day(data: pd.DataFrame): """Get weekday/weekend designation value from data. :param pandas.DataFrame data: the data to get day of week from. :return: (*numpy.array*) -- indicates weekend or weekday for every day. """ return np.array(data["If Weekend"])
5,349,208
def bisection(f, a, b, power, iter_guess="yes"): """Given f(x) in [`a`,`b`] find x within tolerance, `tol`. Root-finding method: f(x) = 0. Parameters ---------- f : expression Input function. a : float Left-hand bound of interval. b : float Right-hand bound of inte...
5,349,209
def make_pretty(image, white_level=50): """Rescale and clip an astronomical image to make features more obvious. This rescaling massively improves the sensitivity of alignment by removing background and decreases the impact of hot pixels and cosmic rays by introducing a white clipping level that should...
5,349,210
def inventory( network_report_file: Path = typer.Argument(...), output_file: Optional[Path] = typer.Option( None, "-o", "--output", help="Output file", ), print_to_console: bool = typer.Option( False, "--print", help="Print to console instead of output file" )...
5,349,211
def get_examples_version(idaes_version: str): """Given the specified 'idaes-pse' repository release version, identify the matching 'examples-pse' repository release version. Args: idaes_version: IDAES version, e.g. "1.5.0" or "1.5.0.dev0+e1bbb[...]" Returns: Examples version, or if the...
5,349,212
def data_convert(): """ data iteration wrapper """ if os.path.isdir(fea_path) == False: os.mkdir(fea_path) for dataname in sorted(os.listdir(label_path)): data_y, data_box = load_data(dataname) if data_y is None or data_box is None: continue # S...
5,349,213
def hash(data: bytes) -> bytes: """ Compute the hash of the input data using the default algorithm Args: data(bytes): the data to hash Returns: the hash of the input data """ return _blake2b_digest(data)
5,349,214
def compute_cd_small_batch(gt, output,batch_size=50): """ compute cd in case n_pcd is large """ n_pcd = gt.shape[0] dist = [] for i in range(0, n_pcd, batch_size): last_idx = min(i+batch_size,n_pcd) dist1, dist2 , _, _ = distChamfer(gt[i:last_idx], output[i:last_idx]) cd_...
5,349,215
def find_sub_supra(axon, stimulus, eqdiff, sub_value=0, sup_value=0.1e-3): """ 'find_sub_supra' computes boundary values for the bisection method (used to identify the threeshold) Parameters ---------- axon (AxonModel): axon model stimulus (StimulusModel): stimulus model eqdiff (function): ...
5,349,216
def test_ca_file(kivy_clock, scheme): """Passing a `ca_file` should not crash on http scheme, refs #6946""" from kivy.network.urlrequest import UrlRequest import certifi obj = UrlRequestQueue([]) queue = obj.queue req = UrlRequest( f"{scheme}://httpbin.org/get", on_success=obj._o...
5,349,217
def constantly(x): """constantly: returns the function const(x)""" @wraps(const) def wrapper(*args, **kwargs): return x return wrapper
5,349,218
def ToBaseBand(xc, f_offset, fs): """ Parametros: xc: Señal a mandar a banda base f_offset: Frecuencia que esta corrido fs: Frecuencia de muestreo """ if PLOT: PlotSpectrum(xc, "xc", "xc_offset_spectrum.pdf", fs) # Se lo vuelve a banda base, multiplicando por una exponencial con fase f_offset / fs x_b...
5,349,219
def hvp( f: DynamicJaxFunction, x: TracerOrArray, v: TracerOrArray, ) -> TracerOrArray: """Hessian-vector product function""" return jax.grad(lambda y: jnp.vdot(jax.grad(f)(y), v))(x)
5,349,220
def concat_all_gather(tensor): """ Performs all_gather operation on the provided tensors. *** Warning ***: torch.distributed.all_gather has no gradient. """ return hvd.allgather(tensor.contiguous())
5,349,221
def run_modes(): """Run modes instrumented in config file""" for mode in RUN_MODES: if mode == "check_index": logging.info("Checking that TMDB Elasticsearch index is created") if index_exists_and_has_data(INDEX_READ): logging.info("Elasticsearch index has been cre...
5,349,222
async def test_config_entry_not_ready( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_elgato: MagicMock, ) -> None: """Test the Elgato configuration entry not ready.""" mock_elgato.info.side_effect = ElgatoConnectionError mock_config_entry.add_to_hass(hass) await hass.config_...
5,349,223
def start_search(search): """Run the specified number of threads of the searcher""" #Make the queue of all of the threads to run my_queue = Queue.Queue() for i in range(search.threads): t = threading.Thread(target=search_instance, args=(search, )) my_queue.put(t) #Run all of the thr...
5,349,224
def get_config(): """Prints the current config""" print(manager.get_config())
5,349,225
def find_files( path: str, skip_folders: tuple, skip_files: tuple, extensions: tuple = (".py",), ) -> List[str]: """Find recursively all files in path. Parameters ---------- path : str Path to a folder to find files in. skip_folders : tuple Skip folders containing fo...
5,349,226
def get_min_area_rect(points): """ 【得到点集的最小面积外接矩形】 :param points: 轮廓点集,n*1*2的ndarray :return: 最小面积外接矩形的四个端点,4*1*2的ndarray """ rect = cv2.minAreaRect(points) # 最小面积外接矩形 box = cv2.boxPoints(rect) # 得到矩形的四个端点 box = np.int0(box) box = box[:, np.newaxis, :] # 从4*2转化为4*1*2 return bo...
5,349,227
def the_volume_is_republished(volume_ctx): """the volume is re-published.""" volume_ctx[VOLUME_CTX_KEY] = publish_volume()
5,349,228
def vector_to_cyclic_matrix(vec): """vec is the first column of the cyclic matrix""" n = len(vec) if vec.is_sparse(): matrix_dict = dict((((x+y)%n, y), True) for x in vec.dict() for y in xrange(n)) return matrix(GF(2), n, n, matrix_dict) vec_list = vec.list() matrix_lists = [vec_list...
5,349,229
def cfn_resource_helper(): """ A helper method for the custom cloudformation resource """ # Custom logic goes here. This might include side effects or # Producing a a return value used elsewhere in your code. logger.info("cfn_resource_helper logic") return True
5,349,230
def get_ts_code_and_list_date(engine): """查询ts_code""" return pd.read_sql('select ts_code,list_date from stock_basic', engine)
5,349,231
def balanced_eq(want, to_balance): """Run `to_balance` through the expander to get its tags balanced, and assert the result is `want`.""" expander = ForParser(to_balance) eq_(want, expander.to_unicode())
5,349,232
def modifySummary(filename, cost, leadTime, isManufacturable): """ Modifies an existing testbench_manifest file, changing the AnalysisStatus and Value fields. """ print filename with open(filename, "r") as file: summary = json.load(file) summary["TierLevel"] = 2 summary["TestBench"] = "Foundry" if co...
5,349,233
def nested_cv_ridge( X, y, test_index, n_bins=4, n_folds=3, alphas = 10**np.linspace(-20, 20, 81), npcs=[10, 20, 40, 80, 160, 320, None], train_index=None, ): """ Predict the scores of the testing subjects based on data from the training subjects using ridge regression. Hyper...
5,349,234
def absolute_time(time_delta, meta): """Convert a MET into human readable date and time. Parameters ---------- time_delta : `~astropy.time.TimeDelta` time in seconds after the MET reference meta : dict dictionary with the keywords ``MJDREFI`` and ``MJDREFF`` Returns -------...
5,349,235
def create_app(object_name, env="prod"): """ Arguments: object_name: the python path of the config object, e.g. webapp.settings.ProdConfig env: The name of the current environment, e.g. prod or dev """ app = Flask(__name__) app.config.from_object(object_name) ...
5,349,236
def test_parameter_name(): """ test_parameter_name """ ta = Tensor(np.ones([2, 3])) tb = Tensor(np.ones([1, 4])) n = Net(ta, tb) names = [] for m in n.parameters_and_names(): if m[0]: names.append(m[0]) assert names[0] == "mod1.weight" assert names[1] == "mod2.weight"...
5,349,237
def yyyydoy_to_date(yyyydoy): """ Convert a string in the form of either 'yyyydoy' or 'yyyy.doy' to a datetime.date object, where yyyy is the 4 character year number and doy is the 3 character day of year :param yyyydoy: string with date in the form 'yyyy.doy' or 'yyyydoy' :return: datetime.date...
5,349,238
def create_selection(): """ Create a selection expression """ operation = Forward() nested = Group(Suppress("(") + operation + Suppress(")")).setResultsName("nested") select_expr = Forward() functions = select_functions(select_expr) maybe_nested = functions | nested | Group(var_val) operatio...
5,349,239
def move_nodes(source_scene, dest_scene): """ Moves scene nodes from the source scene to the destination scene. :type source_scene: fbx.FbxScene :type dest_scene: fbx.FbxScene """ source_scene_root = source_scene.GetRootNode() # type: fbx.FbxNode dest_scene_root = dest_scene.GetRootNode()...
5,349,240
def extract_values(*args): """ Wrapper around `extract_value`; iteratively applies that method to all items in a list. If only one item was passed in, then we return that one item's value; if multiple items were passed in, we return a list of the corresponding item values. """ processed = [...
5,349,241
def disconnect(receiver, signal=Any, sender=Any, weak=True): """Disconnect receiver from sender for signal. Disconnecting is not required. The use of disconnect is the same as for connect, only in reverse. Think of it as undoing a previous connection.""" if signal is None: raise DispatcherError...
5,349,242
def predefined_split(dataset): """Uses ``dataset`` for validiation in :class:`.NeuralNet`. Examples -------- >>> valid_ds = skorch.dataset.Dataset(X, y) >>> net = NeuralNet(..., train_split=predefined_split(valid_ds)) Parameters ---------- dataset: torch Dataset Validiation data...
5,349,243
def file_instruction(): """Prints log file setup instructions to the console """ print(''' Weather Log File ---------------- The weather log files are automatically created and saved in the weather_logs folder located in the same folder as this python file. The default filename given ...
5,349,244
def writeBremDecay( # Might want a config later lhe, mAp, eps, zlims, seed, outdir, outname, nevents=10_000 ): """ Break A'->ee LHEs in...
5,349,245
def bgr_to_rgba(image: Tensor, alpha_val: Union[float, Tensor]) -> Tensor: """Convert an image from BGR to RGBA. Args: image (Tensor[B, 3, H, W]): BGR Image to be converted to RGBA. alpha_val (float, Tensor[B, 1, H, W]): A float number or tensor for the alpha value. ...
5,349,246
def d_matrix_1d(n, r, v): """Initializes the differentiation matrices on the interval. Args: n: The order of the polynomial. r: The nodal points. v: The Vandemonde matrix. Returns: The gradient matrix D. """ vr = grad_vandermonde_1d(n, r) return np.linalg.lstsq(v.T, vr....
5,349,247
def compile_replace(pattern, repl, flags=0): """Construct a method that can be used as a replace method for sub, subn, etc.""" call = None if pattern is not None and isinstance(pattern, RE_TYPE): if isinstance(repl, (compat.string_type, compat.binary_type)): repl = ReplaceTemplate(patte...
5,349,248
def python_2_unicode_compatible(klass): """ From Django A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. ...
5,349,249
def ParseNewPingMsg(msg): """Attempt to parse the message for a ping (in the new format). Return the request and response strings (json-ified dict) if parsing succeeded. Return None otherwise. """ parsed = re.match(kNewPingMsgRe, msg) if not parsed: return None try: return (parsed.group(1), parsed.g...
5,349,250
def parse_main_dict(): """Parses dict to get the lists of countries, cities, and fakers. Fakers allow generation of region specific fake data. Also generates total number of agents """ Faker.seed(seed) # required to generate reproducible data countries = main_dict.keys() cities = [v['city'...
5,349,251
def showMIinstructions(window, miType, holdTime): """Presents instructions for the traditional motor imagery (TMI) response. Parameters ---------- window : obj Psychopy window object. miType : string Type of motor imagery which needs to be prompted Could be one of: ...
5,349,252
def format_payload(svalue): """formats mqtt payload""" data = {"idx": IDX, "nvalue": 0, "svalue": svalue} return json.dumps(data)
5,349,253
def load_auth_client(): """Create an AuthClient for the portal No credentials are used if the server is not production Returns ------- globus_sdk.ConfidentialAppAuthClient Client used to perform GlobusAuth actions """ _prod = True if _prod: app = globus_sdk.Confidenti...
5,349,254
def start_python_console(namespace=None, noipython=False): """Start Python console binded to the given namespace. If IPython is available, an IPython console will be started instead, unless `noipython` is True. Also, tab completion will be used on Unix systems. """ if namespace is None: name...
5,349,255
def test_our_signal_object_method_returns_qobject(optional_name_argument): """qtrio._core.Signal instance provides access to signal-hosting QObject.""" class NotQObject: signal = qtrio.Signal(int, **optional_name_argument) instance = NotQObject() assert isinstance(NotQObject.signal.object(ins...
5,349,256
def DCGAN_discriminator(img_dim, nb_patch, bn_mode, model_name="DCGAN_discriminator", use_mbd=True): """ Discriminator model of the DCGAN args : img_dim (tuple of int) num_chan, height, width pretr_weights_file (str) file holding pre trained weights returns : model (keras NN) the Neural Net...
5,349,257
def common_stat_style(): """ The common style for info statistics. Should be used in a dash component className. Returns: (str): The style to be used in className. """ return "has-margin-right-10 has-margin-left-10 has-text-centered has-text-weight-bold"
5,349,258
def TourType_LB_rule(M, t): """ Lower bound on tour type :param M: Model :param t: tour type :return: Constraint rule """ return sum(M.TourType[i, t] for (i, s) in M.okTourType if s == t) >= M.tt_lb[t]
5,349,259
def build_auto_dicts(jsonfile): """Build auto dictionaries from json""" dicts = {} with open(jsonfile, "r") as jsondata: data = json.load(jsondata) for dicti in data: partialstr = data[dicti]["partial"] partial = bool(partialstr == "True") dictlist = data[dicti]["list"]...
5,349,260
def print_status(message, status, status_text=None): """ Prints a status message in the form: <message>\t[<status>]. The first part of the status message is any message passed as a parameter. Following this with a tab distance and in boxed brackets is a status message text in a colour based on the ...
5,349,261
def log_gammainv_pdf(x, a, b): """ log density of the inverse gamma distribution with shape a and scale b, at point x, using Stirling's approximation for a > 100 """ return a * np.log(b) - sp.gammaln(a) - (a + 1) * np.log(x) - b / x
5,349,262
def read_basin() -> gpd.GeoDataFrame: """Read the basin shapefile.""" basin = gpd.read_file(Path(ROOT, "HCDN_nhru_final_671.shp")) basin = basin.to_crs("epsg:4326") basin["hru_id"] = basin.hru_id.astype(str).str.zfill(8) return basin.set_index("hru_id").geometry
5,349,263
def cross_validate(estimator: BaseEstimator, X: np.ndarray, y: np.ndarray, scoring: Callable[[np.ndarray, np.ndarray, ...], float], cv: int = 5) -> Tuple[float, float]: """ Evaluate metric by cross-validation for given estimator Parameters ---------- estimator: BaseEstimator ...
5,349,264
def unpack_request(environ, content_length=0): """ Unpacks a get or post request query string. :param environ: whiskey application environment. :return: A dictionary with parameters. """ data = None if environ["REQUEST_METHOD"] == "GET": data = unpack_get(environ) elif environ["R...
5,349,265
def GetMembership(name, release_track=None): """Gets a Membership resource from the GKE Hub API. Args: name: the full resource name of the membership to get, e.g., projects/foo/locations/global/memberships/name. release_track: the release_track used in the gcloud command, or None if it is not a...
5,349,266
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...
5,349,267
def get_snmp_community(device, find_filter=None): """Retrieves snmp community settings for a given device Args: device (Device): This is the device object of an NX-API enabled device using the Device class community (str): optional arg to filter out this specific community Retu...
5,349,268
def create_input_chunks(cs, partition, data_dir, file_format): """ cs: chunk shape file_format: file format data_dir: to store the file """ if file_format == "HDF5": file_manager = HDF5_manager() else: print("File format not supported yet. Aborting...") sy...
5,349,269
def get_header_size(tif): """ Gets the header size of a GeoTIFF file in bytes. The code used in this function and its helper function `_get_block_offset` were extracted from the following source: https://github.com/OSGeo/gdal/blob/master/swig/python/gdal-utils/osgeo_utils/samples/validate_cloud...
5,349,270
def format_x_ticks_as_dates(plot): """Formats x ticks YYYY-MM-DD and removes the default 'Date' label. Args: plot: matplotlib.AxesSubplot object. """ plot.xaxis.set_major_formatter(mpl.dates.DateFormatter('%Y-%m-%d')) plot.get_xaxis().get_label().set_visible(False) return plot
5,349,271
def operations(): """Gets the base class for the operations class. We have to use the configured base back-end's operations class for this. """ return base_backend_instance().ops.__class__
5,349,272
def send_data_without_firstname(page_new_contact, the_faker) -> None: """I send the data without the firstname.""" page_new_contact.contact = ContactFakerFactory(_faker=the_faker).initialize(config={}) p_action = ContactWriteAction(_page=page_new_contact) p_action.fill_lastname().fill_phone() del p_...
5,349,273
def office_convert_get_page(request, repo_id, commit_id, path, filename): """Valid static file path inclueds: - index.html for spreadsheets and index_html_xxx.png for images embedded in spreadsheets - 77e168722458356507a1f373714aa9b575491f09.pdf """ if not HAS_OFFICE_CONVERTER: raise Http404...
5,349,274
def combine_res_work_dcfc_lcoc(res_lcoc_file = 'outputs/cost-of-charging/residential/res_states_baseline.csv', wrk_lcoc_file = 'outputs/cost-of-charging/workplace-public-l2/work_pub_l2_states_baseline.csv', dcfc_lcoc_file = 'outputs/cost-of-charging/dcfc/dcf...
5,349,275
def tensorize_data( uvdata, corr_inds, ants_map, polarization, time, data_scale_factor=1.0, weights=None, nsamples_in_weights=False, dtype=np.float32, ): """Convert data in uvdata object to a tensor Parameters ---------- uvdata: UVData object UVData object co...
5,349,276
def _normalize_rows(t, softmax=False): """ Normalizes the rows of a tensor either using a softmax or just plain division by row sums Args: t (:obj:`batch_like`) Returns: Normalized version of t where rows sum to 1 """ if not softmax: # EPSILON hack avoids occasional...
5,349,277
def calculate_baselines(baselines: pd.DataFrame) -> dict: """ Read a file that contains multiple runs of the same pair. The format of the file must be: workload id, workload argument, run number, tFC, tVM This function calculates the average over all runs of each unique pair of workload id and...
5,349,278
def pick_ind(x, minmax): """ Return indices between minmax[0] and minmax[1]. Args: x : Input vector minmax : Minimum and maximum values Returns: indices """ return (x >= minmax[0]) & (x <= minmax[1])
5,349,279
def removedir(dirpath): """Remove dir if it does exist and is a dir.""" if exists(dirpath) and isdir(dirpath): shutil.rmtree(dirpath)
5,349,280
def read_files(file_prefix,start=0,end=100,nfmt=3,pixel_map=None): """ read files that have a numerical suffix """ images = [] format = '%' + str(nfmt) + '.' + str(nfmt) + 'd' for j in range(start,end+1): ext = format % j file = file_prefix + '_' + ext + '.tif' ...
5,349,281
def check_geometry(geometry): """ Checks if a node is valid geometry node and raise and exception if the node is not valid :param geometry: str, name of the node to be checked :return: bool, True if the give node is a geometry node """ if not is_geometry(geometry): raise exceptions.Geom...
5,349,282
def test_table_exists(db: DataBaseConn, create_table): """Test return True if table exists.""" assert db.table_exists("test")
5,349,283
def describing_function( F, A, num_points=100, zero_check=True, try_method=True): """Numerical compute the describing function of a nonlinear function The describing function of a nonlinearity is given by magnitude and phase of the first harmonic of the function when evaluated along a sinusoidal ...
5,349,284
def _read_point(asset: str, *args, **kwargs) -> List: """Read pixel value at a point from an asset""" with COGReader(asset) as cog: return cog.point(*args, **kwargs)
5,349,285
def test_copy(): """Ensure that the copy method makes a proper copy of the fermentable.""" recipe = RecipeStub() original = Fermentable( recipe=recipe, name='Test', amount=MassType(1, 'lb'), ftype='Grain', group='Smoked', producer='Crisp', ...
5,349,286
def get_unquoted_text(token): """ :param token: Token :return: String """ if isinstance(token, UnquotedText): return token.value() else: raise exceptions.BugOrBroken( "tried to get unquoted text from " + token)
5,349,287
def image2tensor(image: np.ndarray, range_norm: bool, half: bool) -> torch.Tensor: """Convert ``PIL.Image`` to Tensor. Args: image (np.ndarray): The image data read by ``PIL.Image`` range_norm (bool): Scale [0, 1] data to between [-1, 1] half (bool): Whether to convert torch.float32 sim...
5,349,288
def panda_four_load_branch(): """ This function creates a simple six bus system with four radial low voltage nodes connected to \ a medium valtage slack bus. At every low voltage node the same load is connected. RETURN: **net** - Returns the required four load system EXAMPLE: i...
5,349,289
def word_flipper(our_string): """ Flip the individual words in a sentence Args: our_string(string): Strings to have individual words flip Returns: string: String with words flipped """ word_list = our_string.split(" ") for idx in range(len(word_list)): word_list[idx]...
5,349,290
def load_json(ctx, param, value): """Decode and load json for click option.""" value = value[1:] return json.loads(base64.standard_b64decode(value).decode())
5,349,291
def hyperparam_search(model_config, train, test): """Perform hyperparameter search using Bayesian optimization on a given model and dataset. Args: model_config (dict): the model and the parameter ranges to search in. Format: { "name": str, "model": sklearn.base.BaseE...
5,349,292
def sendNotification(email, asset, dom_ids, cve_ids): """Send email notification about new scan results.""" sender = settings.EMAIL_HOST_USER cves = [v['name'] for v in VulnInstance.objects.filter(id__in=cve_ids).values('name')] doms = [d['fqdn'] for d in DomainInstance.objects.filter(id__in=dom_ids).va...
5,349,293
def profile_tags(profile): """ Get the tags from a given security profile. """ # TODO: This is going to be a no-op now, so consider removing it. return profile.id.split('_')
5,349,294
def _sawtooth_wave_samples(freq, rate, amp, num): """ Generates a set of audio samples taken at the given sampling rate representing a sawtooth wave oscillating at the given frequency with the given amplitude lasting for the given duration. :param float freq The frequency of oscillation of the sa...
5,349,295
def ResNet_UNet_Dropout(dim=512, num_classes=6, dropout=0.5, final_activation=True): """ Returns a ResNet50 Nework with a U-Net like upsampling stage. Inlcudes skip connections from previous ResNet50 layers. Uses a SpatialDrop on the final layer as introduced in https://arxiv.org/pdf/1411.4280....
5,349,296
def test_bucket_names(sdc_builder, sdc_executor, gcp, test_name, bucket_name): """ Write data to Google cloud storage with different valid bucket names. The pipeline looks like: google_cloud_storage_origin >> wiretap """ pipeline_builder = sdc_builder.get_pipeline_builder() storage_cli...
5,349,297
def ldap_suffix(): """Returns ldap search base. return 'dc=xx,dc=com' """ assert False
5,349,298
def _parse_accounts_ce(database, uid, result_path): """Parse accounts_ce.db. Args: database (SQLite3): target SQLite3 database. uid (str): user id. result_path (str): result path. """ cursor = database.cursor() try: cursor.execute(query) except sqlite3.Error as e...
5,349,299