content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def article_markdown(text): """ 对传入的text文本进行markdown """ renderer = ArticleRenderer() markdown = mistune.Markdown(renderer=renderer) return markdown(text)
32d1edc0d5155c62b0dc0ff18dc9a44f1ec85d7a
3,658,700
def tf_pywt_wavelet_decomposition(patch_vec, patch_size, name, wavelet_type, level, mode): """ :param patch_vec: :param patch_size: :param name: :param wavelet_type: :param level: :param mode: :return: """ # TODO: docstring # Convert input values for pywt wavelet_type =...
4f4774189b06d5f51b6c65af7c4fc4f83b49314c
3,658,701
from pycompss.api.api import compss_start, compss_stop from importlib.machinery import SourceFileLoader # noqa import imp # noqa import os import logging import sys def launch_pycompss_application(app, func, log_level="off", # type: st...
68871a41dedf1195045b51e712c17e7e45127a4e
3,658,702
def _gen_key(user_id, key_name): """ Tuck this into UserManager """ try: manager = users.UserManager.instance() private_key, fingerprint = manager.generate_key_pair(user_id, key_name) except Exception as ex: return {'exception': ex} return {'private_key': private_key, 'fingerprin...
f5babf523bded37ba624295a7435e2709488d47a
3,658,703
def svhn_loader(size=None,root="./shvn",set="train",batch_size=32,mean=0.5,std=0.5,transform="default",download=True,target_transform=None,**loader_args): """ :param size: :param root: :param set: :param batch_size: :param mean: :param std: :param transform: :param download: :pa...
f40cd95338f4e745cbbb849ac8a9999f98245cf0
3,658,704
import pkg_resources def get_supervisees(): """Pull the supervisor specifications out of the entry point.""" eps = list(pkg_resources.iter_entry_points(ENTRY_POINT_GROUP)) return dict((ep.name, ep.load()) for ep in eps)
6a812bb8422382c6e481bab8b27651786984ea66
3,658,705
async def index(request): """ This is the view handler for the "/" url. **Note: returning html without a template engine like jinja2 is ugly, no way around that.** :param request: the request object see http://aiohttp.readthedocs.io/en/stable/web_reference.html#request :return: aiohttp.web.Respons...
f90ba225055bf77b39942da7fc1b1b2f5b4a7286
3,658,706
def adtg(s, t, p): """ Calculates adiabatic temperature gradient as per UNESCO 1983 routines. Parameters ---------- s(p) : array_like salinity [psu (PSS-78)] t(p) : array_like temperature [℃ (ITS-90)] p : array_like pressure [db] Returns ------- ad...
8d195810ad52215135db4ef8f9825a914b01522c
3,658,707
import re def calculate_ion_mz(seq: str, ion: str = 'M', charge: int = 0 ) -> float: """ given a peptide sequence and ion type, count the number of atoms, accounting for ion type and whether cysteines are measured by IAA - ion type M:...
e032ad439414314511b008d98dadb23b84012798
3,658,708
import os def get_all_sub_folders(folder_path): """get all sub folders to list Parameters ---------- folder_path : str Returns ------- list """ sub_folders = [] for path in os.listdir(folder_path): full_path = os.path.join(folder_path, path) if os.path.isdir(f...
65afa34dadbf4cdd37ebd7feeab9aca9b03570ad
3,658,709
def hhc_to_int(s): """Parse a number expressed in sortable hhc as an integer (or long). >>> hhc_to_int('-') 0 >>> hhc_to_int('.') 1 >>> hhc_to_int('~') 65 >>> hhc_to_int('.-') 66 >>> hhc_to_int('..') 67 >>> hhc_to_int('.XW') 6700 >>> hhc_to_int('----..') 67 ...
25f6e8097f1fbf0f6ceed08fc8ac0195fb88acb4
3,658,710
def initializeSens(P, B, idxs): """ This function initializes the sensitivities using the bicriteria algorithm, to be the distance between each point to it's closest flat from the set of flats B divided by the sum of distances between self.P.P and B. :param B: A set of flats where each flat is represen...
6726c892311d1590adea62babde6023d4b7d67a3
3,658,711
def fast_knn(data, k=3, eps=0, p=2, distance_upper_bound=np.inf, leafsize=10, idw=util_idw.shepards): """ Impute using a variant of the nearest neighbours approach Basic idea: Impute array with a basic mean impute and then use the resulting complete array to construct a KDTree. Use this KDTree to compute n...
976e51c66878643965b099f764595629b379d440
3,658,712
def role_generator(role): """Closure function returning a role function.""" return lambda *args, **kwargs: role.run(*args, **kwargs)
35dd1a54cb53a6435633c39608413c2d0b9fe841
3,658,713
def pick_slices(img, num_slices_per_view): """ Picks the slices to display in each dimension, skipping any empty slices (without any segmentation at all). """ slices = list() for view in range(len(img.shape)): dim_size = img.shape[view] non_empty_slices = np.array( ...
ed80e4bd53e6a72c6ad7cad899d875ac320b33b7
3,658,714
import json def cate2(request): """ DB에서 Cate2의 분류 이름을 반환 """ cate1 = Cate1.objects.get(cate1_name=request.GET.get('cate1')) cate2 = list(map(lambda cate2 : cate2['cate2_name'], Cate2.objects.filter(cate1=cate1).values('cate2_name'))) json_data = json.dumps({'cate2': cate2}) retu...
ebeca48bb9d6550fb34d68c453ef1fb47225fb4a
3,658,715
def get_single_endpoint(name): """ TODO - Add docstring """ class EndpointWithID(Resource): def get(self, pid): return get_with_id(name, pid), 200 # TODO - Add `get.__doc__` EndpointWithID.__name__ = name return EndpointWithID
2081935a568545545e2825eaaa6bcb2c1ac33a6c
3,658,716
def dayChange(): """ Day Change Calculates and stores in a dictionary the total current change in position value since yesterday, which is (current_price - lastday_price)* qty. :return: dictionary """ daychange = dict() for position in portfolio: # Strings are returned from API; ...
f33979f25ffe44a0de8ec0abc1c02284e8fe5427
3,658,717
def look_for_section(line): """Look for one of the sections in a line of text.""" for key in SECTIONS: if line.startswith(key): return key return None
d44ad97312528c4fea856e705be8e6820695fd9a
3,658,718
def SetStrucIdx(sid, index): """ Change structure index @param sid: structure type ID @param index: new index of the structure @return: != 0 - ok @note: See GetFirstStrucIdx() for the explanation of structure indices and IDs. """ s = idaapi.get_struc(sid) if not s: ...
8b246d6e2fb155bdc789536f75e20971a54ddfc3
3,658,719
import json def extract_user_dict_from_tweet( tweet: Tweet ): """Takes the other_data field from a tweet object and extracts the data for the user from it. It returns a dictionary rather than a User model object because we might want to try looking up whether the user exists before creating a new ...
533d8795c652e5c7f1299f3dcc04fc30de644222
3,658,720
def in_scope(repository_data): """Return whether the given repository is in scope for the configuration. Keyword arguments: repository_data -- data for the repository """ if "scope" in repository_data["configuration"] and repository_data["configuration"]["scope"] == "all": return True ...
0e521f805f69a1c6f306700680d42fbe76595c3a
3,658,721
from typing import Union from typing import Tuple from typing import Optional from typing import List from typing import Any def run_image_container_checks( image_container: Union[AICSImage, Reader], set_scene: str, expected_scenes: Tuple[str, ...], expected_current_scene: str, expected_shape: Tup...
a502650fb227aa4425a2501f112603b681b41fbf
3,658,722
from typing import Type def collect_validation_helper(package_names: str) -> Type[ValidationHelper]: """Finds subclasses of the validate.ValidationHelper from a list of package names. Args: package_names: A list of Python package names as strings. Returns: A validator class that are ...
bb38b734641a025a9d7fd26d46ebfb1476879c82
3,658,723
def heartbeat(request): """Test that ElasticSearch is operationnal. :param request: current request object :type request: :class:`~pyramid:pyramid.request.Request` :returns: ``True`` is everything is ok, ``False`` otherwise. :rtype: bool """ indexer = request.registry.indexer try: ...
6acf0b21b6fcc64f70ca75cb6795df0b5109f273
3,658,724
def _load_edge_data(graph, regions): """Load and return all relevant edges from the graph.""" has_seat = _load_edges_from_query( graph, 'SELECT inV().@rid AS in_rid, outV().@rid AS out_rid FROM Has_Seat') # The edges in the existing dataset point from parent to child region / settlement. ...
d7a002c6214b614e95edc42d850dc9df51a26462
3,658,725
def get_story_assignee(jira_sheet, process): """ Accessor for Story Assignee Accessor method for retrieving the value for Story Assignee on the JIRA Stories Sheet. There is a check to make certain the process in question is amongst those qualified to exist. Args: jira_sheet: A variabl...
3f49c10e540b001cf0f4eebf69a1821a16ec9476
3,658,726
def predict_mhalo(obs_dsigma, mock_use, logms_mod_tot, logms_mod_inn, sig_logms=None): """Halo mass and its scatter in each bin. Parameters ---------- obs_dsigma: list List of observed DeltaSigma profiles. mock_use: numpy array UniverseMachine mock catalog. logms_mod_tot : ndarr...
0c68d773155f997d85361ae663bf0eaae09be258
3,658,727
def create_agent_model(env, lr=1e-4, h_size=128, epsilon=0.2, beta=1e-3, max_step=5e6, normalize=False, num_layers=2): """ Takes a Unity environment and model-specific hyper-parameters and returns the appropriate PPO agent model for the environment. :param env: a Unity environment. :param lr: Learni...
ef43219e9e12ba46c81ed3a39ecb1b82e8953585
3,658,728
from typing import List def decode_to_sequence(encoded_sequence: Bytes) -> List[RLP]: """ Decodes a rlp encoded byte stream assuming that the decoded data should be of type `Sequence` of objects. Parameters ---------- encoded_sequence : An RLP encoded Sequence. Returns ------...
cb33dd9da8deb2096ce3ad205a743c4c22c0f4c8
3,658,729
def list_field_override_choices(override_map=None, html=True): """ This returns either a list of allowable choices, or an HTML-formatted unordered list (default). """ if override_map: if html: choices = '<b>These are the allowable field override choices for field name:<ul>' ...
9b29493af651d95d67f8bd2c4283f53e737e7c5c
3,658,730
import logging def get_logger(initial_level=logging.DEBUG): """Gets the named logger""" logger = logging.getLogger('ungoogled') if logger.level == logging.NOTSET: logger.setLevel(initial_level) if not logger.hasHandlers(): console_handler = logging.StreamHandler() ...
d9f9a264f1f2c3c4638ffc5c6e886182923cbf5a
3,658,731
import logging import os import sys def config_logger(name, log_file, file_level, console_level): """Configure the logger that should be used by all modules in this package. This method sets up a logger, such that all messages are written to console and to an extra logging file. Both outputs will be t...
624cafebc685e10333134be28849b06c098902d1
3,658,732
import six def _safe_resolve_url(url): """ Previously, resolve_url_lazy would fail if the url was a unicode object. See <https://github.com/fusionbox/django-authtools/issues/13> for more information. Thanks to GitHub user alanwj for pointing out the problem and providing this solution. ""...
9b06bc346ebe03b1e5209aa8c108b76aae895089
3,658,733
def get_metrics( reset: bool = False, include_custom: bool = True, raise_errors: bool = True, ) -> pd.DataFrame: """ Returns table of available metrics used for CV. Example ------- >>> from pycaret.datasets import get_data >>> boston = get_data('boston') >>> from pycaret.regression im...
1d2ed9372aa6f26cd740e6987a2e94baaef647dc
3,658,734
def get_unique_wikilinks(filepath): """Get UNIQUE wikilinks from a md file. The links' order of appearance in the file IS preserved in the output. This accounts for: - Aliases / alt text, so [[Lorem ipsum|L.I.]] will be represented as 'Lorem ipsum'. - Header text links, so [[Lorem ipsum#Dummy t...
ca02428942d8a555d606a5c4b8190859917c22c7
3,658,735
def parse_single_example(serialized_example, params): """Parses a singel serialized TFExample string.""" decoder = tf_example_decoder.TfExampleDecoder() data = decoder.decode(serialized_example) image = data['image'] source_id = data['source_id'] source_id = dataloader_utils.process_source_id(source_id) h...
e274a6ebfe7e7aa51dc7bc6b779ef222081a7e47
3,658,736
def eval_blocking(lamb, mu, k): """Finds the blocking probability of a queue. Args: lamb (float): The rate into the queue. mu (float): The rate out of the queue. k (int): Maximum number of customers able to be in the queue. """ rho = lamb/mu return rho**k*((1-rho)/(1-rho**(k...
4c1ea7f5f7984fb24c85a5c1c6c77cdbc2e1e76a
3,658,737
def get_dependent_columns(covar): """ Get the list of dependent columns :param covar: The covariance matrix :return: Dependent columns """ ind_columns = (np.where(~covar.any(axis=1))[0]).tolist() dep_columns_z = [] for i in range(0, covar.shape[0]): if i not in ind_columns: ...
d0145649ce685a4d609809a57d374b1e362c303e
3,658,738
def results_to_answers(guess_hints, answers): """Provide remaining valid answers matching a list of guesses and corresponding hints """ gh_stack = guess_hints.copy() new_ans = answers.copy() while len(gh_stack) > 0: gh = gh_stack.pop() guess = gh[0] hint = gh[1] ...
243cbaeb2d36c66e49cd570c1487bbca7636cd2c
3,658,739
from typing import Optional def get_archive_map(data: DataFrame, row_col: Optional[str] = "ROW") -> Series: """ Get a series mapping object names to archive names :param data: Dataset with archive names as ARCHIVE column and object names in index :type data: DataFrame :param row_...
2d66c55c64dab89e7523778411a7bf70ac784bf6
3,658,740
from typing import Iterable import math def gain_ratio(x_mat: ndarray, y_row: ndarray, prop: int, prop_values: Iterable, gain_value: float = None) -> float: """ 计算使用属性 prop 对样本集进行划分的信息增益率,值越大表示使用属性 prop 进行划分 所获得的纯度提升越大。此方法对可取值数目较少的属性有所偏好 :param x_mat: 特征向量组,行数 m 表示样本数,列数 n 表示特征数 :param y_row: 输出向...
08a26ba4c3dc7712ca515f128f7e3039f005b993
3,658,741
def _LengthError(e: ByteList): """Check if the length of the EDID is a multiple of 128. Args: e: The list form of the EDID to be checked. Returns: A list of error.Error objects, or None. """ if not len(e) % 128: return None else: return [ error.Error( ...
940b6f4b2648eefe79afe69f623b0f1e02583ce1
3,658,742
def __single_auc_score__(feature_i, clf, cv_indices, X, y, sample_weight=None): """Method determining the 'area under curve' for a single test set. This function is intended for internal ...
51738218bde23aeb3633bcfa47dff918af29c4cd
3,658,743
def IntCurveSurface_ThePolygonToolOfHInter_Bounding(*args): """ :param thePolygon: :type thePolygon: IntCurveSurface_ThePolygonOfHInter & :rtype: Bnd_Box """ return _IntCurveSurface.IntCurveSurface_ThePolygonToolOfHInter_Bounding(*args)
294da704fcc9a59a8e7fc2042d050255aa45accb
3,658,744
def identity_show(client, resource_group_name, account_name): """ Show the identity for Azure Cognitive Services account. """ sa = client.get(resource_group_name, account_name) return sa.identity if sa.identity else {}
19018c895f3fdf0b2b79788547bf80a400724336
3,658,745
import os import sys def parsing_input(program_parameters): """ Parses apart the command line or qsub submission file to get all user input parameters for analyzing the data. Function also prints all user parameters to command line, so a user can monitor the inputs. Also, default settings are se...
761e29994ee77ffc62f0d4c4039bc82971d4fc77
3,658,746
import re def normalize_country_code(country_code): """ Normalize country codes a bit by making capitalization consistent and removing trailing comments (and other words). """ if not country_code: return country_code country_code = re.match(r'^(\w+)', country_code).group(1) return coun...
37dce64b62ae4ec20cb2d9b10c66beeba73c5683
3,658,747
import math def get_angle(p1, p2): """Get the angle between two points.""" return math.atan2(p2[1] - p1[1], p2[0] - p1[0])
a29ea1ed74a6c071cf314d1c38c6e2f920bd1c3a
3,658,748
def per_application(): """ :return: a seeder function that always returns 1, ensuring at most one delegate is ever spawned for the entire application. """ return lambda msg: 1
7ecc568846ab484557e768ad372f4faf85238401
3,658,749
import requests from bs4 import BeautifulSoup def get_job_information(url): """ Uses bs4 to grab the information from each job container based on the url. Parameters ---------- url : str Career builder url of any job Returns ------ job_data : dict Contains Job Name, Compa...
a5c0b53338dbacc7fe0e7c7eb91b66855968af2b
3,658,750
def idiv(self, other): """Compute the element-wise division. Parameters ---------- other : Union[dragon.Tensor, number] The value to divide. Returns ------- dragon.Tensor The self. See Also -------- `dragon.math.div(...)`_ """ return _apply_binary_op([...
05afbc883ec835e06cceaa9a13119fbac0df8f5c
3,658,751
def getAudioMetadata(fileRef): """Extract metadata for audio file""" args = [config.mediaInfoExe] args.append("--Output=EBUCore") args.append(fileRef) # Command line as string (used for logging purposes only) cmdStr = " ".join(args) status, out, err = shared.launchSubProcess(args) # C...
4f954d45e6b029b22001a02e49ad453a2f572bb8
3,658,752
def simulation_test(**kwargs): """Decorate a unit test and mark it as a simulation test. The arguments provided to this decorator will be passed to :py:meth:`~reviewbot.tools.testing.testcases.BaseToolTestCase .setup_simulation_test`. Args: **kwargs (dict): Keyword arguments to...
56aa51374e66bb765bfc3d4da51e3254d06c0b55
3,658,753
def update_action_state(): """ :type action: dart.model.action.Action """ # we receive a list of {action_id, action_status, workflow_instance_id/status} # We will update the database for each such entry try: action_status_updates = request.get_json() _logger.info("AWS_Batch: extracted j...
f89142b6877f615cce253d727c001737729394fa
3,658,754
def page_not_found(): """Directs to error page if user is not logged in. :return: HTML file for error page. """ error = 'You must be logged in to view this page.' return render_template('error.html', error=error)
ff3cc2c369154bec1303658bb3c691de448d8231
3,658,755
def mtf_toy_model_parallel(): """Set of hyperparameters.""" hparams = mtf_toy_base() hparams.add_hparam("layout", "hidden:0") return hparams
74c01e9f8c68f07d332119fd7cead21b92e4de84
3,658,756
from typing import Union from pathlib import Path def to_dataframe(sas7bdat_file: Union[str, Path]) -> pd.DataFrame: """Converts a sas7bdat and/or xpt file into a pandas dataframe. args: sas7bdat_file: The name, including the path, for the sas7bdat file. return: A pandas dataframe contai...
70564f16c43a6c6fdaf65841ee1d0c48d8f550f2
3,658,757
def shift_scale_rmsf(rmsf_double, phi, cellsize, ccomp, faraday_peak): """Shift and scale the RMSF, to the parameters of the found clean component. Args: rmsf_double (numpy array): double sized array of complex point spread function values in Faraday space. phi (numpy array): array of Fara...
d658cfece87276075b7c53b987772906908b5b80
3,658,758
def region_filter(annos, annotation): """filter for Region annotations. The 'time' parameter can match either 'time' or 'timeEnd' parameters. """ result = [] for anno in annos: time = annotation.get("time") timeEnd = annotation.get("timeEnd") for key in ['text', 'tags']: ...
3ca4c6ba39d44370b3022f5eb17a25e0e1c9f056
3,658,759
def estimator_mixt_default(sample): """Default estimator of mixture distribution This estimator returns tuple with two non-overlaping parts of `sample` which are estimated to come from continuous and discrete parts of mixture distribution. Estimation is done by deciding sample element to be from di...
31394305d9da7afe553f0dab9753d919b6aa7c73
3,658,760
def modularity_clustering(graph, size_cutoff=10, deg_cutoff=0.5, callback=None): """ Use the Clauset-Newman-Moore greedy modularity maximization algorithm to partition the TN93 pairwise graph into communities. Modularity quantifies the density of edges at the periphery of ...
e64e383eaf4895244aab1f32e39fae5af92769b5
3,658,761
import inspect def get_post_processors(): """ Loads post processors by inspecting members of the 'post_processors' package. """ post_processor_classes = [] for _, member in inspect.getmembers(post_processors): if inspect.isclass(member): post_processor_classes.append(member) ...
6b65c438657230661b189c8851ca5b662714c4df
3,658,762
def vulcanize(name: str) -> str: """Add prefixes to names that are similar to the prefixes seen in Vulcan characters in the Star Trek™ franchise. :param name: The name to modify. :return: A :class:str object. :rtype: str Usage: >>> # Seed the RNG to make the example predic...
00cd22427ab873852af519a6657bf9504b945fb3
3,658,763
def B(j, p, x, knots): """ Compute B-splines using recursive definition. """ if p == 0: if knots[j] <= x < knots[j+1]: return 1.0 else: return 0.0 else: left = special_div((x-knots[j])*B(j,p-1,x,knots), knots[j+p]-knots[j]) right = special_div(...
1c578e317a3e2ff00f31b8e0b31b4f184e9bd338
3,658,764
from re import T def not_falsy(item: T, item_name: str) -> T: """ Check if a value is falsy and throw an exception if so. :param item: the item to check for falsiness. :param item_name: the name of the item to include in any exception. :raises ValueError: if the item is falsy. :returns: the it...
b758d3ffe8f4c30086248fc9df2a9e82e05553d3
3,658,765
def _apply_limit_abs_unit(x, lim, unit): """Return one limit with applied unit(abs(x)). See get_limits.""" if unit is None: return lim unit = unit.lower() if unit == 'near': return lim * np.nanmin(np.abs(x)) if unit == 'far': return lim * np.nanmax(np.abs(x)) elif unit ==...
e3c77192b90b04b4c488ca8bac41f79024517a6b
3,658,766
def load_fits(name): """ Open a fits file image Inputs: name: name of the .fits file (str). Output: image: """ while True: try: file = fits.open(name) image = file.copy() return image, name except FileNotFoundError: prin...
24a348239e89cc9e565238e9f124875090ffe92b
3,658,767
import os import subprocess import json def run_flow(command, contents): """Run Flow command on a given contents.""" read, write = os.pipe() os.write(write, str.encode(contents)) os.close(write) try: output = subprocess.check_output( command, stderr=subprocess.STDOUT, stdin=re...
5621c321d0fb35518aabfb04f0f1b088be2bfa79
3,658,768
def cleanup(): """Clean up resoruces in use by implementation. Clean up any resources that have been allocated by the RPC implementation. This is typically open connections to a messaging service. This function would get called before an application using this API exits to allow connections to get...
984d2c3b297c47c1ffaec43302cfb741cfe369e4
3,658,769
def social_bonus_count(user, count): """Returns True if the number of social bonus the user received equals to count.""" return user.actionmember_set.filter(social_bonus_awarded=True).count() >= count
b2469833f315410df266cd0a9b36933edb1f9ac6
3,658,770
def del_category_tag_lib(self,c_uuid,t_uuid): """04删除便签或分类""" if c_uuid: category = Category.by_uuid(c_uuid) if category is None: flash(self, '分类不存在', 'error') return {'status':False} if category.articles: flash(self,'分类下面有文章,请先删除文章','error') ...
db915fe29943d9bb63122d73d59a052715798818
3,658,771
import math def get_distance_metres(aLocation1, aLocation2): """ Returns the ground distance in metres between two `LocationGlobal` or `LocationGlobalRelative` objects. This method is an approximation, and will not be accurate over large distances and close to the earth's poles. It comes from the Ard...
57a56fac2d0a3a83083b769b5f896cb82d55dc56
3,658,772
import types def pd_series_overload(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series Limitations ----------- - Parameters ``dtype`` and ``copy`...
bc5302cbbb30215d8257ad44ee60a5990948f94a
3,658,773
import copy def get_export_summary(results): """Prints to screen the exporting results of example programs. Args: results - results of the compilation stage. which is the output of and export_repos() Returns: Numbers of failed results """ pass_table = PrettyTable() pass_table.field_...
0f68e8da955a73c401536f83e18faa223d603d15
3,658,774
import numpy def _misfitfunc(data, predicted): """ Calculate the total data misfit function between the observed and predicted data. """ result = 0. for d, p, in zip(data, predicted): residuals = d.observed - p result += sqrt(numpy.dot(d.weights*residuals, residuals))/d.norm ...
c21fb4c8d68a2abe20ca155e5776124c69ce2eff
3,658,775
def stream_doi(app, doi): """Returns tuple of URL string and a urlopen() return value.""" apikey = app.cfg.get_or_die('api-keys', 'crossref') url = ('http://crossref.org/openurl/?id=%s&noredirect=true&pid=%s&' 'format=unixref' % (wu.urlquote(doi), wu.urlquote(apikey))) return url, wu.urlopen...
7c3569c4492b52c68ed13bcaac9dae0b6805bdb6
3,658,776
from typing import Optional import getpass from datetime import datetime import json def do_evaluation( *, input_path, training_path: Optional[str] = None, testing_path: Optional[str] = None, method, prediction_task, dimensions: int = 300, number_walks: int = 8, walk_length: int = ...
ab5939065d9cf70c6e5ddba8530f91cb2577a31c
3,658,777
import re def test_structure_fatal_deformities(good_structure, deformity): """Make specific checks upon performing single invalidating deformations of the data of a good structure. """ if deformity is None: return StructureResource(**good_structure) deformity, message = deformity go...
28acc95fb29564ddbf844de70704e31212e59b9f
3,658,778
def edit_user(): """ 返回待编辑用户信息 """ data = request.json user_id = data.get('id') _edit = User.query.filter_by(id=user_id).first() _data = {'account': _edit.account, 'name': _edit.name, 'role_id': _edit.role_id} return jsonify({'data': _data, 'status': 1})
7423eb2342dd135a219bbb6f34ba7f82740b49d0
3,658,779
def transactions(request): """See all transactions that have been contained in blocks.""" vote_list = Vote.objects.all().order_by('timestamp') paginator = Paginator(vote_list, 100, orphans=20, allow_empty_first_page=True) page = request.GET.get('page') votes = paginator.get_page(page) hashes =...
7ed0d4a8b997a41112eccfc67a19784283e65fd8
3,658,780
import pandas def elections_vote_places_geo(source="xd", folder=".", fLOG=noLOG): """ Retrieves data vote places (bureaux de vote in French) with geocodes. @param source should be None unless you want to use the backup plan ("xd") @param folder where to download @param fLOG ...
b81abbeeed1968e01477cb71897a373a113ffafb
3,658,781
from typing import Optional def erfc( x: oneflow._oneflow_internal.BlobDesc, name: Optional[str] = None ) -> oneflow._oneflow_internal.BlobDesc: """This operator computes the :math:`1-erf(x)`, for more details of `erf` function please refer to `math.erf`. Args: x (oneflow._oneflow_internal.Bl...
0fd6f01b0d6dbbdf7449a5a7dc2ac9ee3f0bce0e
3,658,782
from typing import Union from typing import Iterable from typing import Optional from typing import List from typing import Dict from typing import Any def ner_manual_tokenizers_bert( dataset: str, source: Union[str, Iterable[dict]], loader: Optional[str] = None, label: Optional[List[str]] = None, ...
982ddc4ab2e574870a5790dc37854ff5ffec648a
3,658,783
def test_nested_simple_condition() -> None: """ Iterates and maps expressions over a complex Condition: (A=B OR A=B) AND (A=B OR A=B) """ c1 = Column(None, "t1", "c1") c2 = Column(None, "t1", "c2") co1 = binary_condition(None, ConditionFunctions.EQ, c1, c2) c3 = Column(None, "t1", "c1"...
f047f916f3ace9142e8940a39fd47d36d43dc108
3,658,784
import functools def _deep_setattr(obj, key, val): """ Set an attribute `key` on the object. If any of the prefix attributes do not exist, they are set to :class:`~pyro.nn.PyroModule`. """ def _getattr(obj, attr): obj_next = getattr(obj, attr, None) if obj_next is not None: ...
a28b01484de71dc486c73fe9ad01238675b15a04
3,658,785
def inverse_max_dcg(labels, gain_fn=lambda labels: tf.pow(2.0, labels) - 1., rank_discount_fn=lambda rank: 1. / tf.math.log1p(rank), topn=None): """Computes the inverse of max DCG. Args: labels: A `Tensor` with shape [batch_size, list_size]. Each valu...
60e5b05af91fbd8e51a58894f9f19a5a8f92d1b5
3,658,786
def get(url): """ 用 GET 请求 url 并返回响应,对301进行了处理 :param url: :return:status_code, headers, body """ protocol, host, port, path = parsed_url(url) s = socket_by_protocol(protocol) s.connect((host, port)) request = 'GET {} HTTP/1.1\r\nhost: {}\r\nConnection: close\r\n\r\n'.format(path, ...
3ef816149e8b4953e119c807726112feeacc6eed
3,658,787
import re def make_rule(frontier_pair, amr, tree, align, next_index): """ Creates a new rule with the given parts, and collapses these parts in the original graph and tree. """ constituent, amr_fragment = frontier_pair outside_edges = [e for e in amr.triples() if e not in amr_fragment.triples()] root_...
4b7cd9af8534688e8c30b88f4e5fa4da3c85f180
3,658,788
def NotEqual(data1, data2, target=utils.CCE): """ check whether data1 notequals to data2. Args: data1 (tvm.tensor.Tensor): Tensor. data2 (tvm.tensor.Tensor): Tensor. Returns: tvm.tensor.Tensor. If data1 notequal to data2 return True, else return False. Supported Platfo...
88be9ea40900644a61dd3f37c0a05f9fa8c3eb76
3,658,789
def read_labels(labels_path): """Reads list of labels from a file""" with open(labels_path, 'rb') as f: return [w.strip() for w in f.readlines()]
3ebc61c76dd1ae83b73aa8b77584661c08a51321
3,658,790
import torch def targeted_neurogenesis(weights, n_replace, targeted_portion, is_training): """ Takes a weight matrix and applied targetted dropout based on weight importance (From Gomez et al. 2019; https://for.ai/blog/targeted-dropout/) Args: weights - the input by ouput matrix of weights ...
4b605ddcd6ef0f13822d2c7050da588b3d1d0b72
3,658,791
def calc_distance_two_points(long_from, lat_from, long_to, lat_to): """Calculate distance between two points Parameters ---------- long_from : float Longitute coordinate from point lat_from : float Latitute coordinate from point long_to : float Longitute coordinate to po...
0c35c22458db165684242389470248632f2e1edb
3,658,792
from typing import Counter def modified_precision(reference_max_counts, hypothesis, n): """ Calculate modified ngram precision. The normal precision method may lead to some wrong translations with high-precision, e.g., the translation, in which a word of reference repeats several times, has very ...
cbaf2ca391a6b0ac8bfcf9e2f85aba83f4b585d0
3,658,793
def bin_spectrum(bin_width, wavelength, doppler_shift, flux, flux_uncertainty, final_uncertainty='combine'): """ Args: wavelength: doppler_shift: flux: flux_uncertainty: Returns: """ bw = bin_width wv = wavelength ds = doppler_shift f =...
3c71977ae845161156ed95b42f68d7de65b80f66
3,658,794
def scrub(old_fs: Vfs, new_fs: Vfs) -> Vfs: """Try to eliminate files which were previously installed but are no longer used.""" old_fs = old_fs.copy() new_fs = new_fs.copy() # Look for files in the old log which are no longer present in the new log for txn in old_fs._log: if txn[0] == "li...
c1cdfad6c658e481b05658d3041458ab6fd3419c
3,658,795
def get_filename(row): """ Assembles the name of the feature file. Parameters ---------- row : pandas.Series A row fom the sequence dataframe. Must have the following index values: "sample_name", "inj_number", "batch_name", "acquisition_date_and_time". Returns ------- f...
68624971527442da110734043bdbaa1c68dc4875
3,658,796
def create_plotly_trace(data_x, data_y, namexy, chosen_mode='lines', use_gl = True, swap_xy = False): """ Создание одного trace по данным :param data_x: данные для оси x :param data_y: данные для оси y :param namexy: название для trace :param chosen_mode: настройка отображения 'lines', 'marker...
dd90d370c27968053bfaf98f509868d959416d39
3,658,797
import yaml def read_metadata() -> dict: """Reads and returns raw metadata.""" with open(metadata_path().resolve(), "r") as fd: return yaml.safe_load(fd)
0eafc0a722ac5cae69407a7e76d5bf62b7541b69
3,658,798
def plot_plaid_contrast_tuning(bf_indices, base_contrasts, mask_contrasts, base_orientations, mask_orientations, test_responses): """ Plot responses to orthogonal plaid stimulus at different base and mask contrasts Inputs: bf_indices: [list or array] of neuron indices to use all indices should be less...
7521e7c5208f6fa9fe12772faa09106b31d1a96b
3,658,799