content
stringlengths
22
815k
id
int64
0
4.91M
def normalized_sat_value_difference_index(Blue, Green, Red): """transform red, green, blue arrays to normalized sat-value difference Parameters ---------- Blue : np.array, size=(m,n) blue band of satellite image Green : np.array, size=(m,n) green band of satellite image Red : np...
80,000
def make_game(environment_data, level): """Initialises the game. Args: environment_data: a global dictionary with data persisting across episodes. level: which game level to play. Returns: A game engine. """ sprites = {SUSHI_CHR: [SushiSprite], AGENT_CHR: [AgentSprite]} upda...
80,001
def send_stop_job_command(connection, job_id): """Instruct a worker to stop a job""" job = Job.fetch(job_id, connection=connection) if not job.worker_name: raise InvalidJobOperation('Job is not currently executing') send_command(connection, job.worker_name, 'stop-job', job_id=job_id)
80,002
def filter_by_freq(word_list, chained_words, min_freq): """ Replaces words occuring less than min_freq with the unknown tag <unk> and dumps the replaced words to a file (via pickle) """ unk_list = [] print("Filtering words occuring less than %d times..." % min_freq) for word in word_list: ...
80,003
def score_tile( tile_cij, clr, expected_indexed, expected_value_col, clr_weight_name, kernels, max_nans_tolerated, band_to_cover, ): """ The main working function that given a tile of a heatmap, applies kernels to perform convolution to calculate locally-adjusted expected and...
80,004
def plot_image_process(img_before, img_after, img_reference=None, plot_type='subtract'): """ Plot processes performed on an image. img_before : the original image img_after : the image after processing img_reference : (optional) the image used to perform the process plot_type ...
80,005
def display_time(seconds, granularity=1): """ Turns seconds into weeks, days, hours, minutes and seconds. Granularity determines how many time units should be returned. EG: # 2 time unites, week and day 1934815, 2 = '3 weeks, 1 day' # 4 time units 1934815, 4 = '3 weeks, 1 day, 9 hours, 26 minute...
80,006
def euler2mat(angle): """Convert euler angles to rotation matrix. Reference: https://github.com/pulkitag/pycaffe-utils/blob/master/rot_utils.py#L174 Args: angle: rotation angle along 3 axis (in radians) -- size = [B, 3] Returns: Rotation matrix corresponding to the euler angles -- size =...
80,007
def execute_cli_command(args: List[str], input_data: Optional[str] = None, ret_val: int = 0, output_string: bool = True) -> Any: """Execute a Nessie CLI command.""" if output_string: return _run(args, input_data, ret_val).output return _run(args, input_data, ret_val)
80,008
def get_key(password=None, filekey=None): """ get_key """ key = None filekey = filekey if filekey else tempfile.gettempdir() + "/.private.key" if password and isinstance(password, (str,)): kdf = PBKDF2HMAC(algorithm = hashes.SHA256(), length = 32, salt = os.urandom(16), iterations = 100...
80,009
def transformer_latent_decoder(x, encoder_output, ed_attention_bias, hparams, name=None): """Transformer decoder over latents using latent_attention_type. Args: x: Tensor of shape [batch,...
80,010
def errorbar(*args, **kwargs): """ Plot curves with error bars Example:: import numpy as np x = np.linspace(-5, 5, 1000) errorbar(x, -1+x**2/20+.2*np.random.rand(len(x)), x/20) show() """ axe = gca() curve = make.merror(*args, **kwargs) axe.add_p...
80,011
def privkey_to_wif(privkey, netcode="BTC"): """ Get private key from bitcoin wif. Args: privkey (str): Hex encoded private key Return: str: Private key encode in bitcoin wif format. """ prefix = networks.wif_prefix_for_netcode(netcode) secret_exponent = encoding.from_bytes_32(h...
80,012
def join_values(values): """Return the values as a space-delimited string.""" return " ".join((str(v) for v in values))
80,013
def get_cookie_opener( gs_username, gs_token, gs_toolname=None ): """ Create a GenomeSpace cookie opener """ cj = http_cookiejar.CookieJar() for cookie_name, cookie_value in [ ( 'gs-token', gs_token ), ( 'gs-username', gs_username ) ]: # create a super-cookie, valid for all domains cookie = ...
80,014
def translate(im,trans): """translates 3d images""" shape_ = im.shape zmax=shape_[0] xmax=shape_[1] ymax=shape_[2] zmin,xmin,ymin=0,0,0 trans_=np.array(np.round(trans),dtype=int) zmin-=trans_[0] zmax-=trans_[0] xmin-=trans_[1] xmax-=trans_[1] ymin-=trans_[2] ymax-=tra...
80,015
def add_base32_padding(base32_input_no_padding): """Return a base32 string with the correct padding Parameters: base32_input_no_padding (str): base32 string without padding """ result = base32_input_no_padding while ((len(result) % 8) != 0): result += '=' return result
80,016
def compute_similarities(audio_embeds, query_embeds, audio_lens): """ Compute a batch of audio-text alignment matrices. :param audio_embeds: tensor, (N, T, E). :param query_embeds: tensor, (N, Q, E). :param audio_lens: numpy 1D-array, (N,). :return: tensor, (N, T, Q). """ N = audio_embe...
80,017
def get_request_body(db, light, prev_light_state): """ Build the request body for the hue api.""" body = {} brightness = calc_brightness(db=db, light=light) color_temp = calc_color_temp(db=db, light=light) if light.ct_controlled: body['ct'] = color_temp if light.bri_controlled: ...
80,018
def T_inv(e, d, b): """Inverse transform b.""" return T(rotate_right(e, d+1), N-d-2, b)
80,019
def main(): """Main function only in command line""" from sys import argv lines = None with open(argv[1], 'r') as f: lines = f.readlines() s = StackTree(lines) s.to_flame()
80,020
def check_for_no_version_recommended(context): """Check for no recommended version if private vuln.""" json_data = context.response.json() assert "recommended_versions" in json_data assert json_data["recommended_versions"] == ""
80,021
def magic(num_lst, n, k): """对 num_lst 使用 k 次魔力""" a = num_lst[:] for j in range(k): b = a[1:] # 又一种“移动”方法 b.append(a[0]) for i in range(n): a[i] = (a[i] + b[i]) % 100 # 无差别对 100 取余 return a
80,022
def write_dir_labels(template_path: str, raw_dir: str, out_dir: str): """Write labels for all clusters in specified directory. Hardcoded to use the directory structure in cloud_to_clusters. raw_dir/<drive>/<cloud>/*.npy """ for directory in os.listdir(raw_dir): drive_dir = os.path.join(raw...
80,023
def get_status(config, request_uuid, show_logs, show_query, filter_logs, table_max_width): """ Get information for an ephemeris search request \b REQUEST_UUID the request unique identifier """ # get request status try: url = pyaurorax.api.urls.ephemeris_request_url.format(request...
80,024
async def test_timeout(aresponses): """Test request timeout from AdGuard Home.""" # Faking a timeout by sleeping async def response_handler(_): """Response handler for this test.""" await asyncio.sleep(2) return aresponses.Response(body="Goodmorning!") aresponses.add("example.co...
80,025
def test_load_pandas_dataframe_to_table(database_table_fixture): """Test load_pandas_dataframe_to_table against snowflake""" database, table = database_table_fixture pandas_dataframe = pd.DataFrame(data={"id": [1, 2]}) database.load_pandas_dataframe_to_table(pandas_dataframe, table) statement = f"...
80,026
def format_number(number): """ Round number to two decimals :param number: input number :return: number rounded to two decimals """ return format(float(number), '.2f')
80,027
def apply_sort(query, sort_spec): """Apply sorting to a :class:`sqlalchemy.orm.Query` instance. :param sort_spec: A list of dictionaries, where each one of them includes the necesary information to order the elements of the query. Example:: sort_spec = [ {'...
80,028
def _find(searchable_models, tupls): """ # start with the output of the _dice doctest >>> p = [('a', 'b', 'c'), ('a', 'b'), ('b', 'c'), ('a',), ('b',), ('c',)] >>> class MockModel_A(object): ... ... def __repr__(self): ... return "<MM:A>" ... ... @classmethod ......
80,029
def tags_index(): """Show a page with info on all tags""" tags = Tag.query.all() return render_template('tags/index.html', tags=tags)
80,030
def build_estimator(model_dir, model_type): """Build an estimator.""" if model_type == "wide": m = tf.estimator.LinearClassifier( model_dir=model_dir, feature_columns=feature_columns) elif model_type == "deep": m = tf.estimator.DNNClassifier( model_dir=model_dir, feature_columns=fe...
80,031
def double_variants(word): """get variants for the variants for a word""" return set(s for w in variants(word) for s in variants(w))
80,032
def register_cmd_module(cmd_mod: Union[Iterable[ModuleType], ModuleType]): """ Register a command with the implementation module. The register function in the module which is decorated with @register_cmd will be used to complete the command registration and prepation :param cmd_mod: Union[iterable, pack...
80,033
def cc(bond, bond_length): """" Divides the CC bond range into five types for better coverage of physically relevant bonds """ # TODO: Automate division process if bond == "CC": if bond_length < 1.206: bond = "C1" elif bond_length < 1.325: bond = "C2" ...
80,034
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Danfoss Air HRV switch platform.""" from pydanfossair.commands import ReadCommand, UpdateCommand data = hass.data[DANFOSS_AIR_DOMAIN] switches = [ [ "Danfoss Air Boost", ReadCommand.boost...
80,035
def callBigDlFunc(bigdl_type, name, *args): """ Call API in PythonBigDL """ jinstance = JavaCreator.instance(bigdl_type=bigdl_type).value sc = get_spark_context() api = getattr(jinstance, name) return callJavaFunc(sc, api, *args)
80,036
def k_fold_cross_valid(k, epochs, verbose_epoch, X_train, y_train, learning_rate, weight_decay, batch_size): """Conducts k-fold cross validation for the model.""" assert k > 1 fold_size = X_train.shape[0] // k train_loss_sum = 0.0 test_loss_sum = 0.0 for test_idx in range...
80,037
def format_indentation(string): """ Replace indentation (4 spaces) with '\t' Args: string: A string. Returns: string: A string. """ return string.replace(" ", "&nbsp;&nbsp;&nbsp;&nbsp;")
80,038
def remove(app_id): """ Remove a bundle ID or command as being allowed to use assistive access. app_id The bundle ID or command to remove from assistive access list. CLI Example: .. code-block:: bash salt '*' assistive.remove /usr/bin/osascript salt '*' assistive.remove c...
80,039
def main(): """Main function""" set_seed(1) prefix = config.eval_mindrecord_prefix config.test_images = config.imgs_path config.test_txts = config.annos_path mindrecord_dir = config.mindrecord_dir mindrecord_file = os.path.join(mindrecord_dir, prefix) print("CHECKING MINDRECORD FILES ......
80,040
def get_sync_group(database_name: Optional[str] = None, resource_group_name: Optional[str] = None, server_name: Optional[str] = None, sync_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSyncGroupRe...
80,041
def kneel_down(score_diff, timd, secs_left, dwn): """Return 1 if the offense can definitely kneel out the game, else return 0.""" if score_diff <= 0 or dwn == 4: return 0 if timd == 0 and secs_left <= 120 and dwn == 1: return 1 if timd == 1 and secs_left <= 87 and dwn == 1: ...
80,042
def set_global_cache(cache_type: str, cache_backend: joblib.Memory) -> None: """ Set global cache by cache type. :param cache_type: type of a cache :param cache_backend: caching backend """ if _TRACE_FUNCS: _LOG.debug("") _dassert_is_valid_cache_type(cache_type) global _MEMORY_C...
80,043
def create_wrappers_for_header_file(path: Union[str, PathLike[str]], out_dir: str, include_dir: Union[str, PathLike[str]], init_file: TextIO, namespace: Collection[str] = None,...
80,044
def test_examples(): """ Examples from the puzzle description. """ assert sum_all_numbers([1, 2, 3]) == 6 assert sum_all_numbers({"a": 2, "b": 4}) == 6 assert sum_all_numbers([[[3]]]) == 3 assert sum_all_numbers({"a": {"b": 4}, "c": -1}) == 3 assert sum_all_numbers({"a": [-1, 1]}) == 0 ...
80,045
def get_top_ngrams(vectorizer, top_n=5): """ Get highest ranking ngrams of a feature matrix :param vectorizer: vectorizer object :param top_n: amount of top n-grams to return :return: top n-grams """ indices = np.argsort(vectorizer.idf_)[::-1] features = vectorizer.get_feature_names() ...
80,046
def variational_kmeans(mesh, vector_field, n_clusters, iters, tol): """ An instance of VariationalKMeans. """ return VariationalKMeans(mesh, vector_field, n_clusters, iters, tol)
80,047
def push(ctx): # pylint: disable=unused-argument """ Push (upload) a new package to a repository. At the moment you need to specify the package format (see below) of the package you're uploading. Each package format may have additional options/parameters that are specific to that package format (e...
80,048
def fail_message(e): """ Print failure message """ template = "An exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(e).__name__, e.args) print(message)
80,049
def replace_ids(fpath): """ TODO """ youtube_id_expr = r"([a-zA-Z0-9_-]{11})\.mp3" ytid_map = dict() lines = [] with open(fpath, "r") as f: for line in f: match = re.search(youtube_id_expr, line) if match: youtube_id = os.path.splitext(match.g...
80,050
def _get_api_key(): """Returns string with API key to access ResultStore. Intended to be used in Kokoro envrionment.""" api_key_directory = os.getenv('KOKORO_GFILE_DIR') api_key_file = os.path.join(api_key_directory, 'resultstore_api_key') assert os.path.isfile(api_key_file), 'Must add --api_key arg if...
80,051
def _parse_function_doc(doc): """ Takes a function and returns the params and return value as a tuple. This is nothing more than a docstring parser. TODO docstrings like utime(path, (atime, mtime)) and a(b [, b]) -> None TODO docstrings like 'tuple of integers' """ # parse round parentheses...
80,052
def train(train_loader, model, criterion, optimizer, epoch, opt, CUTMIX = False,cam = None): """one epoch training""" model.train() batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() end = time.time() if 'cut' in opt.aug: CUTMI...
80,053
def get_contours(image): """ For input image use `cv2.findContours` function to get a list of contour objects. Args: image (numpy.ndarray): Input image. Returns: list of contour objects: List of contour objects extracted from the image. """ # NOQA E501 #...
80,054
def encode(n, b=58): """ :param n: 压缩的数字 :param b: 进制 最大58 :return: 对应进制字符串 """ result = '' x = int(n) while True: x, y = divmod(x, b) result = baseList[y] + result if x <= 0: break return result
80,055
def test_add_transition() -> None: """Test adding a transition to the transition FSM""" # 0 -> 1 -> 0 -> 2 -> 0 -> 1 # Adjacency List # 0 : {1: 2, 2: 1} # 1 : {0: 1} # 2: {0: 1} fsm = TransitionFSM() state_ids = [0, 1, 0, 2, 0, 1] active_id = state_ids[0] for next_id in state_id...
80,056
def check_results(conf, expected_lines): """ Checks the benchmark results """ clean_dir("results") set_working_directory("reporting") subprocess.check_call(["Rscript", "check_results.R"]) if expected_lines: last_measurement_filter = [str(conf.Sequences), ...
80,057
def convert_currency_string_to_float(money: str): """ Utility function which gives a numerical representation of the given string containing a money value. Handles conversion from 'million'. :param money: String containing the money value :return: Float representing the money mentioned in the string...
80,058
def quantity_string(quantity, unit, computer_prefix=False): """Return a human-friendly string representing a quantity by adding prefixes and keeping the number of significant figures low. 'computer_prefix' determines whether each prefix step represents 1024 or 1000. Examples: >>> quantity_strin...
80,059
def loadConfigFile(filename): """ Load just a single YAML configuration file """ with open(filename, 'r') as f: config = yaml.load(f) # Validate if not config: raise ValueError( 'This configuration file contains no meaningful information') # Process includes includes = [] if 'include...
80,060
def get_current_version_by_config_file() -> str: """ Get current version from the version variable defined in the configuration :return: A string with the current version number :raises ImproperConfigurationError: if version variable cannot be parsed """ debug('get_current_version_by_config_fil...
80,061
def populate_context(dbot_scores: list, domain_entries: list, file_entries: list, url_entries: list, email_entries: list = None) -> dict: """ Populate the context object with entries as tuples - the first element contains global objects and the second contains PhishLabs objects :par...
80,062
def round_datetime(dt, period, tzinfo=pytz.UTC, force=False): """ Rounds a datetime to the nearest period. Valid periods are: minute, minute-15, hour, day, week :type dt: datetime :param dt: A naive or aware datetime object. :type period: str :param period: Options are minute, minute-1...
80,063
def force_categorical_determination(table): """ Find string columns using 'computationally expensive' approach """ source_shape = table.shape columns_number = source_shape[1] if len(source_shape) > 1 else 1 categorical_ids = [] non_categorical_ids = [] # For every column in table make check for...
80,064
def _apply_words(nums): """ Get the corresponding words for a list of 11-bit numbers. Args: nums (int[]): list of 11-bit numbers Returns: str[]: list of words """ return [index_to_word[n] for n in nums]
80,065
def FCN_32s(input_shape, n_class, encoder_name, encoder_weights=None, fc_num=4096, weight_decay=1e-4, kernel_initializer="he_normal", bn_epsilon=1e-3, bn_momentum=0.99, dropout=0.5): """ implementation of FCN...
80,066
def test_run_by_setting_attributes(): """Test running a HydroTrend simulation.""" d = Dakota(method="vector_parameter_study", plugin="hydrotrend") d.template_file = os.path.join(data_dir, "HYDRO.IN.dtmpl") d.auxiliary_files = os.path.join(data_dir, "HYDRO0.HYPS") d.variables.descriptors = [ ...
80,067
def leave_workspace(workspace_id): """Exit from a member of the workspace - ワークスペースのメンバーから抜けます Args: workspace_id (int): workspace ID Returns: Response: HTTP Respose """ app_name = multi_lang.get_text("EP020-0001", "ワークスペース情報:") exec_stat = multi_lang.get_text("EP020-0010", "退去...
80,068
def test_reads_with_some_buffer(): """test BR reads empty data from stdout""" attrs = {'stdout.read.return_value': b'line\nbuff'} process = mock.Mock(**attrs) old_buffer = 'simple ' buf_reader = BufferReader(process, '\n', last_buffer=old_buffer) lines = buf_reader.read() assert lines[0] == ...
80,069
def set_left_speed(bus, speed): """Set left motor speed.""" bus.write_word_data(EPUCK_I2C_ADDR, LEFT_MOTOR_SPEED, convert_speed(speed))
80,070
def L2d1(x): """ First derivative of the quadratic lagrange basis function. :param x: points to interpolate :type x: numpy array (npoints) :return: basis weights :rtype: numpy array(npoints, 3) """ L1 = 1-x return numpy.array([ 1.0 - 4.0 * L1, 4.0 * L1 - 4.0 * x,...
80,071
def get_calls(article_name, number_of_lines=7): """ returns hover data in raw format this is used in app callbacks to display hover summary data in a text box just enter article name like "Atom" or "Proton" """ S = requests.Session() URL = "https://en.wikipedia.org/w/api.php" PARAMS = {...
80,072
def vector_to_dictionary(vector, layers): """ Convert the parameter vector of a model into a dictionary used by the model Arguments: vector -- one-dimensional vector in orders: "W1", "W2", "WL", "b1", "b2", "bL" layers -- list of (n_uints, activations) pairs that define network structure,...
80,073
def test_position_short_close(): """ Tests that the properties on the Position are calculated for a short opening trade and subsequent closing trade. """ # Initial short details asset = 'EQ:TSLA' quantity = -100 dt = pd.Timestamp('2020-06-16 15:00:00', tz=pytz.UTC) price = 982.13...
80,074
def prettify_soup(soup: bs4.BeautifulSoup) -> str: """Generate an HTML string of a BeautifulSoup paper document that is slightly more readable than simply calling str(soup). Args: soup (bs4.BeautifulSoup): Paper soup Returns: str: HTML (UTF-8 encoded) """ # Only insert newlines...
80,075
def compute_vanderwaals(traj_frag_molid, frame_idx, index_to_label, sele_id, VDW_EPSILON, VDW_RES_DIFF): """ Compute all vanderwaals interactions in a frame of simulation Parameters ---------- traj_frag_molid: int Identifier to simulation fragment in VMD frame_idx: int Frame num...
80,076
def load_text(filepath): """Loads text from a file and returns it as a string. Args: filepath (str): The path to the file to be loaded. Returns: text (str): The text loaded from the file. Examples -------- >>> load_text('text.txt') """ with open(filepath, encoding='utf...
80,077
def f_call_one_optional_kwd(a, /, *, b=2): """ >>> f_call_one_optional_kwd(1) (1, 2) >>> f_call_one_optional_kwd(1, b=3) (1, 3) """ return (a,b)
80,078
def send_post_request(url, data: dict = None, **kwargs) -> dict: """ 发起post请求 :param url: 请求目标地址 :param data: 请求参数 :param kwargs: :return: """ try: resp_dict = requests.post(url, data=json.dumps(data), **kwargs).json() except Exception as e: resp_dict = {} LOG...
80,079
def test_cli_note_import_value_error(mocker, mock_nncli): """test cli_note_import failure""" mocker.patch('nncli.nncli.exec_cmd_on_note', new=mocker.Mock(return_value='{"content": "test"}')) nn_obj = nncli.nncli.Nncli(False) mocker.patch.object(nn_obj.ndb, 'import_note', ...
80,080
def show_landmarks_batch(sample_batched): """Show image with landmarks for a batch of samples.""" images_batch, landmarks_batch = \ sample_batched['image'], sample_batched['landmarks'] batch_size = len(images_batch) im_size = images_batch.size(2) grid_border_size = 2 grid = utils.ma...
80,081
def _data_type_filter(x, y): """Filter data types into acceptable format.""" if HAS_DASK: x = extract_dask_data(x) if y is not None: y = extract_dask_labels(y) if HAS_PANDAS: x = extract_pandas_data(x) if y is not None: y = extract_pandas_labels(y) return x, y
80,082
def area(int_pts, num_of_inter): """area""" area_val = 0.0 for i in range(num_of_inter - 2): area_val += abs(trangle_area(int_pts[:2], int_pts[2 * i + 2:2 * i + 4], int_pts[2 * i + 4:2 * i + 6])) return area_val
80,083
def unique(it): """Return a list of unique elements in the iterable, preserving the order. Usage:: >>> unique([None, "spam", 2, "spam", "A", "spam", "spam", "eggs", "spam"]) [None, 'spam', 2, 'A', 'eggs'] """ seen = set() ret = [] for elm in it: if elm not in seen: ...
80,084
def configure_uploads(app, upload_sets): """ Call this after the app has been configured. It will go through all the upload sets, get their configuration, and store the configuration on the app. It will also register the uploads module if it hasn't been set. This can be called multiple times with di...
80,085
def handle_ws_mqtt(message: typing.Union[str, bytes], matcher: MQTTMatcher): """Handle subscribe/publish MQTT requests from a websocket.""" assert core is not None message_dict = json.loads(message) message_type = message_dict["type"] assert message_type in [ "subscribe", "publish",...
80,086
def fontedit(fontname: Union[str, Font], **kwargs: Any) -> Iterator[Font]: """ Applies some settings to a font, and then removes them """ if isinstance(fontname, str): font = get_font(fontname) else: font = fontname defaults = {} for key in kwargs: try: defaults[...
80,087
def _quaternionAdd(quat0, quat1): """ Multiplies 2 lists of quaternions """ # Find the maximum indices to use for clipping purposes max0, max1 = quat0.shape[0]-1, quat1.shape[0]-1 maxsize = max(max0, max1) + 1 quat = np.empty((maxsize,4)) for ii in range(maxsize): index0 = min(ii, ...
80,088
def image_numbers(logfile,name="",repeat_count=[]): """Select a subset of a dataset based on critria, such a file name and repeat counts logfile: table object, must have attributes "file",Temperature","Delay" name: part of the image filname, e.g. "_offWT" repeat_count: e.g. [["Temperature",1],["Delay",0...
80,089
def valid_file(path): """Helper method for parse_args to convert to Path and verify if the file path exists. Args: path: path to file from parse_args() Returns: The absolute path of the given file path if it exists Raises: argparse.ArgumentTypeError if the file given does not ...
80,090
def optimize_epsilon(data_train, labels_train, data_test, labels_test, num_markers, method='centers', fixed_parameters={}, bounds=[(0.2 , 10)], x0=[1], max_fun_evaluations=20, n_experiments=5, clf=None, hierarchy=False, verbose=True): """ Finds the optimal value of epsilon using scipy.optimize.dual_annealing ...
80,091
def census_vip_call(*, resp, **_): """ Convert response for calling url to pandas dataframe, begin parsing df into FBA format :param resp: df, response from url call :return: pandas dataframe of original source data """ # Convert response to dataframe df = pd.read_excel(resp.content, ...
80,092
def _init_tk_type(): """ Initializes OS X Tk variant values for isAquaTk(), isCarbonTk(), isCocoaTk(), and isXQuartz(). """ global _tk_type if platform == 'darwin': root = tkinter.Tk() ws = root.tk.call('tk', 'windowingsystem') if 'x11' in ws: _tk_type = 'xqua...
80,093
def check_cyclone_xml_output(expected_file, result_file, regen=False): """ Check that expected and result_file are equal. Ignore headers. If `regen` is True the expected_file is overwritten with `results_file`. """ result = load_and_clean_xml(result_file) if regen: expected = result ...
80,094
def model_field_slugify( model_class, instance, string, filter_keys=None, exclude_keys=None, slug_field='slug'): """Slugify string based on another string and saves slug in model""" if str(string).lower() in reserved_slugs: raise ReservedSlugException('Es...
80,095
def create_read_fmt(read_id: str) -> str: """create a bitstruct format for any given read it up to 512 bits""" if len(read_id) > 64: raise ValueError("Read ID is too large") padding = 512 - len(read_id)*8 r_fmt = "t{0}p{1}".format(len(read_id)*8, padding) return r_fmt + ("u3" * 150) + ("u6" ...
80,096
def penMarksFeatures(MF, prefix='', input=[], whole_image=True, output=[]): """Obtain coordinates of the pixels at the edge of the penmarks from the tile frames in both pre- and post-MALDI microscopy datasets using matlab implementation of the SURF algorithm. Args: MF (str): path to Main Folder. ...
80,097
def load_controller_config(custom_fpath=None, default_controller=None): """ Utility function that loads the desired controller and returns the loaded configuration as a dict If @default_controller is specified, any value inputted to @custom_fpath is overridden and the default controller configuration i...
80,098
def get_job_log_file(run: Run, index: Optional[int] = None) -> str: """ Reads the job log file (70_driver_log.txt or std_log.txt) of the given job. If an index is provided, get the matching file from a multi-node job. :return: The contents of the job log file. """ assert run.status == RunStatus....
80,099