content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def is_json_request_accept(req): """Test if http request 'accept' header configured for JSON response. :param req: HTTP request :return: True if need to return JSON response. """ return ( type(req.accept) is accept.NoHeaderType or type(req.accept) is accept.ValidHeaderType and ( ...
1a73946c5d090b905ceb09d2841efc316659a90d
28,561
def make_hierarchy(parent_ps, relative_size, make_subsys, *args, **kwargs): """ """ parent_size = parent_ps.radial_size ps = ParticleSystem() for p in parent_ps: subsys = make_subsys(*args, **kwargs) subsys.dynrescale_total_mass(p.mass) subsys_size = relative_size * parent_...
3381290bca4791f1ad342b9478855bdaf1646b22
28,562
def get_site_stats(array, player_names): """ Return the summarized statistics for a given array corresponding to the values sampled for a latent or response site. """ if len(array.shape) == 1: df = pd.DataFrame(array).transpose() else: df = pd.DataFrame(array, columns=player_name...
7105e5cd932675f812ec9b7c3c4299b138af49b2
28,564
def new(data=None, custom=None): """Return a fresh instance of a KangarooTwelve object. Args: data (bytes/bytearray/memoryview): Optional. The very first chunk of the message to hash. It is equivalent to an early call to :meth:`update`. custom (bytes): Optional. ...
5177ce6dccdc7ec7b764f90748bfda48b1c6bf6f
28,565
def document_edit(document_id: int): """Edits document entry. Args: document_id: ID of the document to be edited """ document = Upload.get_by_id(document_id) if not document: return abort(404) form = DocumentEditForm() if request.method == 'GET': form.name.data = do...
5233466553b98566c624a887e0d14556f6edeae9
28,566
from typing import Union from typing import List def get_output_tensors(graph: Union[tf.Graph, GraphDef]) -> List[str]: """ Return the names of the graph's output tensors. Args: graph: Graph or GraphDef object Returns: List of tensor names """ return [node.tensor for node in ...
598e1e5d223875bc2e094127ab40dfc84a05f2f8
28,567
def create_build_list(select_repo, all_repos_opt): """Create a list of repos to build depending on a menu that the user picks from.""" if all_repos_opt is True: build_list = repo_info.REPO_LIST print "Building repos: " + str(build_list) print "\n" return build_list # If the ...
3976d4479c2c8ee8c8381362e00aadb161dc5701
28,568
def hinton(matrix, significant=None, max_weight=None, ax=None): """Draw Hinton diagram for visualizing a weight matrix.""" ax = ax if ax is not None else plt.gca() if not max_weight: max_weight = [2 ** np.ceil(np.log(np.abs(matrix[i]).max()) / np.log(2)) for i in range(matrix.shape[0])] ax.pat...
93e3b4ed863e7542d243ccb5c33fe5187046f3a6
28,570
def to_bin(s): """ :param s: string to represent as binary """ r = [] for c in s: if not c: continue t = "{:08b}".format(ord(c)) r.append(t) return '\n'.join(r)
b4c819ae25983a66e6562b3677decd8389f5fbe2
28,571
def get_bppair(bamfile, bp_cand_df, \ seq_len = 50, seed_len = 5, min_nt = 5, match_method = 'fuzzy_match'): """ get the bppairs from bp_cand_stats (a list of bps) parameters: seq_len - # bases within breakend seed_len - # of bases up and down stream of the breakend in assembled b s...
be37ded59aac2cd481e3891e8660b4c08c7327ee
28,572
def get_dropdown_items(df: pd.DataFrame, attribute: str) -> list: """ Returns a list of dropdown elements for a given attribute name. :param df: Pandas DataFrame object which contains the attribute :param attribute: str, can be either port, vessel_type, year, or month :return: list of unique attrib...
c66b17cc4e47e05604b7cc6fde83fd2536b25962
28,573
import time def RunFromFile(): """Take robot commands as input""" lm = ev3.LargeMotor("outC") assert lm.connected # left motor rm = ev3.LargeMotor("outA") assert rm.connected # right motor drive = ReadInDirection() t0 = time.time() a = True while a: a = drive.run() t1...
e77546cef50c27d292deb22f65a524a7d402a640
28,574
def veljavna(barva, di, dj, polje, i, j): """Če je poteza v smeri (di,dj) na polju (i,j) veljavna, vrne True, sicer vrne False""" #parametra di in dj predstavljata spremembo koordinate i in koordinate j #npr. če je di==1 in dj==1, se pomikamo po diagonali proti desnemu spodnjemu #robu plošče in pre...
128cf01f8947a30d8c0e4f39d4fd54308892a103
28,575
def _do_filter(items, scores, filter_out, return_scores, n): """Filter items out of the recommendations. Given a list of items to filter out, remove them from recommended items and scores. """ # Zip items/scores up best = zip(items, scores) return _recommend_items_and_maybe_scores( ...
644cdbe1072dfa397e58f9d51a21fc515d569afe
28,576
def userlogout(request): """ Log out a client from the application. This funtion uses django's authentication system to clear the session, etc. The view will redirect the user to the index page after logging out. Parameters: request -- An HttpRequest Returns: An HttpRespon...
e12bb923268592841f0c98613ab0226f56c8cbf6
28,577
def regularize(dn, a0, method): """Regularization (amplitude limitation) of radial filters. Amplitude limitation of radial filter coefficients, methods according to (cf. Rettberg, Spors : DAGA 2014) Parameters ---------- dn : numpy.ndarray Values to be regularized a0 : float ...
fe4722a273060dc59b5489c0447e6e8a79a3046f
28,580
from typing import Optional def get_fields_by_queue(client: Client, queue: Optional[list]) -> list: """ Creating a list of all queue ids that are in the system. Args: client: Client for the api. Returns: list of queue ids. """ if queue: queues_id = queue else: ...
a6ee562e50ec749ec9132bf39ca0e39b0336bdbc
28,581
def emitter_20(): """Interval, emit from center, velocity fixed speed around 360 degrees""" e = arcade.Emitter( center_xy=CENTER_POS, emit_controller=arcade.EmitterIntervalWithTime(DEFAULT_EMIT_INTERVAL, DEFAULT_EMIT_DURATION), particle_factory=lambda emitter: arcade.LifetimeParticle( ...
6a7d6689299cab15fbe6ab95e6bb62164ae09657
28,582
def add_mask_rncc_losses(model, blob_mask): """Add Mask R-CNN specific losses""" loss_mask = model.net.SigmoidCrossEntropyLoss( [blob_mask, 'masks_init32'], 'loss_mask', scale=model.GetLossScale() * cfg.MRCNN.WEIGHT_LOSS_MASK ) loss_gradients = blob_utils.get_loss_gradients(model...
e8ae0e80e2ca3ce6f7782173872f4d3e01c916c1
28,583
def fixed_discount(order: Order): """ 5k fixed amount discount """ return Decimal("5000")
867a98049e19aea03d421c37141dbc7acd651fc9
28,584
def index(): """ The index page. Just welcomes the user and asks them to start a quiz. """ return render_template('index.html')
13e70c6fd82c11f3cd6aed94b043fd1110e65c3c
28,585
from typing import BinaryIO def parse_element(stream: BinaryIO): """Parse the content of the UPF file to determine the element. :param stream: a filelike object with the binary content of the file. :return: the symbol of the element following the IUPAC naming standard. """ lines = stream.read().d...
2911d7ee97df77fd02bbd688a5044c8ba6f5434e
28,586
from typing import Optional from typing import List from typing import Any from typing import Type def mention_subclass( class_name: str, cardinality: Optional[int] = None, values: Optional[List[Any]] = None, table_name: Optional[str] = None, ) -> Type[Mention]: """Create new mention. Creates...
1639f19609b3b815a25e22729b3b0379caf13ac2
28,587
def undupe_column_names(df, template="{} ({})"): """ rename df column names so there are no duplicates (in place) e.g. if there are two columns named "dog", the second column will be reformatted to "dog (2)" Parameters ---------- df : pandas.DataFrame dataframe whose column names shoul...
51d13bad25571bc60edd78026bb145ff99281e2d
28,588
def get_example_data(dataset_name): """ This is a smart package loader that locates text files inside our package :param dataset_name: :return: """ provider = get_provider('ebu_tt_live') manager = ResourceManager() source = provider.get_resource_string(manager, 'examples/'+dataset_name)...
5f5f3fd3485f63a4be2b85c2fed45a76e2d53f7c
28,590
def js(data): """ JSをミニファイ """ # 今のところは何もしない return data
2ee82b81dcb3cfb9d133ed218ba1c67b5d16f691
28,591
def _has_endpoint_name_flag(flags): """ Detect if the given flags contain any that use ``{endpoint_name}``. """ return '{endpoint_name}' in ''.join(flags)
e8827da778c97d3be05ec82ef3367686616d3a88
28,592
def convert_example(example, tokenizer, max_seq_len=512, max_response_len=128, max_knowledge_len=256, mode='train'): """Convert all examples into necessary features.""" goal = example['goal'] knowledge = exam...
5ebce39468cda942f2d4e73cd18f8fa4dd837f0a
28,593
def mag2Jy(info_dict, Mag): """Converts a magnitude into flux density in Jy Parameters ----------- info_dict: dictionary Mag: array or float AB or vega magnitude Returns ------- fluxJy: array or float flux density in Jy """ fluxJy=info_dict['Fl...
db8a56e1ca0529cd49abd68dea65ce6aeff7fd22
28,594
def load_array(data_arrays, batch_size, is_train=True): """Construct a PyTorch data iterator. Defined in :numref:`sec_utils`""" dataset = ArrayData(data_arrays) data_column_size = len(data_arrays) dataset = ds.GeneratorDataset(source=dataset, column_names=[str(i) for i in range(data_column_size)], s...
804da2b88eceaeb84e2d5d6a3961aa12df958da3
28,595
def do_get_batched_targets(parser, token): """ Retrieves the list of broadcasters for an action and stores them in a context variable which has ``broadcasters`` property. Example usage:: {% get_batched_targets action_id_list parent_action_id as batched_targets %} """ bits = token.conte...
b4847c5acc480b88c0a9cd7b44467f307eed0d65
28,596
def task_success_slack_alert(context): """ Callback task that can be used in DAG to alert of successful task completion Args: context (dict): Context variable passed in from Airflow Returns: None: Calls the SlackWebhookOperator execute method internally """ slack_webhook_token...
596694b089f758a683eac677d7ca237a253a2bd2
28,597
import base64 def return_img_stream(img_local_path): """ 工具函数: 获取本地图片流 :param img_local_path:文件单张图片的本地绝对路径 :return: 图片流 """ img_stream = '' with open(img_local_path, 'rb') as img_f: img_stream = img_f.read() img_stream = base64.b64encode(img_stream) return img_strea...
7ddee56650fcfabf951ca9b5844a08c7ae5fb2b7
28,598
from typing import Optional from typing import Dict from typing import Union from typing import Any def filter_log_on_max_no_activities(log: EventLog, max_no_activities : int = 25, parameters: Optional[Dict[Union[str, Parameters], Any]] = None) -> EventLog: """ Filter a log on a maximum number of activities ...
b09d376a758a10f784fd2b9f7036cc6e0d58be05
28,599
def GSSO( directed = False, preprocess = "auto", load_nodes = True, load_node_types = True, load_edge_weights = True, auto_enable_tradeoffs = True, sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None, cache_sys_var = "GRAPH_CACHE_DIR", version = "2.0.5", **kwargs ) -> Graph: """Return ...
ac5722afae3bb28321aa9d465873b12852b1f2f6
28,600
from typing import Optional from typing import Union from typing import Sequence from typing import Dict def tb( data: pd.DataFrame, columns: Optional[Union[Sequence[str], pd.Index]] = None, subscales: Optional[Dict[str, Sequence[int]]] = None, ) -> pd.DataFrame: """Compute the **Technology Commitment...
ac92f6ed7dd484e076b80db32fff6bc9fdd64619
28,601
def format_date(date: str): """ This function formats dates that are in MM-DD-YYYY format, and will convert to YYYY-MM-DD, which is required sqlite. :param date: The date to modify. :return: The modified string. """ tmp = date.split("/") return "{}-{}-{}".format(tmp[2], tmp[0], tmp[1])
f1a0149bfd96db557c49becdedb84789daa1168c
28,602
def _doUpgradeApply(sUpgradeDir, asMembers): """ # Apply the directories and files from the upgrade. returns True/False/Exception. """ # # Create directories first since that's least intrusive. # for sMember in asMembers: if sMember[-1] == '/': sMember = sMember[len(...
a181e710db010733828099a881ee7239f90674a7
28,603
def _parse_atat_lattice(lattice_in): """Parse an ATAT-style `lat.in` string. The parsed string will be in three groups: (Coordinate system) (lattice) (atoms) where the atom group is split up into subgroups, each describing the position and atom name """ float_number = Regex(r'[-+]?[0-9]*\.?[0-9]+([...
4cb40f7c25519bc300e389d0a2d72383dda3c7f0
28,604
from typing import Union def datetime_attribute_timeseries(time_index: Union[pd.DatetimeIndex, TimeSeries], attribute: str, one_hot: bool = False) -> TimeSeries: """ Returns a new TimeSeries with index `time_index` and one or more dimensions ...
9330f22d7b81aaeb57130563a3f32009e48e3fe0
28,605
def hexscale_from_cmap(cmap, N): """ Evaluate a colormap at N points. Parameters ---------- cmap : function a function taking a scalar value between 0 and 1 and giving a color as rgb(a) with values between 0 and 1. These are for example the pyplot colormaps, like plt.cm.viri...
0c26f7b404ac3643317db81eacac83d0d62e5f80
28,606
def getFirebaseData(userID): """ This gets the data from the Firebase database and converts it to a readable dictionary Args: userID (string): the id of the user """ cred = credentials.Certificate("serviceAccountKey.json") a = firebase_admin.initialize_app(cred) ourDatabase = f...
4da109004771908009ed431ad69a25ac52d0969c
28,607
def gen_tracer(code, f_globals): """ Generate a trace function from a code object. Parameters ---------- code : CodeType The code object created by the Enaml compiler. f_globals : dict The global scope for the returned function. Returns ------- result : FunctionType ...
abb9e043ad12f4ced014883b6aee230095b63a18
28,608
def MAD(AnalogSignal): """ median absolute deviation of an AnalogSignal """ X = AnalogSignal.magnitude mad = sp.median(sp.absolute(X - sp.median(X))) * AnalogSignal.units return mad
069231a87e755de4bff6541560c0e5beabc91e0d
28,609
def angular_frequency(vacuum_wavelength): """Angular frequency :math:`\omega = 2\pi c / \lambda` Args: vacuum_wavelength (float): Vacuum wavelength in length unit Returns: Angular frequency in the units of c=1 (time units=length units). This is at the same time the vacuum wavenumber. "...
305349cff0d7b9489d92eb301c6d058ca11467f0
28,610
def web_urls(): """Builds and returns the web_urls for web.py. """ urls = ( '/export/?', RestHandler, '/export/bdbag/?', ExportBag, '/export/bdbag/([^/]+)', ExportRetrieve, '/export/bdbag/([^/]+)/(.+)', ExportRetrieve, '/export/file/?', ExportFiles, '/export/f...
d2580499a7b4bad8c94494fd103a2fe0f6d607d6
28,611
import torch def box_cxcywh_norm_to_cxcywh(box: TensorOrArray, height: int, width: int) -> TensorOrArray: """Converts bounding boxes from (cx, cy, w, h) norm format to (cx, cy, w, h) format. (cx, cy) refers to center of bounding box. (a, r) refers to area (width * height) and aspect ratio (width ...
7cf112b7f3420161513e4b70ef531fb586074431
28,612
def lyrics_from_url(url): """Return a tuple with song's name, author and lyrics.""" source = identify_url(url) extractor = { 'letras': (lyrics_from_letrasmus, info_from_letrasmus), 'vagalume': (lyrics_from_vagalume, info_from_vagalume) } html = html_from_url(url) if source in ex...
2034c1ee26ce563f227f49de10b7e1b56092c7c8
28,613
import json def _get_pycons(): """Helper function that retrieves required PyCon data and returns a list of PyCon objects """ with open(pycons_file, "r", encoding="utf-8") as f: return [ PyCon( pycon["name"], pycon["city"], pycon["c...
749947829d4c28b08f957505d8ede02fe8d5ecbb
28,614
def f_function(chromosome): """Define Fitness Function Here.""" x = chromosome.convert_to_integer() return (15 * x[0]) - (x[0] * x[0]) # return (((15 * x[0]) - (x[0] * x[0])) * -1) + 1000 To Find Minimum Solution
aee3744c63ada24302857ef4ddb4e6aff35fc69e
28,615
def _GetRevsAroundRev(data_series, revision): """Gets a list of revisions from before to after a given revision. Args: data_series: A list of (revision, value). revision: A revision number. Returns: A list of revisions. """ if not _MAX_SEGMENT_SIZE_AROUND_ANOMALY: return [revision] middle...
966e590f4cc1e017ed6d4588ca15655b9de61d7a
28,616
def get_output_length(): """Returns the length of the convnet output.""" return conv_base.layers[-1].output_shape[-1]
6471f0b1331a97147be43b464c5fb5384e185980
28,617
def rules(command, working_directory=None, root=True, **kargs): """ Main entry point for build_rules.py. When ``makeprojects``, ``cleanme``, or ``buildme`` is executed, they will call this function to perform the actions required for build customization. The parameter ``working_directory`` is requ...
9456822c0956fa847e19917b735d1a6680d0961a
28,618
def get_py_func_body(line_numbers, file_name, annot): """ Function to get method/function body from files @parameters filename: Path to the file line_num: function/method line number annot: Annotation condition (Ex: @Test) @return This function returns python function...
c6324e13831008118a39a599cce8b9ec3513b0a1
28,619
from typing import Any from typing import Union def extract_optional_annotation(annotation: Any) -> Any: """ Determine if the given annotation is an Optional field """ if ( hasattr(annotation, "__origin__") and annotation.__origin__ is Union and getattr(annotation, "__args__", ...
024e28f88005b03e45b96c739a44bd56b2115849
28,620
import itertools import json def combine_pred_and_truth(prediction, truth_file): """ Combine the predicted labels and the ground truth labels for testing purposes. :param prediction: The prediction labels. :param truth_file: The ground truth file. :return: The combined prediction and ground truth...
d7dee4add59a4b3df7e0bd3a6e5fcc981ff23d59
28,621
def calc_cogs_time_series(days, cogs_annual): """ Cost of Goods Sold Formula Notes ----- Can adjust for days/weekly/monthly/annually in the future - ASSUMED: CONSUMABLES PURCHASED MONTHLY """ cogs_time_series = [] for i in range(days): if i % DAYS_IN_MONTH == ...
b3efffc274676549f23f7a20321dd2aac02c1666
28,622
def stations(): """ Returning the all Stations """ station_list = session.query(station.name).all() jsonify_sation = list(np.ravel(station_list)) #Jsonify results return jsonify(jsonify_sation)
ce51f8551043d740657da7fc7d3f3d9afcead4d1
28,624
def test_run_sht_rudeadyet_default(tmpdir) -> int: """ Purpose: Test to make sure sht-rudeadyet run works Args: N/A Returns: (Int): 0 if passed run, -1 if not """ attack = "sht_rudeadyet" run_config = "configs/mw_locust-sht_rudeadyet.json" return magicwand_run(tmp...
072a8608dc5ac8007e62e8babbd3047fbb8b8bce
28,625
def _clean_markdown_cells(ntbk): """Clean up cell text of an nbformat NotebookNode.""" # Remove '#' from the end of markdown headers for cell in ntbk.cells: if cell.cell_type == "markdown": cell_lines = cell.source.split('\n') for ii, line in enumerate(cell_lines): ...
8b34ff6713a323340ea27f6d8f498a215ca9d98a
28,626
import asyncio def get_thread_wrapper(target, name): """Returns a target thread that prints unexpected exceptions to the logging. Args: target: Func or coroutine to wrap. name(str): Task name. """ @wraps(target) def wrapper(*args, **kwargs): try: result = targ...
75ddf5ca81825769e51fd8ed4f850ec9db18a31e
28,627
def getStructType(ea): """ Get type information from an ea. Used to get the structure type id """ flags = idaapi.getFlags(ea) ti = idaapi.opinfo_t() oi = idaapi.get_opinfo(ea, 0, flags, ti) if oi is not None: return ti else: return None
3ed8a000405f87b0e069d165dd72215852d22bd5
28,629
def confirm_email(token): """ GET endpoint that confirms the new officer user. This endpoint link is normally within the confirmation email. """ club_email = flask_exts.email_verifier.confirm_token(token, 'confirm-email') if club_email is None: raise JsonError(status='error', reason='Th...
2e8feb0607361ec0d53b3b62766a83f131ae75c6
28,630
def xcrun_field_value_from_output(field: str, output: str) -> str: """ Get value of a given field from xcrun output. If field is not found empty string is returned. """ field_prefix = field + ': ' for line in output.splitlines(): line = line.strip() if line.startswith(field_pre...
a99efe76e21239f6ba15b8e7fb12d04d57bfb4de
28,631
def get_all_markets_num(): """ 获取交易所有的市场 :return: "5/2" """ markets = list(set([str(i["stockId"]) + "/" + str(i["moneyId"]) for i in res["result"]])) return markets
33d9e49aeaa6e6d81ec199f21d4f5e40cdd0fd48
28,632
def mae(s, o): """ Mean Absolute Error input: s: simulated o: observed output: maes: mean absolute error """ s, o = filter_nan(s, o) return np.mean(abs(s - o))
313d4605bb240d8f32bc13fc62ff2cf12e22cfd8
28,633
def error_mult_gap_qa_atom( df_qc, df_qats, target_label, target_charge=0, basis_set='aug-cc-pV5Z', use_ts=True, max_qats_order=4, ignore_one_row=False, considered_lambdas=None, return_qats_vs_qa=False): """Computes QATS errors in system multiplicity gaps. Parameters ---------- df_qc : ...
3facdc35f0994eb21a74cf0b1fb277db2a70a14b
28,634
async def materialize_classpath(request: MaterializedClasspathRequest) -> MaterializedClasspath: """Resolve, fetch, and merge various classpath types to a single `Digest` and metadata.""" artifact_requirements_lockfiles = await MultiGet( Get(CoursierResolvedLockfile, ArtifactRequirements, artifact_requ...
367a0a49acfb16e3d7c0c0f1034ef946e75928a8
28,636
def Real_Entropy(timeseries): """ Calculates an approximation of the time-correlated entropy Input: timeseries: list of strings or numbers, e.g. ['1', '2', '3'] or [1, 2, 3] Output: approximation of Real Entropy (time-correlated entropy), e.g. 1.09 """ def is_sublist(ali...
a2d8948723b0f62e91a9255b3f0fb35ccf4b26d8
28,637
def hom(X, mode): """ It converts transformation X (translation, rotation or rigid motion) to homogenous form. Input: X: tf.float32 array, which can be either [B, 3] float32, 3D translation vectors [B, 3, 3] float32, rotation matrices [B, 3, 4] float32, rigid motion matrix mode: one of 'T', 'R' or 'P' deno...
e7104789e996b745a8978867925b8ea5e2c1ad01
28,638
import re def parse_sl(comments: str): """Parses comments for SL on an order""" parsed = None sl_at = "(SL\s{0,1}@\s{0,1})" sl_price = "([0-9]{0,3}\.[0-9]{1,2}((?!\S)|(?=[)])))" pattern = sl_at + sl_price match = re.search(pattern, comments) if match: match.groups() parsed ...
d993fc1686fa2623423269812c834aedb0d504e2
28,639
def nhpp_thinning(rate_fn, tmax, delta, lbound=None): """Nonhomogeneous Poisson process with intensity function `rate_fn` for time range (0, tmax) using the algorithm by Lewis and Shelder 1978. rate_fn: a function `f(t)` of one variable `t` that returns a finite non negative value for `t` in trang...
7761ec918ca1098c17dd997426841e04b93186c2
28,640
import traceback import json def execute_rule_engine(rule_name, body): """ :param rule_name: :param body: :return: """ __logger.info("inside execute_rule_engine for " + rule_name) __logger.info(json.dumps(body, indent=4, sort_keys=True, default=str)) try: result = rule_engine...
b413ec4723d1c030e798e21c670ee607a4f4d373
28,641
def get(): """ Create and return an instance of the FileSelectionContext subclass which is appropriate to the currently active application. """ windowClass = ContextUtils.getForegroundClassNameUnicode() if windowClass == u"ConsoleWindowClass": fsContext = NullFileSelectionContext()...
14e6e94b55801e9b2eb9c8c2738ca6cb8510939a
28,643
def calc_accuracy(y_true, y_predict, display=True): """Analysis the score with sklearn.metrics. This module includes score functions, performance metrics and pairwise metrics and distance computations. Parameters ========== y_true: numpy.array y_predict: numpy.array display: Boolea...
e71cc9773dc593ea6456f28f96c90410e6043fe0
28,644
def HSV_to_HSL(hsv): """Converts HSV color space to HSL""" rgb = HSV_to_RGB(hsv) return RGB_to_HSL(rgb)
dc847755135f0d96f5b8980154b9ade496c1753f
28,645
def prosodic_meter_query( collection, ): """ Function for returning all Prosodic Meters that contain the queried collection of :obj:`fragment.GreekFoot` objects. :param collection: an iterable collection of :obj:`fragment.GreekFoot` objects. """ all_prosodic_meters = get_all_prosodic_meters() res = [] for m...
ec55bc910c246051504f4a66fa12dc10211725d5
28,646
def get_model(loss=keras.losses.MeanSquaredError(), optimizer=keras.optimizers.Adam(), metrics=[keras.metrics.MeanSquaredError()]): """ Loads and compiles the model """ model = unet3D_model() model.compile(loss=loss, optimizer=optimizer, metrics=[metrics]) return model
0a30796893b2d20885fc5496385317c9fc4f2d08
28,647
def mps_kph(m_per_s): """Convert speed from m/s to km/hr. :kbd:`m_per_s` may be either a scalar number or a :py:class:`numpy.ndarray` object, and the return value will be of the same type. :arg m_per_s: Speed in m/s to convert. :returns: Speed in km/hr. """ return m_per_s * M_PER_S__K...
a0cb03d04edcb21bb6820918c262c8a3d6e9afc3
28,648
import torch def evaluate(model: nn.Module, loss_func: nn.Module, loader: iter, logger: Logger, device: str = None): """ Evaluate the parameters of the model by computing the loss on the data. """ if device is None: device = next(model.parameters()).device model.eval() y_hats, y_s = [], [] ...
7c7d769dde86771e052703ecd312f4ee62235419
28,649
def glm_likelihood_bernoulli(parms, X, Y, lamb=1, l_p=1, neg=True, log=True): """The likelihood for a logistic regression or bernoulli model with a penalty term (can accept any norm, default is 1 for L1). Parameters ---------- parms : numpy array (numeric) The coefficients (including in...
e125d7284045036d412b5afa76730103369142a4
28,650
import json def to_tvm(graph, shape_dict, layout, mode='tensorflow'): """convert frontend graph to nnvm graph""" assert mode in FRAME_SUPPORTED if mode == 'tensorflow': mod, params = tvm.relay.frontend.from_tensorflow(graph, layout=layout, shape=shape_dict) elif mode == 'keras': mod, p...
861184aafd6e2d428e08acc8f718a5ef30152d27
28,651
def getAxes(): """ Get each of the axes over which the data is measured. """ df = load_file("atyeo_covid") df = df.filter(regex='SampleID|Ig|Fc|SNA|RCA', axis=1) axes = df.filter(regex='Ig|Fc|SNA|RCA', axis=1) axes = axes.columns.str.split(" ", expand = True) subject = df['SampleID'] subje...
d489f1c261a8a92b44563b6842a30cc2c7a880c5
28,652
import scipy def stretching_current(ref, cur, dvmin, dvmax, nbtrial, window,t_vec): """ Function to perform the stretching of the waveforms: This function compares the Reference waveform to stretched/compressed current waveforms to get the relative seismic velocity variation (and associated error). I...
9442a940e9013c8ef77bb2c2ecc774c4276a99c5
28,653
def convert_to_int(var): """ Tries to convert an number to int. :param var :returns the value of the int or None if it fails """ try: return int(var) except ValueError: return None
19ba35d351096f2c7b29d78b8df692fc63a75a6f
28,654
def eval_input_fn(filepath, example_parser, batch_size): """ 模型的eval阶段input_fn Args: filepath (str): 训练集/验证集的路径 example_parser (function): 解析example的函数 batch_size (int): 每个batch样本大小 Returns: dataset """ dataset = tf.data.TFRecordDataset(filepath) dataset...
1a67adfe1decd8b38fe8a8d973b7caf1fb6ec85a
28,655
def ring_forming_scission_ts_zmatrix(rxn, ts_geo): """ z-matrix for a ring-forming scission transition state geometry :param rxn: a Reaction object :param ts_geo: a transition state geometry """ rxn = rxn.copy() # 1. Get keys to linear or near-linear atoms lin_idxs = list(automol.geom.line...
0d9f09210a533a56b64dd3ba559b5f645381c7b7
28,656
def trip(u, v): """ Returns the scalar triple product of vectors u and v and z axis. The convention is z dot (u cross v). Dotting with the z axis simplifies it to the z component of the u cross v The product is: positive if v is to the left of u, that is, the shortest right hand ro...
5f687ee4b16dc6c1b350ed574cb632a7c9ca996b
28,657
def one_cpc(request, hmc_session): # noqa: F811 """ Fixture representing a single, arbitrary CPC managed by the HMC. Returns a `zhmcclient.Cpc` object, with full properties. """ client = zhmcclient.Client(hmc_session) cpcs = client.cpcs.list() assert len(cpcs) >= 1 cpc = cpcs[0] cp...
18a42e9777881bbab5f54cbeebefb1bf487d0994
28,658
import time def yield_with_display(future_or_iterable, every, timeout=None): """ Yields for a future and display status every x seconds :param future_or_iterable: A future to yield on, or a list of futures :param every: The number of seconds between updates :param timeout: The total number...
07501c913eaf4a4c497ad0c0c3facc87b946e1f5
28,659
def query(cmd, db, cgi='http://www.ncbi.nlm.nih.gov/sites/entrez', **keywds): """query(cmd, db, cgi='http://www.ncbi.nlm.nih.gov/sites/entrez', **keywds) -> handle Query Entrez and return a handle to the results, consisting of a web page in HTML format. See the online documentation for an...
1287e3551eae2be337abeba31ce7888d60938111
28,660
def Q2B(uchar): """单个字符 全角转半角""" inside_code = ord(uchar) if inside_code == 0x3000: inside_code = 0x0020 else: inside_code -= 0xfee0 if inside_code < 0x0020 or inside_code > 0x7e: # 转完之后不是半角字符返回原来的字符 return uchar return chr(inside_code)
fa58980c7eb251fa7278caa7bbf6645ad492ed2b
28,661
from datetime import datetime def parsedate(date, formats=None, bias=None): """parse a localized date/time and return a (unixtime, offset) tuple. The date may be a "unixtime offset" string or in one of the specified formats. If the date already is a (unixtime, offset) tuple, it is returned. >>> pars...
512608fb413fa062a4dff00557fbd95120c5441c
28,662
import glob def prepare_lv2_data(change_price=False): """ read lv1 data and ensemble to make submission """ train_files = glob('./models/level1_model_files/train/*') test_files = glob('./models/level1_model_files/test/*') num_feat = len(train_files) nrow = pd.read_csv(train_files[0]).shape...
a10786bf92dccba9cccf7d04c3301b77e008c584
28,663
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('clldmpg') config.include('clld_glottologfamily_plugin') config.include('clld_phylogeny_plugin') config.register_datatable('familys', datatab...
6d6eaa8b6c3425023e3550ddae1d3455c939c6fd
28,664
import numpy def dwwc(graph, metapath, damping=0.5, dense_threshold=0, dtype=numpy.float64, dwwc_method=None): """ Compute the degree-weighted walk count (DWWC) in which nodes can be repeated within a path. Parameters ---------- graph : hetio.hetnet.Graph metapath : hetio.hetnet.MetaPath ...
aa6d30ed04baf2561e3bac7a992ae9e00b985da8
28,665
def fba_and_min_enzyme(cobra_model, coefficients_forward, coefficients_reverse): """ Performs FBA followed by minimization of enzyme content """ with cobra_model as model: model.optimize() cobra.util.fix_objective_as_constraint(model) set_enzymatic_objective(model, coefficients_...
2e6614be30c7d0f343b9d4206d1e7c34d54436f3
28,666
def logi_led_shutdown(): """ shutdowns the SDK for the thread. """ if led_dll: return bool(led_dll.LogiLedShutdown()) else: return False
fdb7d77b7fb59804458247c32a35e80da44f6c1f
28,667
from typing import Dict def get_blank_adjustments_for_strat(transitions: list) -> Dict[str, dict]: """ Provide a blank set of flow adjustments to be populated by the update_adjustments_for_strat function below. Args: transitions: All the transition flows we will be modifying through the clinical ...
b2e5391280bae48202f92832aa8821d47a288135
28,669
def get_instance(module, name, config): """ Get module indicated in config[name]['type']; If there are args to specify the module, specify in config[name]['args'] """ func_args = config[name]['args'] if 'args' in config[name] else None # if any argument specified in config[name]['args'] if ...
ea57e7097665343199956509bb302e3806fb383a
28,670