content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import copy_reg as copyreg import copyreg import types def _loading_multiprocess(): """ Black magic function to load to enable pickle in multiprocess """ try: except: def _pickle_method(m): if m.im_self is None: return getattr, (m.im_class, m.im_func.func_name) else: ...
c9b9689512752e0397e0f149344fa627fee04cfe
3,604,072
def configure_account_ldc_for_discovery(servicenow_url, ldc_sys_id, new_account_sys_id, discovery_schedule_id): """ Associates service accounts data center with specified discovery schedule to configure for discovery :param servicenow_url: ServiceNow endpoint URL :param ldc_sys_id: Id of discovery stat...
3d09c54ef6aeacd6da0b2cf6d86a18b08ad570e0
3,604,073
def cradmin_instance_url(context, appname, viewname, *args, **kwargs): """ Template tag implementation of :meth:`cradmin_legacy.crinstance.BaseCrAdminInstance.reverse_url`. Examples: Reverse the view named ``"edit"`` within the app named ``"pages"``: .. code-block:: htmldjango ...
9cea000ff75b68d536796cbcc323fef1b0a7059b
3,604,074
def server_state(request): """Get the status for a server. Anyone can request this, :param name: Name of VApp which we want to stop. :returns: The state, by name. """ vm_id, actor_id = _resolve_vm(request) return server.check_state(vm_id)
69c5ddcf6bc70e8d3a5c3494f85996e7318fc8fe
3,604,075
from typing import Sequence def broadcast_in_dim(operand: Array, shape: Shape, broadcast_dimensions: Sequence[int]) -> Array: """Wraps XLA's `BroadcastInDim <https://www.tensorflow.org/xla/operation_semantics#broadcastindim>`_ operator. Args: operand: an array shape: the shape of...
ec611197f76332c2ff207139275082dfab9705ba
3,604,077
def QualityControl_Cast(*args): """ Cast(BaseObject o) -> QualityControl QualityControl_Cast(Seiscomp::Core::BaseObjectPtr o) -> QualityControl """ return _DataModel.QualityControl_Cast(*args)
2705d83114ff121b0436fe964ce4054014d7ab70
3,604,078
def read_js(filename): """ Reads a specific type of JS file to JSON JS file - defines one variable to be interpreted as JSON :param filename: JS file name :return: JSON """ with open(filename, 'r') as f: js_text = f.readlines()[0] # JS should all be on a single line equal_s...
44975caadd0421f1ab5dbf2baf4c71bab2f41355
3,604,079
def execute(pagename, request): """ Temporary glue code for current moin action system """ if request.method != 'POST': return False, u'' return NewPage(request, pagename).render()
6ceba6e6a3118b9a1922f2be5ae2f9a432fba0e0
3,604,082
import string def html5_parse_legacy_color(input_str: str) -> HTML5SimpleColor: """ Apply the legacy color parsing algorithm from section 2.4.6 of HTML5. """ # 1. Let input_str be the string being parsed. if not isinstance(input_str, str): raise ValueError( "HTML5 legacy c...
5b397503c87d7671f9a7d6deb4a18b29c6bbba94
3,604,083
from typing import OrderedDict def _munsell_maximum_chromas_from_renotation(): """ Returns the maximum *Munsell* chromas from *Munsell Renotation System* data and caches them if not existing. Returns ------- tuple Maximum *Munsell* chromas. """ global _MUNSELL_MAXIMUM_CHROMAS...
4fd0d4456cc2bdbe3bd74a44cd96334e180490d6
3,604,084
def calculate_atom_symmetry_number(molecule, atom): """ Return the symmetry number centered at `atom` in the structure. The `atom` of interest must not be in a cycle. """ symmetry_number = 1 single = double = triple = benzene = num_neighbors = 0 # note that 0 is immutable for bond in atom....
d4b28f2b0cb793a5b6190c85c73bd56196ebec43
3,604,085
def parse_xml(xml_string): """ Parse an XML string into an lxml object. If the XML is invalid, None is returned. :param str xml_string: a string of XML :return: lxml object representing the XML content :rtype: etree._Element or None """ try: parsed = fromstring(xml_string) ...
21d0b67c77cb600b915643f4e7b68b9c4fb8543f
3,604,086
def _conformer_source(conf): """Determines source of given conformer.""" if not conf.HasField('properties'): if conf.duplicated_by == 0 and not conf.duplicate_of: raise ValueError( 'Unknown conformer source, no properties or duplicates: ' + str(conf)) return _ConformerSource.DUPLICATE # Ki...
0a2ac843cbc39086981567e99fe8697339a5f92c
3,604,087
import torch def get_discretized_transformation_matrix(matrix, discrete_ratio, downsample_rate): """ Get disretized transformation matrix. Parameters ---------- matrix : torch.Tensor Shape -- (B, L, 4, 4) where B is the batch size, L is the max cav...
fd6ab95dcbb6fca9cab6b35fd5e20998fc12472b
3,604,089
def qiskit_routing(circuit, device): """ Routing using qiskit :param circuit: Circuit object, Either qasm filepath or Cirq's circuit object :param device: Device object, Defines topology for hardware specific routing :returns depth: int, Circuit depth according to tket routing strategies """ ...
060e203cf293ed35c622b598849f1066942f4e48
3,604,090
import re def remove_surrogates(s): """ The following is a helper function, used to convert two-character surrogate sequences into single characters. This is needed because some systems create surrogates but others don't. """ pieces = re.split('(&#\d+;)', s) for i in range(3, len(pieces)-...
31426a1cc76838dec58d78c8ab8a951f84f4eda0
3,604,091
def basic_bn_stem(model, data, dim_in, **kwargs): """Add a basic DenseNet stem. For a pre-trained network that used BN. An AffineChannel op replaces BN during fine-tuning. """ dim = dim_in p = model.Conv(data, 'conv1', 3, dim, 7, pad=3, stride=2, no_bias=1) p = model.AffineChannel(p, 'conv1_bn'...
37469f6baccdc9ec0de5228b6398963e8a984a57
3,604,092
import torch def calc_word_prob(rnn, word, revmap, hidden=None, average=False): """Given some hidden state, calculate the probabilty of a given word""" word_buffer = " " word += ' ' probs = [] if not hidden: hidden = Variable(torch.zeros(rnn.n_layers, 1, rnn.hidden_size).cuda()) for i,...
0bdd0aa0435c1534064e856bad2005c662fb9fe0
3,604,093
def code_reassembly(structure): """ Recursively re-assemble the results of pyparsing analyzed tokens """ reassembled = [] for element in structure: if isinstance(element, pyparsing.ParseResults): reassembled.append(code_reassembly(element)) else: reassembl...
c9f14134d4bebefd559cf1fe4697098b8e163028
3,604,094
def fib_modified(a, b, n): """Computes the modified Fiboniacci-style function.""" for _ in range(2, n): a, b = b, a + b * b return b
103433c685d672019b42c1fd1a17a34bd3727764
3,604,095
def beamform_mvdr(Y, X_mask, N_mask, ban=False): """ Souden MVDR beamformer. Args: Y: CuPy array of shape (channel, time, frequency). X_mask: CuPy array of shape (time, frequency). N_mask: CuPy array of shape (time, frequency). ban: If True, use blind analytic normalization. ...
fc811383055ca8832df56769f899d3961463f0d0
3,604,096
def vit_deit_small_distilled_patch16_224(cfg): """ DeiT-small distilled model @ 224x224 from paper (https://arxiv.org/abs/2012.12877). ImageNet-1k weights from https://github.com/facebookresearch/deit. """ model = VisionTransformer(patch_size=cfg.CONFIG.MODEL.PATCH_SIZE, em...
eeccbe5127dda5ff94cdebb2afd6a976143f9904
3,604,097
def generate_class_object(object_name, attributes, template=None, bases=None, with_dump=False, dump_file=None): """ Generate class object. Args: object_name(string): object name attributes(list or dict): attribute template(string):...
96e5bb64ccfa5b5d9eb0d1cfbb5546a74f0f99dc
3,604,098
from numpy import asarray from numpy.testing import assert_equal def nan_equal(a,b): """Are two arrays containing nan identical, assuming nan == nan?""" a,b = asarray(a),asarray(b) try: assert_equal(a,b) except: return False return True
a5f3186e202e22d79f46781fe3c9e6a1936f4a6a
3,604,099
from pandas.core.sparse.array import ( SparseArray, _sparse_array_op, _wrap_result, _get_fill) def _arith_method_SPARSE_ARRAY(op, name, str_rep=None): """ Wrapper function for Series arithmetic operations, to avoid code duplication. """ def wrapper(self, other): if isinstance(other, np.nd...
ba045084dfecc89751e43eaea85fa53462fba98a
3,604,100
from typing import Callable def _embed(method: dict, link: Callable[[dict], str]) -> discord.Embed: """Generate an embed linking to a particular method.""" embed = discord.Embed(title=method["name"], url=link(method)) if "summary" in method: embed.description = method["summary"] return embed
f759589b7e6bac238ee6fe443d162303b90d967a
3,604,101
def check_thermodynamic_consistency(tab, spec, *XYf): """Thermodynamic consistency: relative error"""# ε = (∂E/∂V|_S - P)/P )""" XYf_DT = XYf[:] rho = XYf_DT[0] temp = XYf_DT[1] Pt = tab.get_table('P{s}_DT', spec)(*XYf_DT) dU_rho = tab.get_table('U{s}_DT', spec).dFx(*XYf_DT) dP_T = tab.get...
7dbf10d7a8a0e0742def3c09d20d5a5768b9dab4
3,604,102
def message(): """ Text message. :return: """ return "That's easy to fix, but I can't be bothered."
abff6c119536ffab9a4506d64afe067131e066a2
3,604,103
import yaml def represent_ordered_dict(dumper, data): """ Serializes ``OrderedDict`` to YAML by its proper order. Registering this function to ``yaml.SafeDumper`` enables using ``yaml.safe_dump`` with ``OrderedDict``s. """ return dumper.represent_mapping(yaml.resolver.BaseResolver.DEFAULT_MAPPING_...
f8c83dd3b3ecf94077b7b465334ffa84df7e16a8
3,604,104
def get_url_from_web(user_id): """ Get user info according to user id. If user domain is 100505,the url is just 100505+userid; If user domain is 103505 or 100306, we need to request once more to get his info If user type is enterprise or service, we just crawl their home page info :param: user i...
b79173db38d887c845b97f16a842e30ccf8d9acc
3,604,105
def make_adjacencyW(ids, distances, sigma): """Create adjacency matrix with a Gaussian kernel. Args: ids (numpy array): for each vertex the ids to its nnn linked vertices + first column of identity. distances (numpy array): for each data the l2 distances to its nnn linke...
da4048a6c2d188107778617f755af0d246de23aa
3,604,106
import types def channel_threshold( img: types.RGBImage, channel: int, thresh_min: int, thresh_max: int = 255, colorspace: int = None) -> types.BinaryImage: """Apply binary thresholding to an image channel.""" if colorspace is not None: img = cv2.cvtColor(img, colorspace) channel...
0058cde9db19914d79e98342423bf0cac42f97f4
3,604,107
def efficientnet_b0(in_size=(224, 224), **kwargs): """ EfficientNet-B0 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (224, 224) Spatial size of the expe...
7bc53321e3395de5db901be09407a07e269c9014
3,604,108
def BackwardBranch(): """(read-only) MOve back toward the source, return index of new active branch, or 0 if no more.""" return lib.Topology_Get_BackwardBranch()
8d2757f482310b2fbc067ba9546c91036c9b976c
3,604,109
def search_cycles(hints): """ Metoda poszukuje cykli w hintach np trzech pól {2,3,4}. Wtedy można poznać ktore elementy nie znajduja w pozostalych hintach. Warunkiem do sprawdzenia jest czy suma mnogosciowa n pol ma n roznych wartosci. Problemem jest jednak przejrzenie wszystkich wyborow elementow d...
599cf94a4e72757a3925786d74ace0dd39cadf43
3,604,110
def parse_datetime_input(datetime_input): """Takes a string containing date/time and intervals in ISO-8601 format Returns a start and end Python datetime.datetime object datetimes are None if the string is not a date/time datetime_end is None if the string is not a date/time interval """ # Dat...
8b0af9722d5c75ea7812000abd02ea37675f9fa3
3,604,111
def raizCuadrada(n): """ estima la raiz cuadrada en 20 intervalos """ raiz = n/2 # La estimacion inicial sera 1/2 de n for k in range(20): raiz = (1/2)*(raiz + (n / raiz)) return raiz
5b3a36dc50d5fa8921dfcbe2a24f7467201c5339
3,604,112
def get_all_idr(): """ Restituisce la lista delle identity request presenti sul db :return: IdentityRequest[] """ return IdentityRequest.objects.all().order_by('-timestamp_identification')
901f22ac11709d6c0633740e92bfbdb1d0f3f214
3,604,113
def get_dot_size(val, verbose=False): """ Get the size of the marker based on val :param val: the value to test :param verbose: more output :return: the size of the marker in pixels """ markersizes = [6, 9, 12, 15, 18] # there should be one less maxmakervals than markersizes and then we...
aa84c98a3cb78822dd02a9062f9f9a325907b310
3,604,114
def get_unique_merged_queryset(exclude_self_id, model_name, q, q_0, q_1, q_2, q_3, q_4): """Merges querysets in specific order and removes duplicates if user appears in a later queryset""" last_q = None if q_4 is not None: last_q = q_4 else: last_q = q result = apps.get_model('co...
28090a0189acf3c8971325df24a33e8eb597867c
3,604,115
def get_network_graph_spacy(document): """Convert the dependencies of the spacy document object to a networkX graph :param document: spacy parsed document object :return: networkX graph object and nodes list """ edges = [] nodes = [] # Ensure that every token is connected for s in doc...
684ee4c72627508e89ab0468d03596c7b15945e7
3,604,117
def preprocess_image(image_data, centroid, bbox_size, cropsize): """ Performs preproccessing on a single image for feeding into the network. :param image_data: raw image data as a bytestring :param centroid: the center of the bounding box to crop to, in pixel coordinates :param bbox_size: the side l...
533665759da91c5f3f7d423aa0c9e4ea44f47b57
3,604,118
def find_image_strings(strings): """ Given a list of strings that are potentially image file names, look for strings that actually look like image file names (based on extension). """ imageStrings = [] bIsImage = [False] * len(strings) for iString,f in enumerate(strings): bIsImage[iS...
27e3ea3818f10020ebc2ba012f794e8820d2854f
3,604,119
def tryAttrs(attrs, choices): """See if attrs has anything in choices; if so, return the first one encountered, otherwise return empty string.""" for choice in choices: if isReal(attrs[choice]): return attrs[choice] return ""
15839855e719adf7140fb42c7fba186ce16bd6f6
3,604,120
def solution_inference_resnet(img: np.ndarray) -> dict: """ Pipeline inference Args: img: image in uint8 RGB HWC format Returns: Dictionary with predicted class name """ global brick_classificator, resnet_color_classificator_brio if img is None: abort(409) partn...
223c39e4c7d1a4ce3e11a55cb2a15a2de4d6cef0
3,604,121
def generator(z_inp, is_training=False, getter=None, reuse=False): """ Generator architecture in tensorflow Generates data from the latent space Args: z_inp (tensor): variable in the latent space reuse (bool): sharing variables or not Returns: (tensor): last activation layer o...
05d416e620e710feb31a0a6e8ea590896b774b0c
3,604,122
def get_baremetal_offer(include_disabled=None,name=None,offer_id=None,zone=None,opts=None): """ Use this data source to access information about an existing resource. """ __args__ = dict() __args__['includeDisabled'] = include_disabled __args__['name'] = name __args__['offerId'] = offer_id...
4d49373d95a6357535239c0d8ba674b2fa7288f3
3,604,124
def rand_rho(d, sparse=False, density=None, dtype=complex): """Generate a random positive operator of size `d` with normally distributed entries and unit trace. See Also -------- rand_matrix, rand_herm, rand_pos, rand_uni """ return nmlz(rand_pos(d, sparse=sparse, density=density, dtype=dty...
9d9d20c18586f3aa3c1d2e168f4bde79fd809fe3
3,604,125
import six def _tuplify_version(version): """ Coerces the version string (if not None), to a version tuple. Ex. "1.7.0" becomes (1, 7, 0). """ if version is None: return version if isinstance(version, six.string_types): version = tuple(int(x) for x in version.split(".")) as...
97575c813ce585e7e928b129e67196dcece5db0a
3,604,126
from typing import Iterable from typing import Union from typing import List def get_git_root_paths(file_list: Iterable[str]) -> Union[str, List[str]]: """ Given a list of file paths, return a list of the root directories of the git working trees of the files. """ rslt = [] if isinstance(file_...
ec1bc46f629b12907564bdc577bbd60c9cb9d443
3,604,127
import math def is_hexagon(x): """ Checks if x is a hexagon number """ n = (1 + math.sqrt(8*x + 1))/4 return(n == round(n))
854aa38984d36cd956852a091318dd6edb0a06e1
3,604,128
import numpy def A_Mat(uv0, uv1, p00, p10, p01, p11, nPixels): """ Create a cooefficent A matrix. """ c1 = (uv1.u - uv0.u) * (uv1.v - uv0.v) coeffs = numpy.zeros((1, nPixels)) coeffs[0, p00] = c1 coeffs[0, p10] = -c1 coeffs[0, p01] = -c1 coeffs[0, p11] = c1 return coeffs
b3e9faecdc432e17c5da0ecf085f5e1c0e2b16a9
3,604,129
from typing import List import bisect def binary_search(elements: List[int], value: int) -> int: """Returns the index of the element closest to value. Args: elements (List): A sorted list. """ if not elements: return -1 closest_index = bisect.bisect_left(elements, value, 0, len(ele...
1e1cb3ebe1b897e480aa93747108365f0e8326fd
3,604,131
def kwargs_log_scale(unique_val, mode="equidistant", base=None): """Return arguments to set log_scale as one would wish. Parameters ---------- unique_val : np.array All unique values that will be plotted on the axis that should be put in log scale. axis : {"x","y"} Axis for which t...
2bf0946e587512973bccb62f3f0c65f684bc7116
3,604,132
import uuid def create_record_id(): """Create record id. :return: Record id string. :rtype: str """ return str(uuid.uuid4())
a582d8e0823061621e250f257ed4877032792fdc
3,604,133
def postprocess(scores, classes, bboxes, iou_threshold=0.3, score_threshold=0.5): """ Post-process the detection results. Non-maximum suppression. """ n = len(scores) det_num = 0 det_classes = [] det_scores = [] det_bboxes = [] idx = np.argsort(scores)[::-1] sorted_scores =...
4073e358687fca7e0a1bc99ab234b7a8ace1f825
3,604,134
def getGeneralDependency(dep): """ :type dep: basestring | DepType :rtype: DepType """ if dep in __H_GENERAL_DEPENDENCIES: return __H_GENERAL_DEPENDENCIES[dep] elif isinstance(dep, DepType): return dep else: return DepType.fromString(dep)
79d7d37f0396ee0d8ddb5b7842541364bd76cc20
3,604,135
import six def _get_key(args, kwargs, remove_callback): """Calculate the cache key, using weak references where possible.""" # Use tuples, because lists are not hashable. weak_args = tuple(_try_weakref(arg, remove_callback) for arg in args) # Use a tuple of (key, values) pairs, because dict is not has...
5f85861395f2ff72e092b0a706ea0199a6bb6325
3,604,137
from typing import Dict from typing import List from typing import Any def get_geometries(handler: h5py.File) -> Dict[str, List[Any]]: """Return an array of smiles in the HDF5.""" group = handler["ligand"] smiles = group["index"]["ligand"][()] pdb = PDBContainer.from_hdf5(group) molecules = pdb.to...
1a3d847bf88454de036f152f77088533d5a0e232
3,604,138
from typing import Type from typing import Callable from typing import Any def is_type(tipe: Type) -> Callable[[Any], bool]: """ :param tipe: A Type :return: A predicate that checks if an object is an instance of that Type """ def predicate(value: Any) -> bool: """ :param value: An...
2b4be636675216c810f9e14f70fe8a5647552e3f
3,604,139
def select_options(element, swap=None, text_exclude=None): """Return dropdown option in key value pair Args: element : An select element swap : list of swapped values text_exclude : immutable object tuple of values to exclude from result Returns: return dict of...
f46d5b05db72ceaa51b1dc4bb3dd82f6516c3bce
3,604,140
def compute_distance_matrix(x1, x2=None): """ Computes the distance matrix between x1 and x2. If x2 isn't given, it will set x2 as x1 and compute the inner distance matrix of x1. Parameters ---------- x1: numpy array like object with one feature where the rows designate samples. ...
6497799847f61d5d101559d2915dd921767f8888
3,604,143
def daily_data(): """ 日线行情 URL:https://tushare.pro/document/2?doc_id=27 """ df = pro.query('daily', ts_code='000001.SZ', start_date='20180701', end_date='20180718') return df
a08eb8657a7c7557a2b9c1f1b6521430837815ba
3,604,144
import re import keyword def get_docx_variables( text:str )->set: """ Given the string from a docx file with fairly simple code), returns a list of everything that looks like a jinja variable in the string. Limits: some attributes and methods might not be designed to be directly assigned in docassemble. Me...
214f2b1b5a8eef902c48e630be3e3f919083e775
3,604,146
def get_control_frame(window, mqtt_sender): """ Constructs and returns a frame on the given window, where the frame has Button objects to exit this program and/or the robot's program (via MQTT). :type window: ttk.Frame | ttk.Toplevel :type mqtt_sender: com.MqttClient """ # Const...
3eca7c6cb21458a2c26678755b4c53dc30f3ee67
3,604,147
def _CheckType(rval, arg, errfmt, span_id): """Shared between NewVar and Readonly.""" if arg.a and rval and rval.tag != value_e.MaybeStrArray: errfmt.Print("Got -a but RHS isn't an array", span_id=span_id) return False if arg.A and rval and rval.tag != value_e.AssocArray: errfmt.Print("Got -A but RHS ...
5ab6ceca86423b961eb31908d913a8c03826646e
3,604,148
import signal def downsample_utterance(features, seglist, n): """ Return the downsampled matrix with each row an embedding for a segment in the seglist. """ embeddings = [] for i, j in seglist: y = features[i:j+1, :].T y_new = signal.resample(y, n, axis=1).flatten("C") ...
b25ec58edaec4e9d8ecd6dc237eb39a2b5d57f4c
3,604,149
def initialize_direct(obj_store_config, manager_id, check_db=False): """ Given a fully-prepared configuration, initialize the manager and set the id. :param obj_store_config: dict, fully ready configuration to use :param manager_id: :param check_db: :return: """ global manager_singleton...
5e25a45d3dbe1c05f664b81d48822774f63b38aa
3,604,151
def get_analysis_list(uid): """get all analysis with user_id 'uid' as a list""" session = tables.get_session() if session is None: return None try: ip_table = IpAddrs() collection_table = CollectionTable() ips = ip_table.get_ips_by_uid(uid, session) res = [] ...
3ed94d7f7509e5c39c7a51763face107d6d7697f
3,604,152
import collections def _get_epoch_data(valid_loss_mean_val: float=3) -> EpochData: """Return testing epoch data.""" epoch_data = collections.OrderedDict([ ('train', collections.OrderedDict([ ('accuracy', 1), ('loss', collections.OrderedDict([('mean', (3, 4))])), ])), ...
655206741628fd16d2b896c4f95da6d0553a15dd
3,604,153
def em_step(dataset, lmm): """Complete one expectation and one maximization step. Parameters ---------- dataset : List of tuples; observations and design matrices. lmm : A linear mixed model object. Returns ------- A 3-tuple; the fixed effects, random effects covariance, and noise ...
6236062faba42d283ed3fdf68a363c565acc3328
3,604,155
def new_measure_get_meas_measure(data: dict) -> MeasureGetMeasMeasure: """Create GetMeasMeasure from json.""" return MeasureGetMeasMeasure( value=int_or_raise(data.get("value")), type=new_measure_type(data.get("type")), unit=int_or_raise(data.get("unit")), )
1e0c87dd99157d50dda17c0093d7c1ac385d42c3
3,604,156
def nexttwin(zahl): """Return the smallest prime twin following a given number.""" print(_("=== Find the next prime twin ===")) answer = "" while answer != "q": print(_("ENTER, a number or 'q'"), end=": ") answer = lies() if answer == "q": break try: ...
8e220815a9568b73b121fca1b13c8992d577e8d1
3,604,157
import requests def list_connect_admins(group_name): """ Return list of admins of connect group Return list of nested dictionaries with state, user_name, and state_set_by """ query = {"token": slate_api_token} group_members = requests.get( slate_api_endpoint + "/v1alpha1/groups...
168ee581fa16d2812a9d1c801fb30a63e70d9352
3,604,158
def MSI(record): """ "Maximise Severity if Invalid": propagate an alarm state on the linked record only if the alarm severity is `INVALID_ALARM`. When propagated, the alarm status will become `LINK_ALARM`. Example (Python source) ----------------------- `my_record.INP = MSI(other_record)` ...
872b13eafe3dd76a962f24d2f3108990b5fda40e
3,604,159
def _get_compound_type_from_kind(kind): """Map compound kinds from Doxygen XML to internal class types.""" if kind == 'file': return File elif kind == 'dir': return Directory elif kind == 'group': return Group elif kind == 'namespace': return Namespace elif kind i...
451ee299a4f9fca3e7f9be0c0b764412ba0e8cd8
3,604,161
import requests def hp_update_firmware(url=None, dry_run=False): """ Apply HP firmware updates :param url: Full URL to the package containing firmware files :param dry_run: If firmware updates should be applied when found """ try: r = requests.get(url, stream=True, verify=False) e...
1ea4aa18d905b60b231a3c898bfb2409eae64903
3,604,162
def delete_group(token, group_id, customerid=None): """ Delete a contact group for the specified account Returns all the data in a dictionary format from the original JSON that is gathered from NodePing :param token: The NodePing API token for the account :type token: str :param group_id: The ...
51ff79b0348298d2bfc3bcf4e8c661d95bfde671
3,604,163
def close_connection(exception): """ Close any existing connection to the database. :param exception: An exception that is triggering the application teardown. """ database = getattr(g, "_database", None) if database is not None: database.close() return None
1ed0e2d74a8ac8fe1d05db7e7ce3929d17992f64
3,604,164
def draw_guess_buttons(colors): """ Draw guess buttons that input each a particular color to a guess. """ buttons = [] y = divider + SQUARESIZE//2 radius = pegsize pygame.draw.rect(screen, DARKEST_GRAY, (0, height-SQUARESIZE*2, width, SQUARESIZE*2)) for c in range(...
1d6b2a726cf108d01347bed5ddfb8d8e6ec7fc9c
3,604,165
import json def voter_guides_to_follow_retrieve_view(request): # voterGuidesToFollowRetrieve """ Retrieve a list of voter_guides that a voter might want to follow (voterGuidesToFollow) :param request: :return: """ voter_device_id = get_voter_device_id(request) # We standardize how we take in...
5737b7f75439d4837d34b51f1aea422a4dc4ce38
3,604,166
def cfg(): """Returns a Config object loaded with test_profile""" cfg = Config() cfg.source_config_file(cfg_file) return cfg
7da4f7a11445bbf3aa6963ad157b073745c62732
3,604,167
def setup_block_and_grid(problem_size, grid_div, params, block_size_names=None): """compute problem size, thread block and grid dimensions for this kernel""" threads = get_thread_block_dimensions(params, block_size_names) current_problem_size = get_problem_size(problem_size, params) grid = get_grid_dime...
1f19bc211b6f1d2dbaf454386468618bc2b98572
3,604,168
def update_token( user_id : str, token : str ): """ Updates a user's API token in the database Parameters: user_id (str): unique identification for the user token (str): authentication for API calls Returns: On Success: Boolean: True On Fail: Boolean: False """ ...
21900af6b8219913683064a3e8aefb263a6bd2dc
3,604,169
def _lam_hawkes_lite( ts, eval_ts, mu_kernel, phi_kernel, t_start=0.0, **kwargs): """ Intensity of Hawkes process given time series and parameters. Memory-lite version. CPU-hungry, could be improved with numba. Uses assignment so may need to be altered fo...
491158080f5ce9642536b2c6cae037c3889ff4bb
3,604,170
def dropin(name, *, contents): """ :param the name of the drop-in. This must be suffixed with ".conf". :param contents: the contents of the drop-in. : return Container Linux systemd drop-in object """ return { 'name': name, 'contents': cleanup_contents(contents) }
49f080c1849584ba8218e8baa9d3f15d2ffb48f2
3,604,171
def unique_id_map(slug): """ :param slug: A slug that specifies the type of object that we want to generate ID for. :return: Tuple of UniqueIdGenerator instance and an optional subclass of UniqueId collection. """ # turn slug into id name = '{}_id'.format(slug.replace('-', '_').lower()) retu...
37630df8824c2991d7dc744a47c74a7dd4bd32cf
3,604,172
def visible_limits(artists, axis): """ Determines the data limits for the data in a set of artists. Ignores non-visible artists Assumes each artist as a get_data method which returns a tuple of x,y Returns a tuple of min, max for the requested axis, or None if no data present Parameters ...
c820e4b46a4ce1ac8f30ca6468e0a46b66d6996a
3,604,173
def rand_sparse_ndarray(shape, stype, density=None, dtype=None, distribution=None, data_init=None, rsp_indices=None, modifier_func=None, shuffle_csr_indices=False): """Generate a random sparse ndarray. Returns the ndarray, value(np) and indices(np) Parameters ...
d6d064a24bd706c155a1d68a540ba1b56fbd01f3
3,604,174
def rand_simple_polygon(vertices): """ That's an unreliable hack to generate a random simple polygon. Beware, sometimes it is stuck in an infinite loop. """ poly = Polygon_2() while vertices > 0: x = randint(-5, 5) * 10 y = randint(-5, 5) * 10 poly.push_back(Point_2(...
a321c23ca7cc69d11ce1f75e8c7f26db00601879
3,604,175
def strip_constants(df, indices): """Remove columns from DF that are constant input factors. Parameters ---------- * df : DataFrame, of input parameters used in model run(s). * indices : list, of constant input factor index positions. Returns ---------- * copy of `df` modified to exclu...
5a68d9beaa39cb2651ccd995af20d25165ccb03e
3,604,176
def _GetBucketName(master_name): """Converts shortened master name to full master name. Buildbucket uses full master name (master.tryserver.chromium.linux) as bucket name, while Findit uses shortened master name (tryserver.chromium.linux). """ buildbot_prefix = 'master.' if (master_name.startswith(buildbot...
375e052db9da02e62c4fcd9f0ef28d0302aaebe6
3,604,177
def _getPushshiftData_(before, after, kind='submission', subreddit='de', size=1000): """ Fetches reddit data via the pushshift api: between "before" and "after" given as linux timestamps of "kind" submission or comment from "subreddit" of size "size" (maximum 1000) """ if...
58bc96a171887e8e672233e288b49d4873a5b27c
3,604,178
def prioritized_texts(): """ Retrieves all of the political statements from the database, prioritizes them with the manifesto model and returns at most as many texts given in the GET parameter `n`, ordered by their uncertainty. :return: { 'data': [ {'text_id': 1, 'label': 'left'}, ...
2a0eea5907207108aff83ef904ce64c405e21091
3,604,179
def null_space(M, k, k_skip=1, eigen_solver='arpack', tol=1E-6, max_iter=100, random_state=None): """ Find the null space of a matrix M. Parameters ---------- M : {array, matrix, sparse matrix, LinearOperator} Input covariance matrix: should be symmetric positive semi-definite...
0f05d8943ac8d77b4c5087de81b15159c98c5cb3
3,604,180
def get_view_content(view): """ Returns view content as string. """ return utils.execute_in_sublime_main_thread(lambda: view.substr(sublime.Region(0, view.size())))
18f7accd4efa6fc58e8f9df83776703006bb99e2
3,604,181
def is_liked(bvid: str = None, aid: int = None, verify: utils.Verify = None): """ 是否点赞视频 :param aid: :param bvid: :param verify: :return: """ if not (aid or bvid): raise exceptions.NoIdException if verify is None: verify = utils.Verify() if not verify.has_sess(): ...
e53c80af1df3448555701193327a8e9b669f7497
3,604,182
def namedtuples(stmt, from_iter = chain.from_iterable, map = starmap): """ Alternative to the .rows() execution method. Use:: >>> from postgresql.types.namedtuple import namedtuples >>> ps = namedtuples(db.prepare(...)) >>> for nt in ps(...): ... nt.a_column_name This effectively selects the execution ...
273de9c7aae9ff1060ec58bd41e8bc13674c5414
3,604,183
def review_request_dropdown_action_hooks(context): """Displays all registered action hooks for review requests.""" return action_hooks(context, ReviewRequestDropdownActionHook, "actions", "extensions/action_dropdown.html")
3b7be826101a3eb7a820fbde64250a56d27461bd
3,604,184
from typing import Type def create_singledispatch_function_callback(ctx: FunctionContext) -> Type: """Called for functools.singledispatch""" func_type = get_proper_type(get_first_arg(ctx.arg_types)) if isinstance(func_type, CallableType): if len(func_type.arg_kinds) < 1: fail( ...
a8fb883383804ee7983bf929e1b7b4eea6dac47e
3,604,186