content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def asn_query(): """Query data from database, plot them and return figure.""" # Query asn and print the most frequent ones query = """ SELECT speedtest.asn, country, COUNT(speedtest.asn) as count FROM speedtest, asn WHERE speedtest.asn = asn.asn GROUP BY speedtest.asn, as...
92f8db0a858f3d158cf2b2c7785e4735401e44e9
60,844
def logout(): """管理人员退出""" response=make_response(redirect(UrlManager.buildUrl("/login/"))) response.delete_cookie(app.config['AUTH_COOKIE_NAME']) return response
94700cb0c5050c033cc9fb35f5917e03faea1bf4
60,845
def convert_gdml_volume(volume, position): """Convert an arbitrary GDML volume to MCNP surfaces""" if position is not None: placement = convert_gdml_position(position) else: placement = 3 * (0.,) # Check for a binary volume tag = volume[0] if tag == "intersection": tran...
7cefa22cd5cc715fbabc4ce74695d6f54da88abd
60,847
def _GetMaxOutlinedIndex(sym_dict): """Find the largest index of an outlined functions. See _OUTLINED_FUNCTION_RE for the definition of the index. In practice the maximum index equals the total number of outlined functions. This function asserts that the index is near the total number of outlined functions. ...
126a05dd9b04894abf8568ee71f5b20b8b8ee4bb
60,848
def evaluate(test_labels, preds, n_decimals=2, binary=True): """ Code to evaluate the predictions of our model. :param test_labels (list): The labels list of our testing set. :param preds (list): The predicitions (given by our model) of our testing set. :param n_decimals (float): The number of deci...
97989610605a6dc3fe35075ed84210baf5e730ea
60,849
import json def get_users(): """ Read all the users from the dynamo database. """ response = _users_table.scan(Select="ALL_ATTRIBUTES") return [json.loads(record["user_obj"]) for record in response.get("Items", [])]
f7c120ac405a891e3d713f691c57549f83362d9c
60,850
def get_grid_values(radar): """ Return the values specific to a grid for mapping the radar data to Cartesian coordinates. """ return _DEFAULT_GRID_VALUES[radar].copy()
5759a891863a8bed8782e83bd85214d24d9601fc
60,851
def comment_modify_question(request, comment_id): """ pybo 질문댓글수정 """ comment = get_object_or_404(Comment, pk=comment_id) if request.user != comment.author: messages.error(request, '댓글수정권한이 없습니다') return redirect('pybo:detail', question_id=comment.question.id) if request.method ...
393cf49c24f4469a474d2b1835d42947554ea29b
60,852
def sort_by_date(xinfo, data, time_index, max_days=30, max_years=2): """ Sorts images by nearest date to reference Args: xinfo (object): The data object. data (3d array): The data to slice and sort. time_index (int): The current time reference. max_days (Optional[int]): The...
aa51d5143359d67bb972bcc942d975feb003fbc5
60,853
from io import StringIO def image2str(img): """Converts PIL Image object to binary data. @param img: PIL Image object @return: binary data """ f = StringIO() img.save(f, "JPEG") return f.getvalue()
0ba3958475018f30ccc25a23d80f384dd75552c7
60,854
import random def experiment(doors, strategy, choice_func, correct): """ Function that runs the actual experiment. A selection is first chosen at random. Then, whilst there are at least 3 doors remaining, the host reveals one incorrect door that is not the door most recently selected. Then the co...
f5ffc84a08612d4f6aecd027edc1363b7b4279fa
60,855
def plot_graph_folium( G, graph_map=None, popup_attribute=None, tiles="cartodbpositron", zoom=1, fit_bounds=True, **kwargs, ): """ Plot a graph as an interactive Leaflet web map. Note that anything larger than a small city can produce a large web map file that is slow to ren...
b9947e0adf36c4b76a4fbf7980d10f9258f0f38d
60,856
def length_validator(min_len=0, max_len=None): """Create a function that checks the length. The type of the checked values must support the :func:`len` function. :param int min_len: the minimum length :param max_len: the maximum length (``None`` means no limit) :type max_len: int or None :...
6bb6448d5cbe457f93c39e2e5109ba60e67033e1
60,857
def parse_query(query): """ Parses grammar output to ETL JSON. :param query: Str. DSL query. :returns: JSON. ETL JSON. """ prsd = parser.parseString(query) match_pattern = prsd["match_pattern"] nodes = [{"node": node.asDict()} for node in match_pattern["nodes"]] edges = [{"edge": ed...
7d7594f796906dc8a2852a63b60e6e086e09288e
60,858
def calc_iou(bbox_1, bbox_2): """Calculate the IOU (Intersection Over Union) given two set of bbox coordinates All coordinates are in the order of (ymin, xmin, ymax, xmax), following the convention in `tf_example_decoder.py` Args: bbox_1: coordinates of bbox1 bbox_2: coordinates of bbox2 ...
e6adbee50230187b20be287e8eb14b724e0367a6
60,859
def apply(R,point): """Applies the rotation to a point""" return (R[0]*point[0]+R[3]*point[1]+R[6]*point[2], R[1]*point[0]+R[4]*point[1]+R[7]*point[2], R[2]*point[0]+R[5]*point[1]+R[8]*point[2])
f6f4e5431e92dac9711f80da9ca0dc75bae793fb
60,860
def svn_wc_has_binary_prop(*args): """svn_wc_has_binary_prop(char const * path, svn_wc_adm_access_t * adm_access, apr_pool_t pool) -> svn_error_t""" return _wc.svn_wc_has_binary_prop(*args)
1f6ec4e4b9c786be461e8070c99200e62f46fd32
60,861
def from_header(header: header.Header, data: hints.Buffer = b'') -> Message: # pylint: disable=redefined-outer-name """ Create a new :class:`~adbwp.message.Message` instance from an existing :class:`~adbwp.header.Header`. :param header: Message header :type header: :class:`~adbwp.header.Header` :p...
b56e20aef5e928ec9a56503f4e56a747f5a28837
60,862
from typing import List from typing import Dict def process_records(records: List[Dict], shard_id: str, fh_d_stream: str): """Process the given records from the underlying Kinesis stream""" return put_records(fh_d_stream, records)
1b78f3227ea40ef059d53176d4d2ec18b4087672
60,863
def linexp_min(xx, h=p0['linexp'][0], a0=p0['linexp'][1], k=p0['linexp'][2]): """ Calculates the minimum phase angle/P degree from given parameters. """ b = h*a0/(1 - (1 + k*a0)*np.exp(-k*a0)) c = h + k*b*np.exp(-k*a0) amin = 1/k * np.log(k*b/c) return (amin, _nb_linexp(amin, h=h, a0=a0, k=k))
dbfaf2ff405826d19e681aaaffe73ca1d4e6f417
60,864
def decode_auth_token(auth_token): """ Decodes the auth token :param auth_token: :throws jwt.ExpiredSignatureError or jwt.InvalidTokenError :return: integer|string """ payload = jwt.decode(auth_token, app.config.get('SECRET_KEY')) return payload['sub']
da8afe59a6006a496bc5c6aed84e0547b1098ff5
60,865
def _minimum_cone_(U, rs): """Calculate the minimum cone. Computes the angle and center of the minimum cone, with its point in the origin, enclosing the vectors in A. Parameters ---------- U : np.array, ndim=2 The vectors that will be enclosed. rs : RandomState A RandomSta...
27df12c40d3e882271e0ca4a56aedcefd74b877e
60,866
from typing import Union from typing import Optional async def asyncio( *, client: AuthenticatedClient, format_: Union[Unset, SchemaRetrieveFormat] = UNSET, ) -> Optional[SchemaRetrieveResponse200]: """OpenApi3 schema for this API. Format can be selected via content negotiation. - YAML: applicati...
1a61ade94a3b6600ad54fac249dd182b5c6f723c
60,867
import re import string def PreProcessSentence(w, sentencepiece, lang): """ Preprocess a sentence by cleaning it, making everything lower case etc. If sentencepiece is being used then don't make spaces between punctuations and words, as it has it's own tokenizer. :param lang: Language of sentence :typ...
5334a17ccc7f77ba514c3d4af94b778c01932eb1
60,868
def mode_off(comp_ent: Entity, ent: Entity) -> str: """Return the offset from the ent to the reference.""" scale = conv_float(comp_ent['const'], 1.0) offset = Vec.from_str(ent['origin']) - Vec.from_str(comp_ent['origin']) return vs_vec(offset * scale)
5bb649db4f700b20d5b1b9f4409f9003a4e42dbd
60,869
def fro_norm(a: np.array) -> float: """Calculate Froberius norm for an array.""" assert a.ndim == 1, "Check that 'fro_norm' receives a 1D array." return np.linalg.norm(a)
0aeadf52af040b0ba35216c7123f1e0e338545b2
60,870
def create_recipe(): """ Allows a user to add a new recipe """ if logged_in: if request.values.get('category_id'): category_id = int(request.values.get('category_id')) category = None for category in categories: if category.user_id == session_user['us...
ce9f08f4c92358bbce83e0270880395207b3bde6
60,871
def _auxiliary_graph(G, Features): """ prepare a graph with twice the number of vertices this graph will contain the connectivity information along the merges. """ K = WeightedGraph(2 * G.V - 1) K.E = G.E K.edges = G.edges.copy() K.weights = np.ones(K.E) K.symmeterize() if K....
200c0ccb01a8777031e435d6fec3c96545441668
60,873
def get_translation(lang, country, key, plural): """ :type lang: str :type country: str :type key: str :type plural: int or None :rtype: str or None """ return _get_translation( lang, country or None, key, "%" if plural is None else 'x', plural)
839c1befc7255df0329ef879f987f871fd7565a1
60,874
def auto_delete_file_on_change(sender, instance, **kwargs): """ Deletes old file from filesystem when corresponding `MediaFile` object is updated with new file. """ if not instance.pk: return False
903224f8070f61055e4068843eed0bb3360c94b6
60,875
def applyRuleTwo(f): """Apply Rule 2 to the formula f. Args: f (str): string representing a formula in binAd Returns: set of str: Set of formulas that can be produced by applying Rule 2 to f. This will be empty if f is not well formed. """ result = set() if n...
5340a1dbdb91d60b07fcf0ef0fc3f8e14b581d06
60,878
def update_cholcov_with_measurement_error(shocks_cholesky, meas_sds, n_wages): """Make a Kalman covariance updated for all possible cases. We use a square-root implementation of the Kalman filter to avoid taking any Cholesky decompositions which could fail due to numerical error. Parameters ------...
6ad8df1c63f5ffc826fb123e0cd3ff528b2f9763
60,879
def system_balance_constraint_rule(backend_model, carrier, node, timestep): """ System balance ensures that, within each location, the production and consumption of each carrier is balanced. .. container:: scrolling-wrapper .. math:: \\sum_{loc::tech::carrier_{prod} \\in loc::carr...
a63961e3d8ed3def40d692684b5d95d5ddc40bfb
60,880
def deserialize_request_string(string, app): """Deserialize request string using in_protocol in application definition. Returns the corresponding native python object. """ server = ServerBase(app) initial_ctx = MethodContext(server, MethodContext.SERVER) initial_ctx.in_string = [string] ct...
ec8de227e54d29ca03d1411a71fb472d33f22cc5
60,881
def update_sub(orig_df, pivot_col=None, pivot_val=None, new_col=None, new_val=None): """ update a subset of DataFrame based on fixed boolean matching. """ out_df = orig_df.copy() out_df.loc[out_df[pivot_col] == pivot_val, new_col] = new_val return out_df
ee52c8bbc9c25e5198093e9f8435725acfb98170
60,882
def buffer(ft): """ Buffer an input feature by 10km """ return ft.buffer(10000).bounds(5)
2eb4eeadbbd47b2527c9ac63f64e21ae3593560c
60,884
from typing import Optional from typing import Union def check_conf( c: invoke.Context, value: Optional[str], conf_key: str, should_raise: bool = True ) -> Optional[Union[invoke.Context, str]]: """Ensure a value is provided from CLI flag value or config.""" if value is not None: return value ...
482950b69c56098cffc18b43273e09b9d1634e7f
60,885
import torch def i2t(images, sentences, nreps=1, npts=None, return_ranks=False, order=False, use_gpu=False): """ Images->Text (Image Annotation) Images: (nreps*N, K) matrix of images Captions: (nreps*N, K) matrix of sentences """ if use_gpu: assert not order, 'Order embedding not supported in GPU mode...
9ad2183da0b5640a43230999e61313d741da44bd
60,886
def alpha_jacobian(**opts): """The jacobian of the change of variables between virtuality and the alpha parameter of the rescaling collinear mapping. """ Q = opts['Q'] pC = opts['pC'] qC = opts['qC'] return Q.dot(qC)/Q.dot(pC)
ce83140c2266dcfdacc9753dde6d9aca5fae53f2
60,887
def has_new_triggerword(predictions, chunk_duration, feed_duration, threshold=0.5): """ Function to detect new trigger word in the latest chunk of input audio. It is looking for the rising edge of the predictions data belongs to the last/latest chunk. Argument: predictions -- predicted labels f...
4a3d7b82e94fac7ee26b18dd848da4ef79378d30
60,888
import typing from datetime import datetime def tryparse_datetime(s: str, formats: typing.List[str]) -> datetime: """ Tries to parse the given string with any of the formats listed. If all formats fail, returns None. """ for fmt in formats: try: return datetime.datetime.strpti...
c3cc3f02ac9c33865535feb79458ddbcfd7e204e
60,889
def get_or_create_bucket_iam_binding(iam_policy, role): """Get or create the binding matching a role.""" binding = get_bucket_iam_binding(iam_policy, role) if not binding: binding = {'role': role, 'members': []} iam_policy['bindings'].append(binding) return binding
30a961553f1c30d2508cc104229f55a18ea3bac8
60,890
def create_monitor_api_client(access_token): """Create API client and construct API headers""" api_client = ApiClient(host=DS_CONFIG["monitor_api_client_host"]) api_client.set_default_header( header_name="Authorization", header_value=f"Bearer {access_token}" ) return api_client
0e7d90611245ad090182c1ebacecfa08708ed317
60,892
def compute_nce_loss(img_embed, text_embed, temp=0.07, return_acc=False): """ Symmetrized NCE loss for paired image/text embeddings """ N = img_embed.shape[0] img_norm = tf.nn.l2_normalize(img_embed, 1) text_norm = tf.nn.l2_normalize(text_embed, 1) # NOTE this is different from what's descri...
f52aa49c995dab2d6319a863a8bb076dc5fde2a4
60,893
def mean_field_ccppo_process(policy, sample_batch, other_agent_batches, odim, adim, other_info_dim): """Average the neighbors' observations""" for index in range(sample_batch.count): neighbours = sample_batch.data['infos'][index]["neighbours"] neighbours_distance = sample_batch.data['infos'][ind...
ae34c43f9f43d7f12d90686a151db7d67b5970ff
60,894
def _password_repr(val: str) -> str: """Change representation of password to hide its content.""" del val return "'********'"
f7e5d653e874b023888d2f13502fc2ff9d894161
60,895
def pbkdf2_hmac(digest, secret, salt, rounds, keylen=None): """pkcs#5 password-based key derivation v2.0 using HMAC + arbitrary digest. :arg digest: digest name or constructor. :arg secret: passphrase to use to generate key. may be :class:`!bytes` or :class:`unicode` (encoded using...
35cdd3af4201b29b9990817b905ecc26145f49b1
60,896
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ with Configurator(settings=settings) as config: # static file for service description config.add_static_view('static', 'static') # X-road services config.add_route('services_he...
a4e72ebce045ae83e9ae952d1b6a7f83f3da6ad9
60,897
def filtered_descendants(glob): """Returns glob-matching filenames under the current directory, but skips some irrelevant paths.""" return find('.', glob, ['third_party', 'external', 'build*', 'out*', 'CompilerIdCXX', '.venv', 'glslang'])
0ff601d756950dfa93b91dcdd212ab659645dba6
60,898
def Home(request): """ 首页 :param request: :return: """ recommend = Recommend.objects.filter(is_recommend=True)[:10] qq = QQ.objects.all() links = link.objects.all() try: page = request.GET.get('page', 1) if page == '': page = 1 except PageNotAnIntege...
46f716d80ecc6bda3adb5893adcf5ac08d5f3b88
60,899
def test(context): """ Manage tests (L1 metadata). Check available tests, inspect their metadata. Convert old metadata into the new fmf format. """ # Show overview of available tests if context.invoked_subcommand is None: tmt.base.Test.overview() return 'test'
5cdc10f09c97b0036e585cee33bc0932686bb053
60,900
def valid_pos(newpos, sprites): """ checks if given position respects given distance between sprites """ mindist = DISTANCE_BETWEEN_SPRITES valid = True for s in sprites: if (newpos - s.pos).length() < mindist: valid = False break return valid
1f43e7f6ad6ba2040aade1375a52fd6c99d8bc8c
60,901
def register_guest(): """ Handle requests to the /register_guest route registers a guest account after an order has been made """ if session['guest']: user = User.query.filter_by(id=session['guest']).first() if user: user.is_registered=True form = Registratio...
995d8ecfa4810528c66ae9c521962edc805c27b7
60,902
def beaufort(wind): """ https://en.wikipedia.org/wiki/Beaufort_scale """ if wind >= 32.7: return "12 hurricane" elif wind > 28.5: return "11 violent storm" elif wind > 24.5: return "10 violent storm" elif wind > 28.5: return "9 violent storm" elif wind > 17.2: return "8 gale" elif ...
4fdbe110ea6b94bdeccbc5c1a4ad39950d35c479
60,903
from typing import Optional def identity(length: int, k: int, axis: Optional[int] = None) -> ndarray: """ Get a vector of given length L with one 1 at position K. Parameters ---------- length : int order of the row vector k : int position of 1 axis : int or None, optional ...
a7f23cdfc92f3a7c04fcfc87310773c8f8a9e23d
60,904
import posix def IsAppBundle(): # type: () -> bool """Are we running inside Oil's patched version of CPython? As opposed to a "stock" Python interpreter. """ # Ovm_Main in main.c sets this. return posix.environ.get('_OVM_IS_BUNDLE') == '1'
9e98681858e493231255f28ee3fbb41f1e104268
60,905
def pad_id(identifier, fmt): """Pad an identifier with leading zeros.""" if not isinstance(identifier, int): identifier = clean_id(identifier) if identifier == '': identifier = 0 else: identifier = int(identifier) return fmt % identifier
fc2d3ae886c0bd1bbe0dea2dce1b22af3f67ab22
60,906
import math def halstead_visitor_report(visitor): """Return a HalsteadReport from a HalsteadVisitor instance.""" h1, h2 = visitor.distinct_operators, visitor.distinct_operands N1, N2 = visitor.operators, visitor.operands h = h1 + h2 N = N1 + N2 if h1 and h2: length = h1 * math.log(h1, ...
441ecd5bcc963b579697654f2e745ca5a92a6b6a
60,907
import pandas def stackDF(df, column_names = ["column1","column2","values"], symmetric = True ): """Stacks similarity dataframe by return column1, column2, values df Args: df: pandas data frame column_names: names of return df (default ["column1","column2","values"] ) symmetric (...
d328a77f9bcf411a5ed1dbdd7f7328dcc675c23c
60,908
def install_system_packages(distro): """ Install system packages based on the Linux distribution of the remote node """ if distro in ["Debian", "Ubuntu"]: require.deb.uptodate_index(max_age={'day': 7}) return require.deb.packages(fsettings.DEBIAN_PKGS) elif distro in ["CentOS", "RHEL...
41628959b9dfa3d39890096ab34f82fc42ba2fc2
60,909
def cmp_structure(llst, rlst, lslices, rslices): """Compare the structure of llst[lslices] and rlst[rslices].""" lshape = slice_shape(llst, lslices) rshape = slice_shape(rlst, rslices) if (len(lshape) != len(rshape)): return -1 for i in range(len(lshape)): if lshape[i] != rshape[i]: ...
29e8abde9de56244d408fa247fa8e72e011b8539
60,910
def adjust_frame_length(x, pad=True, divisible_by=1, **kwargs): """Adjust frame length given a feature vector or matrix. This adjust the number of frames of a given feature vector or matrix to be divisible by ``divisible_by`` by padding to the end or removing the last few frames. Default uses zero-padd...
ef3b1aeea748703222351b3fc656b70ac52dfc22
60,911
def auth_routes(): """ 获得角色方法 :return: """ return jsonify({"/form/advanced-form":{"authority":["admin","user"]}})
75bc42327e2a2d943ce663bc5e10c0fb2e5f4b52
60,912
def tan(x): """ Returns the tangent of any given fractional value. :param x: fractional input (sfix, sfloat) :return: tan of :py:obj:`x` (sfix, sfloat) """ # reduces the angle to the [0,\pi/2) interval. w, b1, b2 = sTrigSub(x) # calculates the sin and the cos. local_sin = ssin(w, b...
2c182335133ab0abfa63f74e4f6d23cfe65123b2
60,913
def matrix_undirected_unweighted(user): """ Returns an undirected, unweighted matrix where an edge exists if the relationship is reciprocated. """ matrix = matrix_undirected_weighted(user, interaction=None) for a, b in combinations(range(len(matrix)), 2): if matrix[a][b] is None or matri...
f196ee5d22159a2ec54a05fb7f32f018a73c8023
60,914
def make_sessions(data, session_th=120 * 60, is_ordered=False, user_key='user_id', item_key='item_id', time_key='ts'): """Assigns session ids to the events in data without grouping keys""" if not is_ordered: # sort data by user and time data.sort_values(by=[user_key, time_key], ascending=True, i...
64cee8b4f3c26a6f6f819f3af57bd4cd20aedfe4
60,915
def balance_data(pairs, classes, n_proportion): """Balance negative and positives samples :param pairs: Positive/negative pairs previously generated :param classes: Classes corresponding to the pairs :param n_proportion: Proportion number, e.g. 2 """ classes = np.array(classes) pairs = np.a...
0bac6ba0a0db8a39566d118efb087c6fbff2de59
60,916
def UC_psi(Z_mask,I,V,q_dict,geo_dict,Z=10): """Generates uniformity correction image given input parameters. Returns dictionary that contains vectors: {q, S, sigS, N_pixels, N_outliers} and images: {outliers, Sfit, Ic, and UCpsi}. """ q = q_dict['q'] q_flat = q_dict['q_flat'] polfactor = geo_di...
f748eccd4bb3f4c6f23dd8de7dce506e9d122f70
60,917
def _g2D_func(f, xs_edges, ys_edges, xs_centres, ys_centres, x_indices, y_indices): """Calculate the position probability numerically.""" pos = np.empty((2,)) x_mod = np.empty((xs_centres.shape[0],)) y_mod = np.empty((ys_centres.shape[0],)) g_values = np.zeros((xs_centres.shape[0], ys_centres.shape[...
d5cb8854e0d197e797426af3f63441dda7cf1cd2
60,918
from presqt.targets.gitlab.functions.fetch import gitlab_fetch_resource import requests def gitlab_upload_keywords(token, resource_id, keywords): """ Upload the keywords to a given resource id. Parameters ---------- token: str User's GitLab token resource_id: str ID of the res...
f46df53a364345e252212ad8f05c0e455b4d0acb
60,919
def reset_network(): """ Method to return initial state of the network """ return jsonify_params( CELLULAR_NETWORK.reset_network() )
81174766ae29ac0ba61ca2e6f4d0ffc8a220ba08
60,921
def filter_table_artefacts( artefacts: tp.Iterable[Artefact] ) -> tp.Iterable[TableArtefact]: """ Filter all table artefacts from a list of artefacts. Args: artefacts: the artefacts to filter Returns: all table artefacts """ return [ tp.cast(TableArtefact, artefact)...
2056ca6f04404bfcb3466cb2024e521d0f67207f
60,922
from typing import Any import json def dumps(obj: Any) -> str: """Generate JSON from a Python object.""" return json.dumps(obj, cls=EventJSONEncoder)
019f913286e182dcc8370532f83cde2ac00482ef
60,923
def format_cpus(n): """Formats n as a number of CPUs""" return '{:.1f}'.format(n)
f28f8d24826341aab70347679920dc68f0b394b0
60,924
def camera(): """ check camera """ _cameras = cmds.ls(type = "camera") _left_cameras = list(set(_cameras) - set(["frontShape","topShape","perspShape","sideShape"])) if _left_cameras: info = "场景存在多余摄像机\n" for _camera in _left_cameras: info += "{}\n".format(_camera) ...
6adf64742a171b20ddf0c5d8c59fda845061aff9
60,925
def switch_block(CLIENT) -> str: """Returns hash of most recent switch block. """ return CLIENT.queries.get_block_at_era_switch()
70a1e712c521c24666de05ef11832f2d87217477
60,926
def format_exception_only(etype, value): """Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; howe...
8d8b1bd58cc84e0e00b59e41393f5b52b2e3d93c
60,927
def polyval2d(x, y, c): """ Evaluate a 2-D polynomial at points (x, y). This function returns the value .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * x^i * y^j The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they ...
7dddbf4c914cd74b7391aa97aee9610b746e7375
60,928
def _python(obj): """Highlight python syntax on Match object with one group.""" tmp = obj.group() if tmp[0] in ('"', '\'', '#'): return "<i>%s</i>" % tmp if tmp[0] in ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'): return "<u>%s</u>" % tmp if tmp[:4] == "def ": return "<b...
1b8a4c00ba15f31b15d62fb8719de901e65e5fe1
60,929
def from_str_to_bool(string): """ # Notes converts string to boolean value. # Arguments - string: string, either one of these values: "true", "false" """ res = string.lower() if res == 'true': return True else: return False
fea84bdebf9363d754d61755c7a8589a0b2b4950
60,930
def solve2(lines): """Solve the problem.""" path1 = trace_path(parse_path(lines[0])) path2 = trace_path(parse_path(lines[1])) dist = min([path1[(x, y)] + path2[(x, y)] for x, y in set(path1.keys()) & set(path2.keys())]) return dist
46a0e3f59b9a102677409379a176892a44ff170d
60,931
def multislice_assign(llst, rlst, lslices, rslices): """Return llst after assigning: llst[lslices] = rlst[rslices]""" if cmp_structure(llst, rlst, lslices, rslices) < 0: raise ValueError("lvalue and rvalue have different structures") return m_assign(llst, rlst, lslices, rslices)
f7c9dcc4e300104f51425d2ee20480b87d5f2f72
60,932
def callback(f, *a): """ Vraci funkci f s nastavenym parametrem a. Tato funkce umi osetrit i vice nez jeden parametr. Pouziti: callback(funkce, arg1, arg2, ..., argn ) """ return lambda: f(*a)
a08188ce01bf887fe7c8c58c300c0ca63ea6fc82
60,933
def _intersect_items(baselist, comparelist): """Return matching items in both lists.""" return list(set(baselist) & set(comparelist))
393e31d13dc63656167505068bcb6fee199d4c06
60,934
from datetime import datetime def _get_doy(fnames, freq, start): """Get the day of year from a filename. Args: freq (int): the frequency of the year, e.g. 365. fnames (list of str): the list of file names. start (string or None): the start date. Returns: numpy.ndarray: an...
bac82928bb7877a7012979f9e81c55023efedb25
60,935
from datetime import datetime async def process_request( dailies_by_station_id: dict, yesterday_dailies_by_station_id: dict, hourly_observations_by_station_id: dict, wfwx_station: WFWXWeatherStation, requested_station: StationRequest, time_of_interest: datetime ) -> Sta...
728b119a13c889ac1939afcb664a15d84bcab545
60,936
def get_engine(uri: str, connect_args: dict) -> sa.engine.Engine: """ Returns a sqlalchemy engine with pool_pre_ping enabled. This function may be updated over time to reflect recommended engine configuration for use with FastAPI. """ return sa.create_engine(uri, pool_pre_ping=True, connect_args=co...
f038d983afefa614beea3dfa55f2dcf266480d0b
60,937
def remove_extra_spaces(string_item): """ Remove all extra spaces from a string leaving single spaces :type string_item: String :param string_item: String that you want to remove spaces from :rtype: String :return: Corrected string without any extra spaces """ string_item = ' '.join(s...
cb7ce9197b5b59175f0712f1d2a4ba6727321c59
60,938
def parse_scale_conversion_command(sh: Worksheet, area: AreaTupleType, name: str = None) -> IssuesLabelContentTripleType: """ Analyze the input area Obtain the numerical part Read a row above and a column to the left, looking for source (left col) and target (row above) factor types FactorTypes do ...
5df3bb285d10790aecb1c6a6146f5decdb8e4737
60,939
def UnrefineSplineSet( fact = 2, compound = None, add = True, infa = False ): """ Description: Unrefines a spline set. Arguments: # fact Description: The unrefinement factor. For example, if equals 2, one spline over two is kept. Type: Integer GUI selection: - Selection by n...
4fcd1e977951592fa663ebba9f02b3c7d308c0b2
60,940
def cardbot_help() -> discord.Embed: """ Get usage on the bot commands. :returns: Instructions for using the bot """ embed = discord.Embed(title="Cardbot Help") embed.add_field( name="!search [card-name]", value=""" Gives a list of all cards matching the search, as well as the s...
cb61ac9a146fc7edd94a514756bccc43f4ec36dd
60,942
def joint_correctness_contingency_table(df1, df2, uid_key, prediction_key, true_label_key): """Makes a contingency table comparing correctness of model 1 and model 2. Args: df1: a DataFrame for the predictions of model 1. df2: a DataFrame for the predictions of model...
ad1c822015809e519fcb060a2346690b26add2ec
60,943
def tunein_to_station(base: Tunein, station_id: int, session=None) -> str: """ :param base: value is taken from the tunein node and based on the playlist format required (as PLS, M3U and XSPF formats are supported) :param station_id: station id :param session: request_cache session if available ...
e32424dd9908f6056855e21db38b5945b491fb9b
60,944
def OneHot(obs: np.ndarray): """ Args: obs:(N,obs_dim) Returns: obs:(N,obs_dim+N) """ N, _ = obs.shape encode = np.eye(N) # one hot encoding return np.concatenate([obs, encode], axis=1)
c1692af8b0001d2383f8db703fada342808cded2
60,947
def shortest_path(start, end): """ Using 2-way BFS, finds the shortest path from start_position to end_position. Returns a list of moves. You can use the rubik.quarter_twists move set. Each move can be applied using rubik.perm_apply """ visited_front={} parent_front={} q_front=dequ...
1296b29055ffbb6461375946c74a24103601f712
60,948
from datetime import datetime def reformat_date(date, new_fmt='%Y-%m-%d'): """ Return reformated date. Example: 01/28/2014 & %d/%m/%Y -> 28/01/2014 Accepted date format: %m/%d/%Y """ try: if type(date) is datetime: return date.strftime(new_fmt) else: fmt = '%m/%...
4e22350ad5a3b6f4087b5aadb1693263f31b5ee6
60,949
def all_episodes1(): """ contains playable podcasts listed as just-in """ soup = thisislove.get_soup(URL) playable_podcast1 = thisislove.get_playable_podcast1(soup) items = thisislove.compile_playable_podcast1(playable_podcast1) return items
594fe8c4fbed54f4f5a064125b193a05f720e794
60,950
def append_species(filename, lines, names): """ (dictionary, str) -> NoneType Appends all of the species and genes from one file to a dictionary. Returns a list that holds all the occurences of a species. """ for line in lines: if line[0] == ">": name = line[1:].strip() if name not in names: names...
d0ca1ccd4b0bc28676e68c3b4574ff1973969f86
60,951
import re def search_type(name, source): """ search for a specific type definitions return type body (as raw text) """ m = re.search(TYPE_RE_TEMPLATE.format(name=name), source, re.DOTALL) if m is None: raise ValueError("Type "+name+" was not found") return m.groupdict()["defs"]
7c3fa7696376f2a42d0203060087c92149dc80b2
60,952
def to_note_off_event(note, channel): """ :param note: model Note :return: Midi Event """ return midi.NoteOnEvent(channel=channel, tick=0, pitch=note.pitch, velocity=0)
5c0e506e2b461d759bbbbc5b2661dbbc1e957cb4
60,953