content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def eiffel_artifact_created_event(): """Eiffel artifact created event.""" return { "meta": { "id": "7c2b6c13-8dea-4c99-a337-0490269c374d", "time": 1575981274307, "type": "EiffelArtifactCreatedEvent", "version": "3.0.0", }, "links": [], ...
0ef2e5adadb58b92c94bac42c9880728573b159e
8,000
def _hash(input_data, initVal=0): """ hash() -- hash a variable-length key into a 32-bit value k : the key (the unaligned variable-length array of bytes) len : the length of the key, counting by bytes level : can be any 4-byte value Returns a 32-bit value. Every bit of the key affec...
c4f1b0ee22ca940d360090b965125e71c272ad4c
8,001
import logging def read_config_option(key, expected_type=None, default_value=None): """Read the specified value from the configuration file. Args: key: the name of the key to read from the config file. expected_type: read the config option as the specified type (if specified) default_...
effc94b89dd8b1e0765c71bd4c0c03760715db1d
8,002
def simple_password(request): """ Checks a password """ if request.method == "POST": form = PasswordForm(data=request.POST) if form.is_valid(): # TODO: set session with better param request.session["simple_auth"] = True return redirect(form.cleaned_dat...
4a70bb5578a528ed1646ce028e1db76e77ef7d91
8,003
from typing import Any import logging def removeKeys(array: dict = None, remove: Any = None) -> dict: """ Removes keys from array by given remove value. :param array: dict[Any: Any] :param remove: Any :return: - sorted_dict - dict[Any: Any] """ if remove is None: remove = [...
1b98821000642c79fbb71a9c0dc7163c4a95fa26
8,004
from trimesh.path.creation import box_outline from trimesh.path.util import concatenate def affine2boxmesh(affines): """ :param affines: (n_parts, 6), range (0, 1) :return: """ n_parts = len(affines) colors = [[0, 0, 255, 255], # blue [0, 255, 0, 255], # green ...
3d6568e6e533bdb31cdceb244666f376d73dad1e
8,005
def _select_index_code(code): """ 1 - sh 0 - sz """ code = str(code) if code[0] == '3': return 0 return 1
697d8e5ca1744c897b7eebbb7b9b0a3b45faec3d
8,006
def get_install_agent_cmd(): """Get OS specific command to install Telegraf agent.""" agent_pkg_deb = "https://packagecloud.io/install/repositories/" \ "wavefront/telegraf/script.deb.sh" agent_pkg_rpm = "https://packagecloud.io/install/repositories/" \ "wavefront/tele...
14373024b3b6046badcedf686a38423f126f02a2
8,007
from typing import Tuple from typing import DefaultDict import collections def unpack(manifests: LocalManifestLists) -> Tuple[ServerManifests, bool]: """Convert `manifests` to `ServerManifests` for internal processing. Returns `False` unless all resources in `manifests` are unique. For instance, returns ...
b7f3c3f1388b9d3791a18f2da97dd40cf131ecaa
8,008
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the switch from config.""" if DATA_KEY not in hass.data: hass.data[DATA_KEY] = {} host = config[CONF_HOST] token = config[CONF_TOKEN] name = config[CONF_NAME] model = config.get(CONF_MODEL) ...
0ef4f94c2b69bb2674ffcace56a85927c2c6d1d1
8,009
def process_generate_metric_alarms_event(event): """Handles a new event request Placeholder copied from alert_controller implementation """ LOG.info(str(event)) return create_response(200, body="Response to HealthCheck")
45f3ac5fa73048ec1f76bb5188a4e1de0eaca62d
8,010
def get_query_segment_info(collection_name, timeout=None, using="default"): """ Notifies Proxy to return segments information from query nodes. :param collection_name: A string representing the collection to get segments info. :param timeout: An optional duration of time in seconds to allow for the RPC...
521119f98a43d1abc303028f9bfa150dbfba098b
8,011
def IoU(pred, gt, n_classes, all_iou=False): """Computes the IoU by class and returns mean-IoU""" # print("IoU") iou = [] for i in range(n_classes): if np.sum(gt == i) == 0: iou.append(np.NaN) continue TP = np.sum(np.logical_and(pred == i, gt == i)) FP = n...
9635472121b13c9ce04e38fdfaee8bf29774a17a
8,012
def from_torchvision(vision_transform, p=1): """Takes in an arbitary torchvision tranform and wrap it such that it can be applied to a list of images of shape HxWxC Returns a callable class that takes in list of images and target as input NOTE: Due to implementation difficuities, in order ...
b2af1a672d24171d9b80cd4eeb6d53fc80d09f53
8,013
import requests def is_valid(inputted): """ Essa função irá verificar o QueryDict trago pelo método POST do nosso frontend e fazer uma verificação dos campos an tes de persistir os dados no banco de dados. :param inputted: Query Dict trago pelo POST :return: Um valor booleano """ for key i...
ff52ad53f2073ff3659d16601528984f7282940a
8,014
def get_ports(context, project_id=None): """Returns all ports of VMs in EOS-compatible format. :param project_id: globally unique neutron tenant identifier """ session = context.session model = db_models.AristaProvisionedVms if project_id: all_ports = (session.query(model). ...
17d8dadde3dde78286f746435454b454d5589bd2
8,015
import hashlib import hmac def _HMAC(K, C, Mode=hashlib.sha1): """ Generate an HMAC value. The default mode is to generate an HMAC-SHA-1 value w/ the SHA-1 algorithm. :param K: shared secret between client and server. Each HOTP generator has a different and unique secret K. :type K: ...
db9bf26c52427acc259f3cb1590c7c13b0d0dd9e
8,016
def get_reference(planet_name): """ Return reference for a given planet's orbit fit Args: planet_name (str): name of planet. no space Returns: reference (str): Reference of orbit fit """ planet_name = planet_name.lower() if planet_name not in post_dict: raise Value...
b700509300bdb2f6595e2a7c44a0d84e04d795f8
8,017
def DefaultPortIfAvailable(): """Returns default port if available. Raises: EmulatorArgumentsError: if port is not available. Returns: int, default port """ if portpicker.is_port_free(_DEFAULT_PORT): return _DEFAULT_PORT else: raise EmulatorArgumentsError( 'Default emulator port [{...
40c065946d8f9ee6c50f7df40f2be6644a472414
8,018
def mock_hub(hass): """Mock hub.""" mock_integration(hass, MockModule(DOMAIN)) hub = mock.MagicMock() hub.name = "hub" hass.data[DOMAIN] = {DEFAULT_HUB: hub} return hub
b4495ca6fbb7638aedf86406f94c00566e376b1b
8,019
def deferred_setting(name, default): """ Returns a function that calls settings with (name, default) """ return lambda: setting(name, default)
286acec75f7a5a1e0217dc4cee7b7b5d1ba8e742
8,020
def extends_dict(target, source): """ Will copy every key and value of source in target if key is not present in target """ for key, value in source.items(): if key not in target: target[key] = value elif type(target[key]) is dict: extends_dict(target[key], value) ...
5a68dde5e3bb7dbb81ad61c3698614f56dd5efd7
8,021
def get_maps_interface_class(zep_inp): """ Takes the input of zephyrus and return the maps of interfaces to classes and viceversa """ interface_to_classes = {} class_to_interfaces = {} for i in zep_inp["components"].keys(): class_name = i.split(settings.SEPARATOR)[-1] interfaces = zep_inp["compone...
9a14de30677abe0fa8cf0bb3907cd1f32a8f33de
8,022
def plextv_resources_base_fixture(): """Load base payload for plex.tv resources and return it.""" return load_fixture("plex/plextv_resources_base.xml")
f252099bd6457af208c4d96b8024d3ce28d84cd9
8,023
from netrc import netrc from requests.auth import HTTPDigestAuth def _auth(machine='desi.lbl.gov'): """Get authentication credentials. """ n = netrc() try: u,foo,p = n.authenticators(machine) except: raise ValueError('Unable to get user/pass from $HOME/.netrc for {}'.format(machine...
4ef27e589416f54dd76522b3312a2aa24441e200
8,024
import re def relative_date_add(date_rule: str, strict: bool = False) -> float: """Change the string in date rule format to the number of days. E.g 1d to 1, 1y to 365, 1m to 30, -1w to -7""" days = '' if re.search(DateRuleReg, date_rule) is not None: res = re.search(DateRuleReg, date_rule) ...
9180ed2ec99302679f7d0e2ee9ca57c4e2e6c48c
8,025
def to_frames_using_nptricks(src: np.ndarray, window_size: int, stride: int) -> np.ndarray: """ np.ndarray をフレーム分けするプリミティブな実装で,分割に`np.lib.stride_tricks.as_strided`関数を使用しており,indexingを使用する`to_frames_using_index`より高速である. Parameters ---------- src: np.ndarray splited source. window_size: i...
b10b077cf0fbf2b0e491e7f1cba9033cfadf10c5
8,026
def global_fit( model_constructor, pdf_transform=False, default_rtol=1e-10, default_atol=1e-10, default_max_iter=int(1e7), learning_rate=1e-6, ): """ Wraps a series of functions that perform maximum likelihood fitting in the `two_phase_solver` method found in the `fax` python module....
46917c0a4e6469759184a4aaa8199c57573360b0
8,027
import os def get_connection_string(storage_account_name): """ Checks the environment for variable named AZ_<STORAGE_ACCOUNT_NAME> and returns the corresponding connection string. Raises a ``ConnectionStringNotFound`` exception if environment variable is missing """ conn_string = os.environ....
0f776e98741132dcce60ced478ab8c4514c5a9f8
8,028
from typing import Optional from typing import List def reorder_task( token: 'auth.JWT', task_id: 'typevars.ObjectID', before_id: 'Optional[typevars.ObjectID]' = None, after_id: 'Optional[typevars.ObjectID]' = None ) -> 'List[models.Task]': """Change the position of the task in the list.""" if...
b9e30b6d5929614d8385bd478e0e0a1f2663723f
8,029
def get_ldpc_code_params(ldpc_design_filename): """ Extract parameters from LDPC code design file. Parameters ---------- ldpc_design_filename : string Filename of the LDPC code design file. Returns ------- ldpc_code_params : dictionary Parameters of the LDPC code. "...
a2702a3fb5faf67d56fa08ae7ab627e3142fb006
8,030
def find_collection(*, collection, name): """ Looks through the pages of a collection for a resource with the specified name. Returns it, or if not found, returns None """ if isinstance(collection, ProjectCollection): try: # try to use search if it is available # cal...
a6532f2f63b682822f96e51d7ab86e7bc240d922
8,031
def terms_documents_matrix_ticcl_frequency(in_files): """Returns a terms document matrix and related objects of a corpus A terms document matrix contains frequencies of wordforms, with wordforms along one matrix axis (columns) and documents along the other (rows). Inputs: in_files: list of tic...
25e6cf8ca1696ebb1d5d7f72ddd90fe091e22030
8,032
def cvt_continue_stmt(node: pytree.Base, ctx: Ctx) -> ast_cooked.Base: """continue_stmt: 'continue'""" #-# Continue assert ctx.is_REF, [node] return ast_cooked.ContinueStmt()
1eefd660e9023aa69957cf1004369d6495048437
8,033
def nth_even(n): """Function I wrote that returns the nth even number.""" return (n * 2) - 2
26e1465a039352917647ae650d653ed9842db7f6
8,034
def _has__of__(obj): """Check whether an object has an __of__ method for returning itself in the context of a container.""" # It is necessary to check both the type (or we get into cycles) # as well as the presence of the method (or mixins of Base pre- or # post-class-creation as done in, e.g., ...
638b6ed823acf2a46ae5a5cda6d3565fad498364
8,035
def grayscale(img): """ Applies the Grayscale transform This will return an image with only one color channel but NOTE: to see the returned image as grayscale (assuming your grayscaled image is called 'gray') you should call plt.imshow(gray, cmap='gray') """ return cv2.cvtColor(img, cv2...
3c3b0508850c5cdaf2617ed37c6f5eea79be64d0
8,036
def get_pageinfo(response, tracktype='recenttracks'): """Check how many pages of tracks the user have.""" xmlpage = ET.fromstring(response) totalpages = xmlpage.find(tracktype).attrib.get('totalPages') return int(totalpages)
ed5c05bcc648d4a22c5f1b51b196743bf6883dff
8,037
def MIN(*args): """Return the minimum of a range or list of Number or datetime""" return _group_function(min, *args)
044d1d433901f6ed3308aad711a6bf7eca4e2301
8,038
def GF(order, irreducible_poly=None, primitive_element=None, verify_irreducible=True, verify_primitive=True, mode="auto", target="cpu"): """ Factory function to construct a Galois field array class of type :math:`\\mathrm{GF}(p^m)`. The created class will be a subclass of :obj:`galois.FieldArray` with meta...
d09dea199559aad111e6aa30a2c391da9ae6b551
8,039
import typing def remove_fields_with_value_none(fields: typing.Dict) -> typing.Dict: """ Remove keys whose value is none :param fields: the fields to clean :return: a copy of fields, without the none values """ fields = dict((key, value) for key, value in fields.items() if va...
22d7ac2a77248809c691bdb98f5f6ebaaf6d4f2b
8,040
def make_values(params, point): #240 (line num in coconut source) """Return a dictionary with the values replaced by the values in point, where point is a list of the values corresponding to the sorted params.""" #242 (line num in coconut source) values = {} #243 (line num in coconut source) for i, k...
8287b49e54cb08802350a3a15805dc20def10ece
8,041
def elbow_method(data): """ This function will compute elbow method and generate elbow visualization :param data: 2 columns dataframe for cluster analysis :return: Plotly Figures """ distortions = [] K = range(1, 10) for k in K: elbow_kmean = model_kmeans(data, k) distor...
5420ce252f8a89ae3540ce37cbfd4f31f0cbe93e
8,042
from typing import Callable def sa_middleware(key: str = DEFAULT_KEY) -> 'Callable': """ SQLAlchemy asynchronous middleware factory. """ @middleware async def sa_middleware_(request: 'Request', handler: 'Callable')\ -> 'StreamResponse': if key in request: raise DuplicateReq...
df4da137e45fcaa2962626a4f3676d9f7b9ecce9
8,043
def dice_loss(y_true, y_pred): """ dice_loss """ smooth = 1. intersection = K.sum(K.abs(y_true * y_pred), axis=-1) dice_coef = (2. * intersection + smooth) / (K.sum(K.square(y_true),-1) + \ K.sum(K.square(y_pred),-1) + smooth) return 1 - dice_coef
863f69071375f37fed3c8910e52c1ffbda14cd71
8,044
def webdriver_init(mobile): """ Initialize a mobile/desktop web driver. This initialize a web driver with a default user agent regarding the mobile demand. Default uer agents are defined by MOBILE_USER_AGENT and DESKTOP_USER_AGENT. :param mobile: The mobile flag :type conn:...
49215bfd5363b9e7e82329b42b97ad04402b7edb
8,045
import hashlib def calculate_file_hash(f, alg, buf_size): """BUF_SIZE - 64 kb need for large file""" h = hashlib.new(alg) for chunk in iter(lambda: f.read(buf_size), b""): h.update(chunk) return h.hexdigest()
6361ef8f18f5ae66e1d51503426c77f7505e10be
8,046
def update(A, B, DA, DB, f, k, delta_t): """Apply the Gray-Scott update formula""" # compute the diffusion part of the update diff_A = DA * apply_laplacian(A) diff_B = DB * apply_laplacian(B) # Apply chemical reaction reaction = A*B**2 diff_A -= reaction diff_B += reaction # A...
75c2004ea089d5b3a9f4ec71fc27510d1c0dc5c0
8,047
import typing import hashlib def sha512(data: typing.Optional[bytes] = None): """Returns a sha512 hash object; optionally initialized with a string.""" if data is None: return hashlib.sha512() return hashlib.sha512(data)
067fffc4c006d9c46e5037b07b86149ac15bb573
8,048
import os def _circle_ci_pr(): """Get the current CircleCI pull request (if any). Returns: Optional[int]: The current pull request ID. """ try: return int(os.getenv(env.CIRCLE_CI_PR_NUM, '')) except ValueError: return None
ae8739a4abbc04181fd17dcd8963beed71db3597
8,049
def get_entropy_of_maxes(): """ Specialized code for retrieving guesses and confidence of largest model of each type from the images giving largest entropy. :return: dict containing the models predictions and confidence, as well as the correct label under "y". """ high_entropy_list = get_high_en...
9a43ac44a61776d25d3b46a7fb733d95720e3beb
8,050
from typing import List from typing import Dict from typing import Any def get_all_links() -> List[Dict[str, Any]]: """Returns all links as an iterator""" return get_entire_collection(LINKS_COLLECTION)
1bda0ac68f778c77914163dd7855491cc04a2c97
8,051
def agent(states, actions): """ creating a DNN using keras """ model = Sequential() model.add(Flatten(input_shape=(1, states))) model.add(Dense(24, activation='relu')) model.add(Dense(24, activation='relu')) model.add(Dense(24, activation='relu')) model.add(Dense(actions, activation=...
b9f8415955cc1b01dbe46b94dd84ab3daa6811c2
8,052
def get_package_nvr_from_spec(spec_file): """ Return a list of the NVR required for a given spec file :param spec_file: The path to a spec file :type spec_file: str :return: list of nevra that should be built for that spec file :rtype: str """ # Get the dep name & version spec = rpm....
9f8c5e5451d9b7fd3721881645688781b221e08d
8,053
def rbo_ext(S, T, p): """Extrapolated RBO value as defined in equation (30). Implementation handles uneven lists but not ties. """ if len(S) > len(T): L, S = S, T else: L, S = T, S l, s = len(L), len(S) xl = overlap(L, S, l) xs = overlap(L, S, s) sum1 = sum(overlap(...
367c979f8ece073e86e9fdc48a26bb393f0236be
8,054
def index(request): """ View of index page """ title = _("Home") posts = Post.objects.all().order_by('-timestamp')[:5] return render(request, 'dashboard/index.html', locals())
a152bfad756be809c56e6dc203cb7cf9d29f4868
8,055
def incremental_str_maker(str_format='{:03.f}'): """Make a function that will produce a (incrementally) new string at every call.""" i = 0 def mk_next_str(): nonlocal i i += 1 return str_format.format(i) return mk_next_str
41ce6e7d7ba69922f92e73ee516e9c09fdbe0713
8,056
def get_time_slider_range(highlighted=True, withinHighlighted=True, highlightedOnly=False): """Return the time range from Maya's time slider. Arguments: highlighted (bool): When True if will return a selected frame range (if there's any se...
f05ca2bfec8bcfb41be9a0fa83a724d180dc545f
8,057
def update_IW(hyp_D_prev, xikk, xk, Pik_old): """ Do an update of Norm-IW conjugate in an exponential form. """ suff_D = get_suff_IW_conj(xikk, xk, Pik_old) hyp_D = hyp_D_prev + suff_D Dik = get_E_IW_hyp(hyp_D) return Dik, hyp_D
d787edf13e18cdbc1c6ff3a65168f32ff8c28b1f
8,058
def compute_state(observations, configuration): """ :param observations: :param configuration: :return StateTensor: """ StateTensorType = configuration.STATE_TYPE return StateTensorType([observations])
44a08caa02137438359c4cd764fff1700b6252b2
8,059
def supports_transfer_syntax(transfer_syntax: pydicom.uid.UID) -> bool: """Return ``True`` if the handler supports the `transfer_syntax`. Parameters ---------- transfer_syntax : uid.UID The Transfer Syntax UID of the *Pixel Data* that is to be used with the handler. """ return t...
65f85a47afc5002ed33e4ad787317d67b4dab218
8,060
def enhance_user(user, json_safe=False): """ Adds computed attributes to AD user results Args: user: A dictionary of user attributes json_safe: If true, converts binary data into base64, And datetimes into human-readable strings Returns: An enhanced dictionary of user at...
4b6fd08440c9c92d074e639f803b242f044f2ea3
8,061
from datetime import datetime import random def create_data(namespace_id, ocs_client): """Creates sample data for the script to use""" double_type = SdsType(id='doubleType', sdsTypeCode=SdsTypeCode.Double) datetime_type = SdsType( id='dateTimeType', sdsTypeCode=SdsTypeCode.DateTime) pressure...
c0b01e36e350d152d758a744735688d15826be06
8,062
def enhanced_feature_extractor_digit(datum): """Feature extraction playground for digits. You should return a util.Counter() of features for this datum (datum is of type samples.Datum). ## DESCRIBE YOUR ENHANCED FEATURES HERE... """ features = basic_feature_extractor_digit(datum) "*** YOU...
b98ef2caf6b51176fae18ae36dd0c316ab2d8ee7
8,063
from typing import Union def linear_resample(x: Union[ivy.Array, ivy.NativeArray], num_samples: int, axis: int = -1, f: ivy.Framework = None)\ -> Union[ivy.Array, ivy.NativeArray]: """ Performs linear re-sampling on input image. :param x: Input array :type x: array :param num_samples: The...
bd6b54ee5cafe5409eb6aa47da57db2ad3b7fff2
8,064
import os def mysql_settings(): """Return a list of dict of settings for connecting to postgresql. Will return the correct settings, depending on which of the environments it is running in. It attempts to set variables in the following order, where later environments override earlier ones. 1...
0fb9a0c0bdc71079da46fbc5f5ed35fd19c985df
8,065
def update_milestones(repo, username=None, namespace=None): """Update the milestones of a project.""" repo = flask.g.repo form = pagure.forms.ConfirmationForm() error = False if form.validate_on_submit(): redirect = flask.request.args.get("from") milestones = flask.request.form.ge...
4869d70a4d8bd85436639dd3214f208822f7241b
8,066
def installedState(item_pl): """Checks to see if the item described by item_pl (or a newer version) is currently installed All tests must pass to be considered installed. Returns 1 if it looks like this version is installed Returns 2 if it looks like a newer version is installed. Returns 0 othe...
b3ec76863f75c87ed11a7984eb36384379c96229
8,067
def trapezoid_vectors(t, depth, big_t, little_t): """Trapezoid shape, in the form of vectors, for model. Parameters ---------- t : float Vector of independent values to evaluate trapezoid model. depth : float Depth of trapezoid. big_t : float Full trapezoid duration. ...
759c7cf946bf9ea998644bea9b28f46dea5a6e55
8,068
def get_rules(clf, class_names, feature_names): """ Extracts the rules from a decision tree classifier. The keyword arguments correspond to the objects returned by tree.build_tree. Keyword arguments: clf: A sklearn.tree.DecisionTreeClassifier. class_names: A list(str) containing the class n...
a4d9bc1964553d384f1c795e2ad4834a532ddbba
8,069
import os import subprocess def save_repo(repo, target="/run/install"): """copy a repo to the place where the installer will look for it later.""" newdir = mkdir_seq(os.path.join(target, "DD-")) log.debug("save_repo: copying %s to %s", repo, newdir) subprocess.call(["cp", "-arT", repo, newdir]) re...
678d35effe4cc72ce7a46cf6af9ff0b62a277607
8,070
def file_parser(localpath = None, url = None, sep = " ", delimiter = "\t"): """ DOCSTRING: INPUT: > 'localpath' : String (str). Ideally expects a local object with a read() method (such as a file handle or StringIO). By default, 'localpath=dummy_file' parameter can be passed to auto-detect and parse...
a1f8cc5fceffdc2a20f745afbce44645634221bd
8,071
def is_list(var, *, debug=False): """ is this a list or tuple? (DOES NOT include str) """ print_debug(debug, "is_list: got type %s" % (type(var))) return isinstance(var, (list, tuple))
8c24f02aea597c6d17218a468ec59481d873a950
8,072
import logging def zonotope_minimize(avfun, avdom, avdfun): """ Minimize a response surface defined on a zonotope. :param function avfun: A function of the active variables. :param ActiveVariableDomain avdom: Contains information about the domain of `avfun`. :param function avdfun: Return...
af42a5a8e2c73c9fa0f4f7dcfdd159809e0f7a10
8,073
def node_to_truncated_gr(node, bin_width=0.1): """ Parses truncated GR node to an instance of the :class: openquake.hazardlib.mfd.truncated_gr.TruncatedGRMFD """ # Parse to float dictionary if not all([node.attrib[key] for key in ["minMag", "maxMag", "aValue", "bValue"]]): ...
0fd81e01140ec7b1a38f28c527139b61cc1c3a92
8,074
def nt(node, tag): """ returns text of the tag or None if the tag does not exist """ if node.find(tag) is not None and node.find(tag).text is not None: return node.find(tag).text else: return None
7ca5f83cf18f918f594374fa2aa875415238eef6
8,075
def set_user_favorites(username, **_): """ Sets the user's Favorites Variables: username => Name of the user you want to set the favorites for Arguments: None Data Block: { # Dictionary of "alert": [ "<name_of_query>": # Named queries ...
391ff8e9736bb2baddbf388c5a203cf9d2d7bdcc
8,076
def delete_token(token_id): """Revoke a specific token in the application auth database. :type token_id: str :param token_id: Token identifier :rtype: tuple :return: None, status code """ client_data = g.client_data if not valid_token_id(token_id): raise Malforme...
204f4ae2c0dc7c704f05baa86930bc7962d1b639
8,077
from typing import Optional async def update_country(identifier: Optional[str] = None, name: Optional[str] = None, capital: Optional[str] = None, country: UpdateCountryModel = Body(...), current_user: AdminModel = Depends(get_current_user)): """ Update a country by name or capital nam...
7805ca1d8e99e21b2558258e890f11fb4f697df9
8,078
def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ """method-1 time O(n), traverse all, get rest""" for i in range(len(nums)): res = target - nums[i] if res in nums: return [i, nums.index(res)] else: ret...
8c5cd095c7800fa5da698dffa0d76d3c00a8a3c1
8,079
def transform_image(image, code_vectors): """ Quantize image using the code_vectors (aka centroids) Return a new image by replacing each RGB value in image with the nearest code vector (nearest in euclidean distance sense) returns: numpy array of shape image.shape ...
19aae8ca188de03f4b916f52d724048c757e936f
8,080
def create_linking_context_from_compilation_outputs( *, actions, additional_inputs = [], alwayslink = False, compilation_outputs, feature_configuration, label, linking_contexts = [], module_context, name = None, swift_toolchain, ...
4918932b7f47495a59226de64cb4c110227a9c8e
8,081
from miniworld.util import ConcurrencyUtil def wait_until_uds_reachable(uds_path, return_sock=False): """ Wait until the unix domain socket at `uds_path` is reachable. Returns ------- socket.socket """ sock = ConcurrencyUtil.wait_until_fun_returns_true(lambda x: x[0] is True, uds_reachable, ...
574053ed1b4ccacda37bec58740ad497e690746a
8,082
def get_relation_count_df( dataset: Dataset, merge_subsets: bool = True, add_labels: bool = True, ) -> pd.DataFrame: """Create a dataframe with relation counts. :param dataset: The dataset. :param add_labels: Whether to add relation labels to the dataframe. :param merge_subs...
a15c22d0790c346cac3842f84a80ee7c27c4471a
8,083
def get_tests(run_id): """ Ручка для получения информации о тест (из тест-рана) Выходящий параметр: test_id """ client = APIClient('https://testrail.homecred.it') client.user = 'dmitriy.zverev@homecredit.ru' client.password = 'Qwerty_22' tests = client.send_get('get_tests/%s' % run_id) ...
a188e8a04dc72e485d5c519c09fcdbd8f2f18f31
8,084
from datetime import datetime def create_ffs(): """ Create a new Powergate Filecoin Filesystem (FFS) """ powergate = PowerGateClient(app.config["POWERGATE_ADDRESS"]) ffs = powergate.ffs.create() creation_date = datetime.now().replace(microsecond=0) # TODO salt token id filecoin_file_...
4163d080ae0ec7e2de2090b2ee6112fdbec89d75
8,085
def other(player): """Return the other player, for a player PLAYER numbered 0 or 1. >>> other(0) 1 >>> other(1) 0 """ return 1 - player
08503c35276cf86efa15631bb6b893d72cbae4d5
8,086
def _explored_parameters_in_group(traj, group_node): """Checks if one the parameters in `group_node` is explored. :param traj: Trajectory container :param group_node: Group node :return: `True` or `False` """ explored = False for param in traj.f_get_explored_parameters(): if pa...
71cbafbad0dcc3fa9294c0bede5f6a09941d452b
8,087
def _execute(query, data=None, config_file=DEFAULT_CONFIG_FILE): """Execute SQL query on a postgres db""" # Connect to an existing database. postgres_db_credentials = postgres_db(config_file) conn = psycopg2.connect(dbname=postgres_db_credentials["dbname"], ...
84884b6a0902ce7fe964b145f3124a1699f72453
8,088
from pathlib import Path def _construct_out_filename(fname, group_name): """ Construct a specifically formatted output filename. The vrt will be placed adjacent to the HDF5 file, as such write access is required. """ basedir = fname.absolute().parent basename = fname.with_suffix('.vrt').na...
117bb8470ab65f0b9fb11bb3151ae653e5e28d23
8,089
import json def _deposit_need_factory(name, **kwargs): """Generate a JSON argument string from the given keyword arguments. The JSON string is always generated the same way so that the resulting Need is equal to any other Need generated with the same name and kwargs. """ if kwargs: for ke...
9c8813f0be657b51a787d9badd2f677aca84a002
8,090
def not_equal(version1, version2): """ Evaluates the expression: version1 != version2. :type version1: str :type version2: str :rtype: bool """ return compare(version1, '!=', version2)
5dab948ec2a3eb8d3cb68fcd9887aedb394757df
8,091
def get_sp_list(): """ Gets all tickers from S&P 500 """ bs = get_soup('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies') sp_companies = bs.find_all('a', class_="external text") return sp_companies
be850de6fc787faaa05bbd3100dc82ce56cceb22
8,092
def get_params_nowcast( to, tf, i, j, path, nconst, depthrange='None', depav=False, tidecorr=tidetools.CorrTides): """This function loads all the data between the start and the end date that contains hourly velocities in the netCDF4 nowcast files in the specified dept...
4cf44961da3109593176476d8e4092a2c05b7a18
8,093
def convert_size(size): """ Helper function to convert ISPMan sizes to readable units. """ return number_to_human_size(int(size)*1024)
a28c8332d8f44071409436f4ec7e844a58837f49
8,094
def get_suppressed_output( detections, filter_id: int, iou: float, confidence: float, ) -> tuple: """Filters detections based on the intersection of union theory. :param detections: The tensorflow prediction output. :param filter_id: The specific class to be filtered. :param iou: The int...
b6a294611ec22fd48a7a72e51e66e43732c1d3f7
8,095
def tf_nan_func(func, **kwargs): """ takes function with X as input parameter and applies function only on finite values, helpful for tf value calculation which can not deal with nan values :param func: function call with argument X :param kwargs: other arguments for func :return: executed f...
d43e509a142bf78025d32984c9ecb0c0856e9a90
8,096
def deep_update(original, new_dict, new_keys_allowed=False, allow_new_subkey_list=None, override_all_if_type_changes=None): """Updates original dict with values from new_dict recursively. If new key is introduced in new_dict, then if new_keys_allo...
12573fd3efef4fc9d6c222ccc3ea525c131a2088
8,097
def queued_archive_jobs(): """Fetch the info about jobs waiting in the archive queue. Returns ------- jobs: dict """ jobs = pbs_jobs() return [ job for job in jobs if (job["job_state"] == "Q" and job["queue"] == "archivelong") ]
af4495f6484cf2e819655a1807a38556f62119a5
8,098
def getCustomKernelSolutionObj(kernelName, directory=globalParameters["CustomKernelDirectory"]): """Creates the Solution object for a custom kernel""" kernelConfig = getCustomKernelConfig(kernelName, directory) for k, v in kernelConfig.items(): if k != "ProblemType": checkParametersAreVa...
31cec952f3dc5afefa5a50bc8a54fe00eb3d3fe9
8,099