content
stringlengths
22
815k
id
int64
0
4.91M
def test_server_should_be_http_1_1(httpbin): """ The server should speak HTTP/1.1 since we live in the future, see issue #6 """ resp = get_raw_http_response(httpbin.host, httpbin.port, '/get') assert resp.startswith(b'HTTP/1.1')
63,100
def remove_ephemeral_entry(self): """Return index of the new entry to be added. The view must be in edit mode, with 'adding_new=True'. We may or may not have included whatever the user entered as a new entry in 'body', depending on whether what the user entered satisfies the entry syntax. If yes, then...
63,101
def get_P_fan_rtd_C(V_fan_rtd_C): """(12) Args: V_fan_rtd_C: 定格冷房能力運転時の送風機の風量(m3/h) Returns: 定格冷房能力運転時の送風機の消費電力(W) """ return 8.0 * (V_fan_rtd_C / 60) + 20.7
63,102
def start_session(message, websocket, metadata): """ Marks the start of a logging session, and attaches metadata to the WebSocket receiving the raw logs. """ for attribute, value in message.items(): metadata[attribute] = value metadata['startTime'] = str(datetime.datetime.now())
63,103
def clear_dir(directory): """ Removes all files in the given directory. @param directory: The path to the directory. """ for f in os.listdir(directory): path = os.path.join(directory, f) try: if os.path.isfile(path): os.unlink(path) elif os.pa...
63,104
def generate_timestamp(now=None): """Generate an enhanced CDBS-style uniqname.""" if now is None: now = datetime.datetime.utcnow() if now.year < 2016: year = chr(now.year - 2015 + ord('z')) elif 2016 <= now.year <= 2025: year = chr(now.year - 2016 + ord('0')) else: ...
63,105
def crop_2d(pts2d, Prect, bounds): """ Expects 2D coordinate points and a dict of bounds of traffic signs """ min_x = bounds['x'] - bounds['w'] max_x = bounds['x'] + bounds['w'] min_y = bounds['y'] - bounds['h'] max_y = bounds['y'] + bounds['h'] # print(min_x) # print(max_x) # print(min_y) # pri...
63,106
def covid_mask_habit(A_1, A_2, D_inverse, a_1, t_2, t_3, b_1, b_2, p, alpha, beta, r, k, habit_p): """ Description ----------- This funciton simulate the spread of two contagions on two different networks, where contagions are correlated as described in the project report. ...
63,107
def _get_http() -> httplib2.Http: """ Provides an authorized HTTP object, one per thread """ if not hasattr(_tls, "_HTTP") or _tls._HTTP is None: http = httplib2.Http(timeout=_TIMEOUT) # Use application default credentials to make the Firebase calls # https://firebase.google.com/docs/ref...
63,108
async def read_rental_states(connection=Depends(get_db)): """ Fetches rental price average per state forecasted for next 2 years """ query = f""" SELECT state, price, date FROM forecasted_rentals_states; """ df = pd.read_sql(query, connection) if len(df) > 0...
63,109
def list_deleted_matches(): """Return paginated list of deleted matches. Params: page (int): Optional. Page number to return """ received = request.get_json() if received: page = received.get('page', 1) else: page = 1 # Query matches per_page = current_app.confi...
63,110
def api_post_by_id(id): """All user CRUD operations for one single post by ID""" cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) if "lost" in id: cursor.execute("SELECT * FROM lost_pets WHERE id=%s", [id]) else: cursor.execute("SELECT * FROM found_pets WHERE id=%s", [i...
63,111
def preprocess_ical(text: str) -> List[str]: """ Removes VALARM ACTION:NONE from the iCal file (included in some events from Google Calendar) """ lines = text.splitlines() new_lines = [] i = 0 try: while i < len(lines): if lines[i] != "BEGIN:VALARM" or lines[i + 1].replace(...
63,112
def insert_to_GB_tree(tree, key): """ vstup: 'tree' korektni zelenomodry strom, do ktereho se ma vlozit novy uzel 'key' hodnota, ktera se ma vlozit do stromu 'tree' vystup: nic, upravujeme primo vstupni strom casova slozitost: O(h), kde 'h' je delka nejdelsi vetve od korene k listu """ ...
63,113
def yule_walker(X, order=1, method="unbiased", df=None, inv=False, demean=True): """ Estimate AR(p) parameters from a sequence X using Yule-Walker equation. Unbiased or maximum-likelihood estimator (mle) See, for example: http://en.wikipedia.org/wiki/Autoregressive_moving_average_model Param...
63,114
def run_tests(name, arc): """ Builds, tests and saves an oscore or an edhoc static library for a specific architecture. The tests are executed for libraries build with different optimizations. name: name of the library -- libuoscore.a or libuedhoc.a arc: the name of the architecture (the Zephyr...
63,115
def rtt_wrapper(args): """ wrapper for path() that enables trouble shooting in worker and multiple args""" try: return rtt(*args) except Exception: logging.critical("Exception in worker.") traceback.print_exc() raise
63,116
def generate_financial_amount_replacement( token: Token, financial_amounts_encountered: Dict, percentage_financial_amount_variation: int, ) -> Tuple[str, Dict]: """ Generate replacements for an amount and currency based on previous amounts generated to conserve coherence within document. Pa...
63,117
def command_seen(bot, user, channel, args): """Displays the last action by the given user""" if not args: return bot.say(channel, "Please provide a nick to search...") table = get_table(bot, channel) # Return the first match, there shouldn't be multiples anyway user = table.find_one(nick=a...
63,118
def decode_parameters(data): """ :code-block 'parameters': [{ 'required': False, 'name': 'skip', 'allowEmptyValue': True, 'in': 'query', 'enum': [0, 1], 'type': 'integer', 'description': 'offset' }] """ q...
63,119
def rotate_180_bm8(bits: int) -> int: """ bit matrixの180度回転 Parameters ---------- bits : int 対象となるbit matrix """ return flip_horizontal_bm8(flip_vertical_bm8(bits))
63,120
def delete(url: str, data: dict, header: dict): """ Issue request Param 1 - url Param 2 - data Param 3 - header Return - response object """ res = requests.delete(url, json=data, headers=header) ret = {'status_code': res.status_code} try: ret['response'] = res.json() ...
63,121
def abspath_from_egg(egg, path): """Given a path relative to the egg root, find the absolute filesystem path for that resource. For instance this file's absolute path can be found invoking `abspath_from_egg("dallinger", "dallinger/utils.py")`. Returns a `pathlib.Path` object or None if the path was ...
63,122
def update_config(args_opt): """ 补全在config中的数据集路径 Args: args_opt: config: Returns: """ if config.num_ssd_boxes == -1: num = 0 h, w = config.img_shape for i in range(len(config.steps)): num += (h // config.steps[i]) * (w // config.steps[i]) * ...
63,123
def get_tldname(): """look in /etc/hosts or /etc/hostname to determine the top level domain to use """ basename = tldname = '' with open('/etc/hosts') as hostsfile: for line in hostsfile: if not line.strip().startswith('127.0.0.1'): continue ipaddr, name =...
63,124
def set_desc(): """Handles 'mrlist setdesc'.""" mlist = List(client, args.list) mlist.setDescription(args.description)
63,125
def get_converter(content_type): """Returns converter object. All converter objects should have convert method. Parameters: content_type the type of content to check for a converter """ return CONVERTERS[content_type]
63,126
def gcp_cli(parser): """ Extend a parser with the GCP options """ parser.add_argument("--bucket", help="Storage account to write image to", default=os.environ.get("GCP_BUCKET")) parser.add_argument("--gce", help="Use GCE as the ...
63,127
def _add_asset_to_account(client, customer_id, price_asset_resource_name): """Adds a new Asset to the given user account. Adding the Asset to an account allows it to serve in all campaigns under that account. Args: client: an initialized GoogleAdsClient instance. customer_id: a client ...
63,128
def db_ok(monkeypatch): """Makes us think that our db is fine.""" monkeypatch.setattr("app.health.check_health", mock.MagicMock(return_value=True))
63,129
def eq_enable(enable): """ 是否使能音频播放器均衡功能。 :param enable(int): 是否使能均衡: 0表示不使能,1表示使能 :returns: 0: 成功,其他: 失败 :raises OSError: EINVAL """ pass
63,130
def proper_case(package_name): """Properly case project name from pypi.org.""" # Hit the simple API. r = _get_requests_session().get( "https://pypi.org/pypi/{0}/json".format(package_name), timeout=0.3, stream=True ) if not r.ok: raise IOError( "Unable to find package {0} ...
63,131
def select_from(*args, **kwds): """ Returns :py:class:`~.Select` instance and passed arguments are used for list of tables. Columns are set to `*`. """ return Select().from_(*args, **kwds)
63,132
def configurable(setting): """Return a function that only gets called if a setting is enabled.""" def decorator(func): @functools.wraps(func) def _configurable(*args, **kwargs): if settings[setting]: return func(*args, **kwargs) return _configurable retu...
63,133
def get_oss_fuzz_repo(): """Clones a temporary copy of the OSS-Fuzz repo. Returns the path to the repo.""" repo_name = 'oss-fuzz' with tempfile.TemporaryDirectory() as tmp_dir: repo_manager._clone(OSS_FUZZ_REPO_URL, tmp_dir, repo_name) yield os.path.join(tmp_dir, repo_name)
63,134
def rate_bucket(dataset, rate_low, rate_high): """Extract the movies within the specified ratings. This function extracts all the movies that has rating between rate_low and high_rate. Once you ahve extracted the movies, call the explore_data() to print first few rows. Keyword arguments:...
63,135
def copy(string: str, **kwargs: Any) -> None: """Copy given string into system clipboard.""" clip.SetText(string) return
63,136
def save_mrc(path, data, pixel_spacing): """ Save data in a mrc-file and set the pixel spacing with the `alterheader` command from IMOD. Parameters ---------- path : str Path of the new file. data : array(float) The data to save. pixel_spacing : float The pixel spaci...
63,137
def get_attributes(sitk_image): """Get physical space attributes (meta-data) of the image.""" attributes = {} attributes['orig_pixelid'] = sitk_image.GetPixelIDValue() attributes['orig_origin'] = sitk_image.GetOrigin() attributes['orig_direction'] = sitk_image.GetDirection() attributes['orig_spa...
63,138
def build_vocab(tokenized_src_trgs_pairs, opt): """Construct a vocabulary from tokenized lines.""" vocab = {} for src_tokens, trgs_tokens in tokenized_src_trgs_pairs: tokens = src_tokens + list(itertools.chain(*trgs_tokens)) for token in tokens: if token not in vocab: ...
63,139
def payback(cashflows): """The payback period refers to the length of time required for an investment to have its initial cost recovered. (This version accepts a list of cashflows) >>> payback([-200.0, 60.0, 60.0, 70.0, 90.0]) 3.1111111111111112 """ investment, ca...
63,140
def main(): """Main function. message is the message to encode or decode cipher_key is the word to use as the key to the cipher mode is set to encrypt or decrypt """ message = INPUT("What is the message you would like to use? ").replace(" ", "").lower() cipher_key = INPUT("Input the key to b...
63,141
def create_table(bqclient, table_id, schema, drop=True): """Creates a table (optionally drops if exists)""" if drop: try: bqclient.delete_table(table_id) _l.info(f'table {table_id} dropped') except: _l.debug(f'table {table_id} not found') bqclient.create...
63,142
def generate_postal_code(chance=None, variation=False, row=None): """ Function to generate the postal code of the profile. Args: chance: Integer between 1-100 used for realistic variation. (not required) variation: Boolean value indicating whether variation is requested. (optional) row: Comma delimited row f...
63,143
def vector_by_axis(axis, origin): """ Create a vector along the specified axis. :param str axis: Axis ('x', 'y', or 'z'). :param array_like origin: Origin of vector. :return: Vector along specified axis. :rtype: :class:`.Vector` """ if not isinstance(origin, Point): origin = Po...
63,144
def daily_statistics(cube, operator='mean'): """ Compute daily statistics. Chunks time in daily periods and computes statistics over them; Parameters ---------- cube: iris.cube.Cube input cube. operator: str, optional Select operator to apply. Available operators: ...
63,145
def format_excel(writer, df_size): """ Add Excel specific formatting to the workbook df_size is a tuple representing the size of the dataframe - typically called by df.shape -> (20,3) """ # Get the workbook and the summary sheet so we can add the formatting workbook = writer.book worksheet =...
63,146
def checkChangeLog(message): """ Check debian changelog for given message to be present. """ for line in open("debian/changelog"): if line.startswith(" --"): return False if message in line: return True sys.exit("Error, didn't find in debian/changelog: '%s'" %...
63,147
def is_symmetric(t): """ Returns True if the root of t is a symmetric node, and False otherwise. If t is a leaf, it returns True: ex falso quodlibet. :return: `bool` instance. """ return t.is_leaf() or \ all(isomorphic(t.children[0], ch) for ch in t.children[1:])
63,148
def fwdkin(robot, theta): """ Computes the pose of the robot tool flange based on a Robot object and the joint angles. :type robot: Robot :param robot: The robot object containing kinematic information :type theta: numpy.array :param theta: N x 1 array of joint angles. Must ha...
63,149
def load_balancers_shall_check_for_health() : """ Check that load balancers have healthcheck activated """ result = ELB_TOOLS.list_load_balancers() for lb in result : logger.info(dumps(lb)) raise Exception('Load balancer found : finalize the keyword')
63,150
def _locateNS(host=None, port=None, broadcast=True, hmac_key=None): """Get a proxy for a name server somewhere in the network.""" if host is None: # first try localhost if we have a good chance of finding it there if config.NS_HOST in ("localhost", "::1") or config.NS_HOST.startswith("127."): ...
63,151
def broadcast_send_multi_dids(cmd, *args): """ :param cmd:支持“READ”,"WRITE","REPORT","NOTIFY" :param args:gid1, gidtyp1,did1,value1,gid2,gidtyp2 did2,value2...gid1,gidtyp1,did和value顺序排列 """ role = TestEngine.instance().get_default_role() role.send_multi_dids(cmd, *args, taid=0xffffffff)
63,152
def lstm_attention_decoder(inputs, hparams, train, name, initial_state, encoder_outputs): """Run LSTM cell with attention on inputs of shape [batch x time x size].""" def dropout_lstm_cell(): return tf.contrib.rnn.DropoutWrapper( tf.nn.rnn_cell.BasicLSTMCell(hparams.hidden_si...
63,153
def check_non_linearity(item: Any) -> bool: """Evaluates whether "item" is a torch module :param item: variable to check :return: boolean """ return isinstance(item(), nn.Module) if item is not None else True
63,154
def mean_average_error(ground_truth, regression, verbose=False): """ Computes the mean average error (MAE). Args: ground_truth (list or 1-dim ndarray): ground truth labels. regression (list or 1-dim ndarray): label estimations. Must have the same length as the ground truth. ver...
63,155
def calcFlashThresholds(loSampleData, hiSampleData): """\ Analyses light sensor sample data and returns suggestions for the thresholds needed to detect the flashes. :param loSampleData: list of sample values, where each value is the lowest seen during that sampling period :param loSampleData: list ...
63,156
def test_vector_arenstorf_orbit_add(): """ Test __add__ """ vector_arenstorf_orbit_1 = VectorArenstorfOrbit() vector_arenstorf_orbit_1.y0 = 1 vector_arenstorf_orbit_1.y1 = 1 vector_arenstorf_orbit_1.y2 = 1 vector_arenstorf_orbit_1.y3 = 1 vector_arenstorf_orbit_2 = VectorArenstorfOrbi...
63,157
def pmd_load_variance(pmd_map): """ Get load variance on a set of pmds. Parameters ---------- pmd_map : dict mapping of pmd id and its Dataif_Pmd object. """ pmd_load_list = list(map(lambda o: o.pmd_load, pmd_map.values())) return util.variance(pmd_load_list)
63,158
def to_QuPath(coords, labels, dstPath, dict, size): """ Convierte los ndarrays 'coords' y 'labels' al formato necesario para poder dibujar las anotaciones en QuPath. Además guarda la salida en el fichero dstPath. * dict -- diccionario que contiene como claves los enteros que representan las etiqueta...
63,159
def RDdispSurf(X, Y, P1, P2, P3, P4, opening, nu): """ RDdispSurf calculates surface displacements associated with a rectangular dislocation in an elastic half-space. """ bx = opening Vnorm = numpy.cross(P2-P1, P4-P1) Vnorm = Vnorm/norm(Vnorm) bX = bx*Vnorm[0] bY = bx*Vnorm[1] ...
63,160
def coerce_human_date(d, datemode = None): """Attempt to coerce d into a Python datetime.date Generally d will have been retrieved from an excel spreadsheet, so I expect it to be a string or an excel date. Args: d - object to be coerced ...
63,161
def check_vcf(variants): """Check if there are any problems with the vcf file Args: variants(iterable(cyvcf2.Variant)) Returns: nr_variants(int) """ logger.info("Check if vcf is on correct format...") nr_variants = 0 previous_pos = None previ...
63,162
def main(): """ operational function """ bst = BinarySearchTree() for elem in [9, 5, 3, 10, 6, 1, 7, 4]: bst.insert(elem) preorder_traversal(bst.root) print() inorder_traversal(bst.root) print() postorder_traversal(bst.root) print()
63,163
def merge_partial_elements(element_list): """ merges model elements which collectively all define the model component, mostly for multidimensional subscripts Parameters ---------- element_list Returns ------- """ outs = dict() # output data structure # needed to preserve ...
63,164
def test_get_master_listener_no_master_listener(get_os): """If there are no Listeners with name master-listener, return None""" conn, lb = get_os conn.load_balancer.find_load_balancer.return_value = default_data() conn.load_balancer.find_listener.return_value = None assert lb._get_master_listener()...
63,165
def get_job_results(engagement_id: str, job_id: str): """Retrieve job results from S3 via authentication. :param engagement_id: str -- the engagement id :param job_id: str -- the job id to retrieve :returns: dict -- the query results """ job_results = query_job(engagement_id, job_id) if job...
63,166
def has_external_refs(*args): """has_external_refs(func_t pfn, ea_t ea) -> bool""" return _idaapi.has_external_refs(*args)
63,167
def bw_scott(x): """ Scott's Rule of Thumb Parameter --------- x : array-like Array for which to get the bandwidth Returns ------- bw : float The estimate of the bandwidth Notes ----- Returns 1.059 * A * n ** (-1/5.) A = min(std(x, ddof=1), IQR/1.349) ...
63,168
def get_bibliography(soup, file_path): """Read in a soup object and a path to that object on disk and return an object describing bibliographic data for that record""" bibliography_data = {} labels = ["printings", "citations"] bibliography = soup.find('div', {'id': 'Bibliographic'}) for o in bibliography...
63,169
def read_as_base64(path: Union[str, Path]) -> str: """ Convert file contents into a base64 string Args: path: File path Returns: Base64 string """ content = Path(path).read_text() return base64.b64encode(content.encode("utf-8")).decode("utf-8")
63,170
def estimate_affine_matrix(x1, x2): """ See https://github.com/YadiraF/face3d. """ x1 = x1.T; x2 = x2.T assert(x2.shape[1] == x1.shape[1]) n = x2.shape[1] assert(n >= 4) mean = np.mean(x2, 1) x2 = x2 - np.tile(mean[:, np.newaxis], [1, n]) average_norm = np.mean(np.sqrt(np...
63,171
def get_verifiers(stage, test_block_config, sessions, expected): """Get one or more response validators for this stage Args: stage (dict): spec for this stage test_block_config (dict): variables for this test run sessions (dict): all available sessions expected (dict): expected ...
63,172
def calcTissueRatio(bird): """ Calculates proportion of whole tissue mass out of total body mass. """ for bird_id,bird_obj in bird.items(): tissue_r = {} for tissue_type, tissue_obj in bird_obj.tissues.items(): key = tissue_type value = float(tissue_obj.mass_total...
63,173
def cms_scan(self): """ CMS component task """ blacklist = list(range(42, 55)) + [58, 106] blacklist = [IPv4Network(f"147.251.{x}.0/24") for x in blacklist] client = CMSClient(bolt=self.neo4j_addr, password=self.neo4j_passwd) res = client.get_ips_and_domain_names().value() stats = 0 ...
63,174
def immerge(images, row, col): """Merge images. merge images into an image with (row * h) * (col * w) `images` is in shape of N * H * W(* C=1 or 3) """ if images.ndim == 4: c = images.shape[3] elif images.ndim == 3: c = 1 h, w = images.shape[1], images.shape[2] if c > ...
63,175
def tests(session, django): """Run test suite with pytest.""" # Skip tests for unsupported matrix values. if session.python == "3.7" and django in ( "Django>=4.0a1,<5.0", "https://github.com/django/django/archive/main.tar.gz", ): session.skip("Unsupported Django version and pytho...
63,176
def type_equals(e, t): """ Will always return true, assuming the types of both are equal (which is checked in compare_object) """ return True
63,177
def create_tenant() -> str: """Create Tenant.""" tenant, _ = Tenant.objects.get_or_create(name=TENANT_NAME) tenant.validated_save() return TENANT_NAME
63,178
def c(): """ CvPoint2D32f and CvPoint are just tuples. No point writing exercises. """
63,179
def result_to_maybe( result_container: Result[_ValueType, _ErrorType], ) -> Maybe[_ValueType]: """ Converts ``Result`` container to ``Maybe`` container. .. code:: python >>> from returns.maybe import Some, Nothing >>> from returns.result import Failure, Success >>> assert result_to_...
63,180
def test_event_edit_button_not_rended_for_anon_user(client, stocking_events): """ A button or link to edit a stocking event should NOT be included in the response for an anonymus user """ for event in stocking_events: url = reverse( "stocking:stocking-event-detail", kwargs={"s...
63,181
def extract_archive(fname, targetdir=None, verbose=False): """Extract .zip, .exe (considered to be a zip archive) or .tar.gz archive to a temporary directory (if targetdir is None). Return the temporary directory path""" if targetdir is None: targetdir = _create_temp_dir() else: try:...
63,182
def calculaterND(_ranking_k,_pro_k,items_n,proItems_n): """ Calculate the normalized difference of input ranking :param _ranking_k: A permutation of k numbers that represents a ranking of k individuals, e.g., [0, 3, 5, 2, 1, 4]. Each number is an identifier ...
63,183
def point_to_rhino_point(pt): # type: (compas.geometry.Point) -> rg.Point3d """Convert :class:`compas.geometry.Point` to :class:`Rhino.Geometry.Point3d`.""" return rg.Point3d(*pt.data)
63,184
def get_default_gateway(): """ Returns the default gateway """ octet_list = [] gw_from_route = None f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): gw_from_route = words[2] ...
63,185
def parse_dict_items(s, label_col, val_col): """ Parse the dictionary embedded in a text columns. The resulting data frame will tuples. This assumes the values in the dict are integers. TODO: improve this. Use this when the # of dictionary items differs. """ s_split = s_split ...
63,186
def nrmse(image, reference_image): """ Compute the normalized root mean square error between image and reference_image. Args: image: Calculated image reference_image: Ground truth image Returns: Root mean square of (image - reference_image) divided by RMS of reference_image "...
63,187
def samples_create(request): """ create new samples """ pass
63,188
def get_known_transports(): """Return a dictionary of all known transport mechanisms.""" if not hasattr(get_known_transports, "cache"): setattr( get_known_transports, "cache", { e.name: e.load() for e in pkg_resources.iter_entry_points(...
63,189
def test_display(): """ UC1701X LCD screen can draw and display an image. """ device = uc1701x(serial) serial.reset_mock() recordings = [] def data(data): recordings.append({'data': data}) def command(*cmd): recordings.append({'command': list(cmd)}) serial.command...
63,190
def make_gif(): """ 制作一张GIF图片 """ def make_number_img(t): size = (80, 60) img = Image.new('RGB', size, (255, 255, 255)) # 创建Font对象: # font = ImageFont.truetype('Arial.ttf', 36) # 创建Draw对象: draw = ImageDraw.Draw(img) draw.text((35, 25), t, fill='red') ...
63,191
def get_full_name(qt_ptr): """ Get full name of qt widget from pointer Args: qt_ptr (ptr): Pointer to QWidget Returns: (unicode): full name of qt widget """ return omUI.MQtUtil.fullName(long(qt_ptr))
63,192
def class_combinations(c, n, m=np.inf): """ Generates an array of n-element combinations where each element is one of the c classes (an integer). If m is provided and m < n^c, then instead of all n^c combinations, m combinations are randomly sampled. Arguments: c {int} -- the number of classes ...
63,193
def dropout(X, rate, test_mode=False): """ Applies dropout to input matrix X using the given dropout rate [0,1). If test_mode is false, returns pair (Z, M) where Z = M * X and M is a matrix of bernoulli trials (M.dtype is bool). If test_mode is True, returns pair (Z, None) where Z = (1-rate)*...
63,194
def read_config(config_file): """Reads a config XML file to find extra projects to add or remove. Args: config_file: The filename of the config XML. Returns: A tuple of (set of remove_projects, set of add_projects) from the config. """ root = ET.parse(config_file).getroot() remove_projects = set( ...
63,195
def get_side_effect_targets_fishers(drug_to_geneids, drug_to_side_effects, cutoff=0.2, correct_pvalues=True): # min_n_drug=5, """ cutoff: p-value or fdr cutoff (0.2) correct_pvalues: apply multiple hypothesis testing (True) (obselete) min_n_drug: Consider only side effects that are associated with at l...
63,196
def set_active_design(oProject, designname): """ Set the active design. Parameters ---------- oProject : pywin32 COMObject The HFSS design upon which to operate. designname : str Name of the design to set as active. Returns ------- oDesign : pywin32 COMObjec...
63,197
def to_fs_encoding(value): """ Convert an unicode value to a str in the filesystem encoding. """ if not isinstance(value, unicode): raise TypeError("expected a unicode value") return value.encode(sys.getfilesystemencoding())
63,198
def init_encoders(): """ Initializes label and one hot encoders from sklearn. This is needed to avoid creating 2 encoder objects for each encoded sequence. :return: a tuple representing label_enoder, ohe_encoder """ integer_encoder = LabelEncoder() one_hot_encoder = OneHotEncoder(sparse=Fals...
63,199