content
stringlengths
22
815k
id
int64
0
4.91M
def get_user_data(filename): """Sorts users based on no of commits and saves the 2nd highest quartile to names_list.txt """ try: users_unsorted={} with open(filename) as f: data = json.load(f) for user in data: ...
44,900
def list_available_filter(): """ List all available filter responses Returns ------- filter_dict : dict Dictionary of filter names containing lists of available instruments """ filter_list = glob(FILTER_DIR + '*_*.dat') filter_dict = {} for filter_file in filter_list: ...
44,901
def select_parents(population, m): """Select randomly parents for the new population from sorted by fitness function existing population.""" fitness_population = sorted( population, key=lambda child: fitness_function(child, m), reverse=True) # ordered_population = [] ...
44,902
def rsqrt(x: Tensor): """Computes reciprocal of square root of x element-wise. Args: x: input tensor Returns: output tensor Examples: >>> x = tf.constant([2., 0., -2.]) >>> rsqrt(x) <Tensor: shape=(3,), dtype=float32, numpy=array([0.707, inf, nan], dtype=f...
44,903
def averageObjPeg(objpegpts, planet, catalog=None, sceneid='NO_POL'): """ Average peg points. """ logger.info('Combining individual peg points: %s' % sceneid) peg = stdproc.orbit.pegManipulator.averagePeg([gp.getPeg() for gp in objpegpts], planet) pegheights = [gp.getAverageHeight() for gp in ob...
44,904
def test_maranhao_call(): """Called the state of Maranhao module, to check to be working""" invalid_number = '120000382' maranhao_index = 'MA' assert con.start(invalid_number, maranhao_index) is False
44,905
def delete_and_remake_directory(folder: PathOrString) -> None: """ Delete the folder if it exists, and remakes it. """ folder = str(folder) if os.path.exists(folder): shutil.rmtree(folder) os.makedirs(folder)
44,906
def create_buttons_version_frame(frame, bg="white"): """インストール/キャンセルボタン、バージョンラベルの生成 Parameters ---------- frame : Frame 表示する親フレーム bg : RGB or string 背景色 """ button_status_list = [["キャンセル" , cancel_button_command ], ["インストール", install_button_comm...
44,907
def send_node_dict(mc, node_dict, end_list=()): """Convert node_dict to node_lists and send to minetest mc : MinetestConnection object node_dict : { (x1,y1,z1):'item1', (x2,y2,z2):'item2', ...} end_list : ('air', 'door:') """ node_lists = node_lists_from_node_dict(node_dict) send_node_lists...
44,908
def _bytes_chr_py2(i): """ Returns a byte string of length 1 whose ordinal value is i in Python 2. Do not call directly, use bytes_chr instead. """ return chr(i)
44,909
def convert(parser: Any) -> c2gtypes.ParserRep: """Convert getopt to a dict. Args: parser (Any): docopt parser Returns: c2gtypes.ParserRep: dictionary representing parser object """ return {"parser_description": "", "widgets": extract(parser)}
44,910
def redirect_vurlkey(request, vurlkey, *args, **kwargs): """redirect_vurlkey(vurlkey) looks up the Vurl with base58-encoded index VURLKEY and issues a redirect to the target URL""" v = Vurl.get_with_vurlkey(vurlkey.encode('utf-8')) return v.http_response()
44,911
def rhand (x,y,z,iopt,parmod,exname,inname): """ Calculates the components of the right hand side vector in the geomagnetic field line equation (a subsidiary subroutine for the subroutine step) :param x,y,z: :param iopt: :param parmod: :param exname: name of the subroutine for the external...
44,912
def upload_user_script(script: ScriptModel, username: str = Depends(decode_token)): """ Add a new script object to the postgreSQL database :param script: The script object containing content and additional information :type script: ScriptModel :param username: The name of the...
44,913
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Volvo sensors.""" if discovery_info is None: return async_add_entities([VolvoSensor(hass.data[DATA_KEY], *discovery_info)])
44,914
def unique_slug_generator_by_email(instance, new_slug=None): """ This is for a Django project and it assumes your instance has a model with a slug field and a title character (char) field. """ slug = new_slug if new_slug is not None else slugify(instance.email) Klass = instance.__class__ qs_...
44,915
def register_provider(price_core_min=1): """Register Provider""" mine(1) web3.eth.defaultAccount = accounts[0] prices = [price_core_min, price_data_transfer, price_storage, price_cache] tx = config.ebb.registerProvider( GPG_FINGERPRINT, provider_email, federation_cloud_id, ...
44,916
def get_signature_and_params(func: Callable): """Get the parameters and signature from a coroutine. func: Callable The coroutine from whom the information should be extracted. Returns ------- Tuple[List[Union[:class:`str`, :class:`inspect.Parameter`]]] Signature and list of paramet...
44,917
def quadratic_formula(polynomial): """ input is single-variable polynomial of degree 2 returns zeros """ if len(polynomial.term_matrix) == 3: if polynomial.term_matrix[2][1] == 1: a, b = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0] return 0, -b/a ...
44,918
def handle_domain_deletion_commands(client: Client, demisto_args: dict) -> str: """ Removes domains from the inbound blacklisted list. :type client: ``Client`` :param client: Client to use. :type demisto_args: ``dict`` :param demisto_args: The demisto arguments. :...
44,919
def UploadClientLogFiles(client): """Uploads the Munki client log files to the server. Args: client: A SimianAuthClient object. """ managed_installs_dir = munkicommon.pref('ManagedInstallDir') log_file_paths = [ os.path.join(managed_installs_dir, 'InstallInfo.plist'), os.path.join(managed_ins...
44,920
def test_export_view_json(runner): """ Tests exporting single article to json """ res = runner.invoke(view, ["new_wangonya", "-e", "json"]) assert res.exit_code == 0
44,921
def checkJavaScriptSyntax(component, tab): """ Checks each JS code component tabs for syntax errors. Note, catalogue message is formatted using a dict that contains: { 'codeTab': The code component tab as string, 'lineNumber': The line number and error msg as string } Pa...
44,922
def test_mocknode_publishers_detect_throttled(): """ Testing that the mocknode detection of topics is throttled properly :return: """ mockn = PyrosMock() assert not mockn.is_alive() assert hasattr(mockn, 'topics') mockn.update_interval = 5 # we wait 5 seconds between each update_throt...
44,923
def create_l2_lag_interface(name, phys_ports, lacp_mode="passive", mc_lag=False, fallback_enabled=False, vlan_ids_list=[], desc=None, admin_state="up", **kwargs): """ Perform a POST call to create a Port table entry for L2 LAG interface. :param name: Alphanumeric name of LAG Por...
44,924
def main_args_parser() -> argparse.Namespace: """ Implements an easy user-friendly command-line interface. It creates three main subparser (classify, train, eval) and add the appropriated arguments for each subparser. Returns ------- args: argparse.Namespace input arguments provided by t...
44,925
def get_train_image_matrices(folder_name, num_images=4): """Gets image matrices for training images. :param folder_name: String with name of training image folder in input_data/train_images directory path. :param num_images: Integer with number of images. :return: Matrices from training images....
44,926
def to_chainer_device(device): """Create a chainer device from a given torch device. Args: device (torch.device): Device to be converted. Returns: A ``chainer.device`` object corresponding to the given input. """ if not isinstance(device, torch.device): raise TypeError('The...
44,927
def max_possible_fps(config): """The max possible FPS if video reading was instantaneous i.e. just a blocking application on the consumer.""" for timer in tqdm(_TIME.measure_many(inspect.currentframe().f_code.co_name, samples=3)): for _ in tqdm(range(config["...
44,928
def decode_region(code): """ Returns the region name for the given region code. For example: decode_region("be") => "Belgium". """ for tag, (language, region, iso639, iso3166) in LANGUAGE_REGION.iteritems(): if iso3166 == code.upper(): return region
44,929
def unzip_whatsapp_file(whatsapp_file): """ unzips a whatsapp .zip file and returns the path of the _chat.txt file that was extracted from the zip Parameters ---------- whatsapp_file: str path to a .zip file with the exported data from Whatsapp. Returns ------- str path to ...
44,930
def neighbourhood_peaks(signal, n=10): """Computes the number of peaks from a defined neighbourhood of the signal. Reference: Christ, M., Braun, N., Neuffer, J. and Kempa-Liehr A.W. (2018). Time Series FeatuRe Extraction on basis of Scalable Hypothesis tests (tsfresh -- A Python package). Neurocomputing 3...
44,931
def check_success(env, policy, act_noise_pct, render=False): """Tests whether a given policy solves an environment Args: env (metaworld.envs.MujocoEnv): Environment to test policy (metaworld.policies.policies.Policy): Policy that's supposed to succeed in env act_noise_pct (fl...
44,932
def import_data(file_regex, index_col_val=None, parse_dates=None, date_format=None): """ takes in a regular expression describing the filepath to the data files and returns a pandas dataFrame Usage1: var_name = import_data.import_data("./hackathon_data/*20*....
44,933
def shift_num_right_by(num: int, digits: int) -> int: """Shift a number to the right by discarding some digits We actually use string conversion here since division can provide wrong results due to precision errors for very big numbers. e.g.: 6150000000000000000000000000000000000000000000000 // 1e27 ...
44,934
def index_handler(request): """ List latest 6 articles, or post a new article. """ if request.method == 'GET': return get_article_list(request) elif request.method == 'POST': return post_article(request)
44,935
def getRawOutput(seqs, tmpfile, command, func): """ Returns output from a given subprocess command that is run iteratively on a given sequence list. It writes to a temporary file on the disk that should be specified. Also, a text processing function can be passed that takes the command line program'...
44,936
def is_windows() -> bool: """ Returns True if the current system is Windows. Returns False otherwise. """ return sys.platform == "win32"
44,937
def hillis_steeles_scan_inclusive_parallel(inp_list): """ Takes in a list, performs hillis-steeles inclusive scan parallelly, returns a shared memory array with the results input: inp_list, 1D list of n elements. returns: 1D Array, newArr of n elements. """ numProcessors = os.cpu_count() inp_list, removeLast = ...
44,938
def test_MADE_autoregressive_property_blocks(weight_norm, blocked_dimensions): """Test that MADE with blocks satisfies the autoregressive property. The test creates a random input for a MADE network and then perturbs it one a time, making sure that output k changes if and only if input with a smaller d...
44,939
def confusion_matrices(prediction, matrix=False, save=False, OutputPath=None, name=None): """ This function plot the confusion matrix at every level of the classification tree. """ cnf_matrix_level_1 = confusion_matrix(prediction['label_level_1'].values,prediction['level_1'].values, labels...
44,940
def showKeyedTimeline(widget): """ Selects the polyColorPerVertex node associated to the geometry to show its timeline and keys Args: widget (PaintWidget): PaintWidget object calling the function """ selected = cmds.ls(sl=True) if not selected: cmds.error("Nothing selected") ...
44,941
def back_propogation(weights, aa, zz, y1hot, lam=0.0): """Perform a back propogation step Args: weights (``list`` of numpy.ndarray): weights between each layer aa (``list`` of numpy.ndarray): activation of nodes for each layer. The last item in the list is the hypothesis. zz (``list`...
44,942
def local_expansion_evaluation(tx, ty, inds, locs, xmids, ymids, LEs, potu, potv, potp, e1, e2): """ Generic local expansion evalution nt: number of targets nL: number of levels tx, f8[nt] - array of all target x values ty, f8[nt] - array of all target y values inds, i8[nt] - wh...
44,943
async def get_reverse_objects_topranked_for_lst(entities): """ get pairs that point to the given entity as the primary property primary properties are those with the highest rank per property see https://www.wikidata.org/wiki/Help:Ranking """ # some lookups just take too long, so we remove them...
44,944
async def close_db(): """Close database connection.""" db_client.close()
44,945
def train_model(max_episodes=1000): """ Trains a DQN agent to play the CartPole game by trial and error :return: None """ # buffer = ReplayBuffer() # Make environment env = WhaleEnv( config={ 'allow_step_back': False, 'allow_raw_data': False, 'si...
44,946
def compute_confidence_interval(data,confidence=0.95): """ Function to determine the confidence interval :param data: input data :param confidence: confidence level :return: confidence interval """ a = 1.0 * np.array(data) n = len(a) se = stat.sem(a) h = se *...
44,947
def adjacent_powerset(iterable): """ Returns every combination of elements in an iterable where elements remain ordered and adjacent. For example, adjacent_powerset('ABCD') returns ['A', 'AB', 'ABC', 'ABCD', 'B', 'BC', 'BCD', 'C', 'CD', 'D'] Args: iterable: an iterable Returns: a li...
44,948
def export_ngrams( docs: Iterator[str], nlp: spacy.language.Language, n: str, patterns=False ) -> Counter: """ Extracts n-gram frequencies of a series of documents Parameters ---------- docs : Iterator[str] An iterator of documents, e.g. abstracts nlp : spacy.language.Language ...
44,949
def getArguments(): """ Gets the name of the gameFile. :return: The arguments provided by the user """ parser = argparse.ArgumentParser() parser.add_argument('gameFile', help='The ini formatted file with the game configuration') return parser.parse_args()
44,950
def solve2D_system( pde_system, conditions, xy_min=None, xy_max=None, single_net=None, nets=None, train_generator=None, shuffle=True, valid_generator=None, optimizer=None, criterion=None, additional_loss_term=None, batch_size=16, max_epochs=1000, monitor=None, return_internal=Fal...
44,951
def model_criterion(preds, labels): """ Function: Model criterion to train the model """ loss = nn.CrossEntropyLoss() return loss(preds, labels)
44,952
def get_dbmapping(syn: Synapse, project_id: str) -> dict: """Gets database mapping information Args: syn: Synapse connection project_id: Project id where new data lives Returns: {'synid': database mapping syn id, 'df': database mapping pd.DataFrame} """ project_ent =...
44,953
def test_padding_slices(): """Make sure we can reverse things.""" oldshape = tuple(rng.integers(64, 256 - 64, 2)) newshape = tuple(rng.integers(s, s * 2) for s in oldshape) data = rng.standard_normal(oldshape) new_data = fft_pad(data, newshape) padding, slices = _padding_slices(newshape, oldshap...
44,954
def end_position(variant_obj): """Calculate end position for a variant.""" alt_bases = len(variant_obj['alternative']) num_bases = max(len(variant_obj['reference']), alt_bases) return variant_obj['position'] + (num_bases - 1)
44,955
def cast_to_server(server_params, topic, msg): """ Invoke a remote method that does not return anything """ return _get_impl().cast_to_server(cfg.CONF, server_params, topic, msg)
44,956
def describe_spot_instance_requests(DryRun=None, SpotInstanceRequestIds=None, Filters=None): """ Describes the Spot instance requests that belong to your account. Spot instances are instances that Amazon EC2 launches when the bid price that you specify exceeds the current Spot price. Amazon EC2 periodically set...
44,957
def get_classification_systems(): """Retrieve all classification systems available in service.""" system = db.session.query(LucClassificationSystem).all() return ClassificationSystemSchema().dump(system, many=True)
44,958
def requirements(domain=None): """ Run task about provisioning of requirements of the app. Example of use: fab requirements:system requirements:webapp :param domain: The key to know how requirements file execute. :return: None """ # Execute the requirements bash file to provisioning to the...
44,959
def test_error_invalid_probability_name(probability_above_cube, interpreter): """Test error raised if probability cube name is invalid""" probability_above_cube.rename("probability_air_temperature_is_above_threshold") with pytest.raises(ValueError, match="is not a valid probability cube name"): inte...
44,960
async def test_switch_connection_error( hass: HomeAssistant, init_integration: MockConfigEntry, mock_wled: MagicMock, caplog: pytest.LogCaptureFixture, ) -> None: """Test error handling of the WLED switches.""" mock_wled.nightlight.side_effect = WLEDConnectionError await hass.services.async...
44,961
def publish(log, session, args): """Publish a collection.""" coll_id = args.id if args.id is not None else "" # check for config if 'config' not in args: log.error('Configuration file path missing') sys.exit(1) configuration = config.parse_config(args.config, log) # get publis...
44,962
def sub_plot_error_img(num, X, min, max): """ This function is used to plot error images of three denoising methods. [min, max] is the relative error range of pixels. """ plt.subplot(3, 5, num) plt.imshow(np.fabs(X - img), vmin = min, vmax = max, cmap = plt.cm.gray) cb = plt.colorbar(aspect ...
44,963
def main(result_pkl=None): """ usage: ./determine_mz_and_i_error.py <Path2ResultPkl> This script will determine the apparant mz and intensity error present in the quantifications for the given result pkl. """ results_class = pickle.load(open(result_pkl, "rb")) plot_name = os.pat...
44,964
def read_annotations(filename, tagset, labeled): """ Read tsv data and return sentences and [word, tag, sentenceID, filename] list """ with open(filename, encoding="utf-8") as f: sentence = [] sentence.append(["[CLS]", -100, -1, -1, None]) sentences = [] sentenceID=0 for line in f: if len(line) > 0: ...
44,965
def LaunchBrowser(ip_addr, port): """Launch browser to connect the webrtc AVD. Args: ip_addr: String, use to connect to webrtc AVD on the instance. port: Integer, port number. """ webrtc_link = _WEBRTC_URL % { "webrtc_ip": ip_addr, "webrtc_port": port} if os.environ....
44,966
def find_rmse(data_1, data_2, ax=0): """ Finds RMSE between data_1 and data_2 Inputs ------ data_1 (np.array) data_2 (np.array) ax (int) The axis (or axes) to mean over Outpts ------ (int) RMSE between data_1 and data_2 """ return np.sqrt(...
44,967
def update(args): """Updates the protein -> taxid idmap If protein accessions were too long these were remapped during the format stage. This requires a new map file to be created with the new (shorter) protein ids. """ prepare.update_idmap(args.idfile, args.taxonmap, args.newfile)
44,968
def validate_tag_update(update): """ Property: ResourceUpdateConstraint.TagUpdateOnProvisionedProduct """ valid_tag_update_values = [ "ALLOWED", "NOT_ALLOWED", ] if update not in valid_tag_update_values: raise ValueError("{} is not a valid tag update value".format(update)...
44,969
def test_delete_user(client): """Test the delete user endpoint.""" response = client.delete('/delete_user/tmehmen2') assert response.status_code == 200 assert response.json == { 'message': 'User with username tmehmen2 has been deleted.', 'status': 'Success' }
44,970
def bollinger_band(df: pd.DataFrame, window: int = 20, window_dev: int = 2) -> pd.DataFrame: """Implementation of bollinger band.""" df_with_signals = df.copy() typical_price = (df["close"] + df["low"] + df["high"]) / 3 df_with_signals["typical_price"] = typical_price std_dev = df_with_signals["typi...
44,971
def close_corner_contour(contour: np.ndarray, shape: tuple) -> np.ndarray: """Check if contours are in the corner, and close them if needed. Contours which cover a corner cannot be closed by joining the first and last element, because some of the area is missed. This algorithm adds the corner point to ...
44,972
def writable_prefix(prefix): """ Checks if this prefix is writable and exists. :param prefix: str - prefix to check :return: str - prefix """ directory = os.path.dirname(prefix) if not os.path.exists(directory): error = "Output directory %s does not exist (%s)" % (directory, prefix) ...
44,973
def assert_mhl_file_has_exact_ignore_patterns(mhl_file: str, patterns_to_check: set): """ asserts the ignore patterns in an mhl are exactly the same as the patterns in patterns_to_check this function adds the default ignore spec to the patterns to check since they are always expected """ patterns_in...
44,974
def encode_csv(csv_path, out_path='csv_encoded.txt', header=True, start_token="<|startoftext|>", end_token="<|endoftext|>"): """Encodes a single-column CSV to a format suitable for gpt-2-simple. Automatically adds the specified prefix and suffix tokens. """ with open(cs...
44,975
def simulate_spatial_ratiometric_reading( do, temperature, sealed_patch_do=0, sealed_patch_kwargs={}, unsealed_patch_kwargs={} ): """ Simulate a "spatial ratiometric" reading using a sealed DO patch as the ratiometric reference Args: do: Dissolved Oxygen partial pressure in mmHg in the unsealed pat...
44,976
async def create_pool(uri, **kwargs) -> asyncpg.pool.Pool: """Creates a connection pool to the specified PostgreSQL server""" def _encode_jsonb(value): return b'\x01' + json.dumps(value).encode('utf-8') def _decode_jsonb(value): return json.loads(value[1:].decode('utf-8')) async def in...
44,977
def plot_state(rho, method='city', filename=None, options=None, mode=None, show=False): """Plot a quantum state. This function provides several methods to plot a quantum state. There are two rendering backends either done in python using matplotlib or using js in a jupyter notebook using...
44,978
def tick_format(ticktime): """ Format the tick date/time """ datetime_object = datetime.strptime(ticktime, '%Y-%m-%dT%H:%M:%S.%fZ') return datetime_object.strftime("%H:%M:%S UTC %A %d %B")
44,979
def add_finite_filter_to_scorer(score_func): """Takes a scorer and returns a scorer that ignores NA / infinite elements in y_true. sklearn scorers (and others) don't handle arrays with 0 length. In that case, return None :param score_func: function that maps two arrays to a number. E.g. (y_true, y_pred) -...
44,980
def run_aa_sim(pSim, simpath, frame): """Run production AA simulation.""" # @TODO HII fix so it uses specific frame from CG simulation LOGGER.info("---> Run AA sim in dir {}".format(simpath)) os.chdir(simpath) # Get backmapped AA files lastFrame = "md-aa-eq6.6.gro" topFile = "system.top" ...
44,981
def lsst_fit(lc, grp): """Take full mock LC and SDSS cadence to find best_fit params. Args: lc: Kali LC object, full mock LC. grp: HDF5 group storing the MCMC chains. """ best_param = [] # store best-fit params ref_ls = [] task = kali.carma.CARMATask(1, 0, nsteps=nsteps, n...
44,982
def iflatten(x): """iflatten(sequence) -> iterator Similar to ``.flatten()``, but returns iterator instead""" for el in x: if _is_listlike(el): for el_ in flatten(el): yield el_ else: yield el
44,983
def assert_rh(instance: machine_learning.StationMachineLearning, model_rh: float, timestamp: datetime, bias_adjusted_rh: float): """ Assert that the ML algorithm predicts the relative humidity correctly """ result = instance.predict_rh(model_rh, timestamp) assert result == bias_adjusted_rh
44,984
def updateLink(page: Page, lnk: dict) -> None: """ Update a link on the current page. """ CheckParent(page) annot = getLinkText(page, lnk) if annot == "": raise ValueError("link kind not supported") page.parent.update_object(lnk["xref"], annot, page=page) return
44,985
def getStudioModeStatus(): """ Indicates if Studio Mode is currently enabled. """ return __createJSON("GetStudioModeStatus", {})
44,986
def calc_long_short_prec( pred: pd.Series, label: pd.Series, date_col="datetime", quantile: float = 0.2, dropna=False, is_alpha=False ) -> Tuple[pd.Series, pd.Series]: """ calculate the precision for long and short operation :param pred/label: index is **pd.MultiIndex**, index name is **[datetime, ins...
44,987
def prepare_tuple_argument(arg, n, arg_name, validate_args=False): """Helper which processes `Tensor`s to tuples in standard form.""" arg_size = ps.size(arg) arg_size_ = tf.get_static_value(arg_size) assertions = [] if arg_size_ is not None: if arg_size_ not in (1, n): raise ValueError('The size of ...
44,988
def isValidLibreOfficeFile(file_path): """ Return true if given file is valid LibreOffice ods file containing manifest.xml, false otherwise. """ try: with zipfile.ZipFile(file_path, 'a') as open_document: open_document.open(DOCUMENT_MANIFEST_PATH) return True except K...
44,989
def main(*args): """Load arguments and run the merger.""" options = load_settings(args) pywikibot.output('Merger started') parser = CsvParser(**options) data_files = load_files(parser, options) merge_data(data_files, options) output_files(parser, data_files, options) pywikibot.output('Me...
44,990
def mean_absolute_percentage_error(y_true, y_pred, zeros_strategy='mae'): """ Similar to sklearn https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_error.html with options for behaviour for around zeros :param y_true: :param y_pred: :param zeros_strategy: :return...
44,991
def test_httpretty_should_allow_adding_and_overwritting_requests(): """HTTPretty should allow adding and overwritting headers with requests""" HTTPretty.register_uri(HTTPretty.GET, "http://github.com/foo", body="this is supposed to be the response", adding_...
44,992
def __get_pretty_body__(headers, body): """ Return a pretty printed body using the Content-Type header information :param headers: Headers for the request/response (dict) :param body: Body to pretty print (string) :return: Body pretty printed (string) """ if HEADER_CONTENT_TYPE in headers: ...
44,993
def bell_sigmoid(ds, a=None, bc=None, d=None, inplace=True): """ Apply a fuzzy membership function to data using bell-shaped sigmoidal function. Requires a low left inflection (a), a mid-point (bc), and a low right inflection (d) point to set the bounds in which to rescale all values to. Value...
44,994
def post_binary(binary, byte_start, byte_data): """Accept a binary file or packet. binary = binary to get the file to write to from byte_start = offset from beginning of file to begin writing byte_data = an iterable that contains data """ result = True message = 'EOF' # rais...
44,995
def test_version(): """Attempt to obtain version""" rtn = testutils.dtf("--version") assert(rtn.return_code == 0) rtn = testutils.dtf("-v") assert(rtn.return_code == 0) rtn = testutils.dtf("version") assert(rtn.return_code == 0)
44,996
def get_composite(name, error=DontCatchError, error_message=None, identifier=None, component_category='unknown'): """ Gets a Composite Singleton :param: - `name`: name to register singleton (clients that want same singleton, use same name) - `error`: exception to catch (``DontC...
44,997
def update_weekly(): """ Updates the weekly Google Trends data. """ with open('src/data/keywords.txt', 'r') as f: for line in f: keyword = line.strip() keyword_url = keyword.replace(' ', '%20') keyword_file = keyword.replace(' ', '_') current = p...
44,998
def is_list_of_float(value): """ Check if an object is a liat of floats :param value: :return: """ return bool(value) and isinstance(value, list) and all(isinstance(elem, float) for elem in value)
44,999