code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def __init__(self, t=None): <NEW_LINE> <INDENT> self._t = t <NEW_LINE> if t is None: <NEW_LINE> <INDENT> self._t = lambda x: x
If a type t is provided, the value from the config will be converted using t as the constructor. If t is not provided, the (possibly eval'd) value will be returned 'as-is' with no conversion.
625941da57b8e32f5248374e
def log_result(self, label, content): <NEW_LINE> <INDENT> self.results.append((label, content)) <NEW_LINE> if self.verbose: print('* ', label, content, file = sys.stderr)
Log results with prefix ' ' The (label, content) is added to self.results array to be printed in performance.txt
625941da21bff66bcd684c01
def conv_backward_naive(dout, cache): <NEW_LINE> <INDENT> dx, dw, db = None, None, None <NEW_LINE> x, w, b, conv_param = cache <NEW_LINE> N, C, H, W = x.shape <NEW_LINE> F, C, HH, WW = w.shape <NEW_LINE> stride = conv_param.get('stride', 1) <NEW_LINE> pad = conv_param.get('pad', 0) <NEW_LINE> H_out = int(1 + (H + 2 * p...
A naive implementation of the backward pass for a convolutional layer. Inputs: - dout: Upstream derivatives. - cache: A tuple of (x, w, b, conv_param) as in conv_forward_naive Returns a tuple of: - dx: Gradient with respect to x - dw: Gradient with respect to w - db: Gradient with respect to b
625941dad8ef3951e32437ef
def loss(self, X, y=None, reg=0.0): <NEW_LINE> <INDENT> W1, b1 = self.params['W1'], self.params['b1'] <NEW_LINE> W2, b2 = self.params['W2'], self.params['b2'] <NEW_LINE> N, D = X.shape <NEW_LINE> scores = None <NEW_LINE> S1 = X.dot(W1) + b1 <NEW_LINE> Z1 = np.maximum(0, S1) <NEW_LINE> S2 = Z1.dot(W2) + b2 <NEW_LINE> sc...
Compute the loss and gradients for a two layer fully connected neural network. Inputs: - X: Input data of shape (N, D). Each X[i] is a training sample. - y: Vector of training labels. y[i] is the label for X[i], and each y[i] is an integer in the range 0 <= y[i] < C. This parameter is optional; if it is not passed...
625941dabde94217f36830a0
def packData(self, *args): <NEW_LINE> <INDENT> output_str = b';'.join(args) <NEW_LINE> return output_str
Takes a set of arguments, and concatenates them in a string that
625941dabe8e80087fb20ef1
def connect(self): <NEW_LINE> <INDENT> s = socket.socket() <NEW_LINE> s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) <NEW_LINE> s.bind(('', self.port)) <NEW_LINE> s.listen(2) <NEW_LINE> conn, adr = s.accept() <NEW_LINE> self.addres = adr[0] <NEW_LINE> return conn
Создание соединения
625941da66673b3332b92343
def load_file(self, file_path): <NEW_LINE> <INDENT> self.nvim.current.buffer[:] = [l.strip("\n") for l in self.files[file_path]]
Loads the given file into the current buffer.
625941da6fece00bbac2d9f3
def validate(self, data): <NEW_LINE> <INDENT> user = self.context["request"].user <NEW_LINE> adv_count = len(Advertisement.objects.select_related('creator').filter(creator=user, status='OPEN')) <NEW_LINE> if adv_count > 10: <NEW_LINE> <INDENT> raise serializers.ValidationError('Превышено количество открытых объявлений'...
Метод для валидации. Вызывается при создании и обновлении.
625941da3617ad0b5ed681a8
def create_vdisk(self, size: int, user, center, group=None, quota=None, remarks=''): <NEW_LINE> <INDENT> if size <= 0: <NEW_LINE> <INDENT> raise errors.VdiskInvalidParams(msg='创建的硬盘大小必须大于0') <NEW_LINE> <DEDENT> if quota: <NEW_LINE> <INDENT> quota = self.schedule_by_quota(size=size, user=user, quota=quota) <NEW_LINE> <D...
创建一个虚拟云硬盘 备注:group和quota参数至少需要一个,优先使用quota参数; 当只有group参数时,通过group获取quota :param center: 分中心对象或id :param group: 宿主机组对象或id :param quota: 硬盘所属的云硬盘CEPH存储池对象或id :param size: 硬盘的容量大小 :param user: 创建硬盘的用户 :param remarks: 备注信息 :return: Vdisk() # success :raises: VdiskError
625941da7047854f462a16b8
def __init__(self, animal_factory=None): <NEW_LINE> <INDENT> self.pet_factory = animal_factory
pet_factory is the abstract factory.
625941da31939e2706e4d118
def testQgsMarkerLineSymbolLayer(self): <NEW_LINE> <INDENT> mTestName = 'QgsMarkerLineSymbolLayer' <NEW_LINE> mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) <NEW_LINE> mDoc = QDomDocument(mTestName) <NEW_LINE> mFile = QFile(mFilePath) <NEW_LINE> mFile.open(QIODevice.Read...
Create a new style from a .sld file and match test
625941da4e4d5625662d4687
def process_auth_provider_login(self, code): <NEW_LINE> <INDENT> raise NotImplementedError
Is doing everything needed to validate the auth code, fetching an access token and user-infos. This function should return the access_token and a userdata object.
625941da8a43f66fc4b54314
def _ra_hourly(lat, lon, doy, time_mid, method='asce'): <NEW_LINE> <INDENT> omega = _omega(_solar_time_rad(lon, time_mid, _seasonal_correction(doy))) <NEW_LINE> delta = _delta(doy, method) <NEW_LINE> omegas = _omega_sunset(lat, delta) <NEW_LINE> omega1 = np.clip(omega - (math.pi / 24), -omegas, omegas) <NEW_LINE> omega...
Hourly extraterrestrial radiation (Eq. 48) Parameters ---------- lat : scalar or array_like of shape(M, ) Latitude [radians]. lon : scalar or array_like of shape(M, ) Longitude [radians]. doy : scalar or array_like of shape(M, ) Day of year. time_mid : scalar or array_like of shape(M, ) UTC time at mid...
625941da8a349b6b435e8425
def splitIter(num_iter, nproc): <NEW_LINE> <INDENT> arr_iter = (onp.zeros(nproc) + num_iter // nproc).astype('int') <NEW_LINE> for i in range(num_iter % nproc): <NEW_LINE> <INDENT> arr_iter[i] += 1 <NEW_LINE> <DEDENT> return arr_iter
Split `num_iter` iterations into `nproc` chunks for multithreading
625941da7c178a314d6ef715
def get_distinct_elements(items, key=None): <NEW_LINE> <INDENT> seen = set() <NEW_LINE> for item in items: <NEW_LINE> <INDENT> val = item if key is None else key(item) <NEW_LINE> if val not in seen: <NEW_LINE> <INDENT> yield item <NEW_LINE> seen.add(val)
去除序列中的重复元素,使得剩下的元素仍然保持顺序不变,对于不可哈希的对象,需要指定 key ,说明去重元素 :param: * items: (list) 需要去重的列表 * key: (hook函数) 指定一个函数,用来将序列中的元素转换成可哈希类型 :return: * result: (generator) 去重后的结果的生成器 举例如下:: print('--- remove_duplicate_elements demo---') list_demo = remove_duplicate_elements([1, 5, 2, 1, 9, 1, 5, 10]) prin...
625941da293b9510aa2c3545
def find_max_number(stack_a, stack_b, limit): <NEW_LINE> <INDENT> s_a = sum_list(stack_a, limit) <NEW_LINE> s_b = sum_list(stack_b, limit) <NEW_LINE> max_num = len(s_a) <NEW_LINE> i = 0 <NEW_LINE> while (i < len(s_b)): <NEW_LINE> <INDENT> if len(s_a) and is_exceed_limit(s_a[-1] + s_b[i]): <NEW_LINE> <INDENT> s_a.pop() ...
The two stacks initially look like this: stack_a: 4 2 4 6 1 stack_b: 2 1 8 5 Add each number in the stack until the sum of number exceeds the limit. If the number exceeds the limit, then remove the rest of numbers in the stack including the number on the current index. If sum of the last value from stack A and the val...
625941dadd821e528d63b459
def get_total_memory_usage(self, dev): <NEW_LINE> <INDENT> self._initialize_physical_devices() <NEW_LINE> self.ensure_initialized() <NEW_LINE> return pywrap_tfe.TFE_GetTotalMemoryUsage(self._context_handle, dev)
Returns total memory usage in bytes for the current device.
625941da56b00c62f0f1490d
def pop_choice(self, key, choices): <NEW_LINE> <INDENT> value = self.pop(key, self.DEFAULT) <NEW_LINE> if value not in choices: <NEW_LINE> <INDENT> key_str = self.history + key <NEW_LINE> message = '%s not in acceptable choices for %s: %s' % (value, key_str, str(choices)) <NEW_LINE> raise ConfigurationError(message) <N...
Gets the value of ``key`` in the ``params`` dictionary, ensuring that the value is one of the given choices. Note that this `pops` the key from params, modifying the dictionary, consistent with how parameters are processed in this codebase. Params: key: Key to get the value from in the param dictionary ...
625941da5fdd1c0f98dc04e6
def fill_in_email_address(self, purchaser_details): <NEW_LINE> <INDENT> self.selenium.wait_for_element_visible(self.locator.register_locators.INPUT_email) <NEW_LINE> self.selenium.send_keys(self.locator.register_locators.INPUT_email, purchaser_details['pEmail'])
Fill in email adress field
625941da24f1403a92600e16
def dr(msg): <NEW_LINE> <INDENT> msgbin = hex2bin(msg) <NEW_LINE> dr = bin2int(msgbin[8:13]) <NEW_LINE> text = None <NEW_LINE> if dr == 0: <NEW_LINE> <INDENT> text = "no downlink request" <NEW_LINE> <DEDENT> elif dr == 1: <NEW_LINE> <INDENT> text = "request to send Comm-B message" <NEW_LINE> <DEDENT> elif dr == 4: <NEW...
Decode downlink request for DF 4, 5, 20, and 21. Args: msg (str): 14 hexdigits string Returns: int, str: downlink request, description
625941dab57a9660fec33b39
def profile_list(): <NEW_LINE> <INDENT> conf = api.Config() <NEW_LINE> for profile in conf.profile_sections(): <NEW_LINE> <INDENT> data = conf._profile_general(profile) <NEW_LINE> try: <NEW_LINE> <INDENT> _print_profile(profile, data) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> print( log.format( f"Invalid...
Show conducto log-in profiles recognized on this computer.
625941da55399d3f05588967
def get_user_roles(user, normalized=False, unrestricted=False): <NEW_LINE> <INDENT> roles = set() <NEW_LINE> if user.is_anonymous: <NEW_LINE> <INDENT> roles.add(get_anonymous_user_role()) <NEW_LINE> return roles <NEW_LINE> <DEDENT> if unrestricted: <NEW_LINE> <INDENT> query_set = user.roles.unrestricted() <NEW_LINE> <D...
:param user: :param normalized: if true parent roles also me extracted :param unrestricted: :return:
625941da7d847024c06be571
def remove_callback(self, callback: Callable[[EventLogEntry], None]): <NEW_LINE> <INDENT> callback = check.callable_param(callback, "callback") <NEW_LINE> with self._callback_fn_list_lock: <NEW_LINE> <INDENT> self._callback_fn_list = [ callback_with_cursor for callback_with_cursor in self._callback_fn_list if callback_...
Observer has stopped watching this run; Remove a callback from the list of callbacks to execute on new EventLogEntrys Also kill thread if no callbacks remaining (i.e. no Observers are watching this run_id) Args: callback (Callable[[EventLogEntry], None]): callback to remove from list of callbacks
625941dacc40096d61595c02
def unpickle_from_file(file_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(sys.path[0] + os.sep + file_name, 'rb') as read_from_file: <NEW_LINE> <INDENT> return pickle.load(read_from_file) <NEW_LINE> <DEDENT> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> return None
desearialize an object from file
625941daf7d966606f6aa2b9
def _delete_dummy_intf_rtr(self, tenant_id, tenant_name, rtr_id): <NEW_LINE> <INDENT> net_id, subnet_id, rtr_id = self.get_dummy_router_net(tenant_id) <NEW_LINE> ret = self.delete_os_dummy_rtr_nwk(rtr_id, net_id, subnet_id) <NEW_LINE> self.delete_network_db(net_id) <NEW_LINE> return ret
Function to delete a dummy interface of a router
625941da50812a4eaa59c5d2
def get(self, key): <NEW_LINE> <INDENT> key_to_get = self.hash(key) <NEW_LINE> sorted = self.bucket_list[key_to_get].items() <NEW_LINE> for k, v in sorted: <NEW_LINE> <INDENT> if k == key: <NEW_LINE> <INDENT> return v <NEW_LINE> <DEDENT> <DEDENT> raise TypeError("That key cannot be found in the hash. Bummer.")
returns the value stored with the given key
625941dac432627299f04efa
def detect(self, img, max_detections=10000): <NEW_LINE> <INDENT> return self._lib.Detect(self._inner_detector, img, max_detections)
Detect faces on given image Args: img: image to detect max_detections: Maximum detection to output, optional Returns: numpy list of detections ([x, y, w, h, score]*#detections)
625941dab5575c28eb68e2b4
def _setprogress(self, new_progress): <NEW_LINE> <INDENT> self._task.lazy_heartbeat(new_progress, self._progress) <NEW_LINE> self._progress = new_progress
posts progres update to our task, lazily @param new_progress progress dict of {'name':$NANME 'progress'$INT_PERCENT }
625941da4e696a04525c96fe
def payload_values_should_match(self, claims): <NEW_LINE> <INDENT> for x in payload: <NEW_LINE> <INDENT> expect(claims[x]).to_equal(payload[x])
Check values
625941da31939e2706e4d119
def test_minimalcuts(self): <NEW_LINE> <INDENT> cuts = { 1: { 'simple': set([frozenset([self.alim[0]]), frozenset([self.motors[0]])]), 'series-parallel': set(), 'parallel-series': set(), 'complex': set(), 'voter': set([frozenset([self.voter])]), }, 2: { 'simple': set([frozenset([self.alim[0]]), frozenset([self.motors[0...
Check for minimal cut of orders 1 and 2.
625941da8a43f66fc4b54315
def _release_version(): <NEW_LINE> <INDENT> with io.open(os.path.join(SETUP_DIRNAME, 'saltpylint', 'version.py'), encoding='utf-8') as fh_: <NEW_LINE> <INDENT> exec_locals = {} <NEW_LINE> exec_globals = {} <NEW_LINE> contents = fh_.read() <NEW_LINE> if not isinstance(contents, str): <NEW_LINE> <INDENT> contents = conte...
Returns release version
625941da004d5f362079a5e4
def getLeftEncoder(self): <NEW_LINE> <INDENT> return _AriaPy.ArRobot_getLeftEncoder(self)
getLeftEncoder(self) -> long
625941da460517430c394432
def trainAndTune(self, trainingData, trainingLabels, validationData, validationLabels, kgrid): <NEW_LINE> <INDENT> self.validationLabels = validationLabels <NEW_LINE> self.validationData = validationData <NEW_LINE> self.kgrid = kgrid <NEW_LINE> prob = util.Counter() <NEW_LINE> for label in trainingLabels: <NEW_LINE> <I...
Trains the classifier by collecting counts over the training data, and stores the Laplace smoothed estimates so that they can be used to classify. Evaluate each value of k in kgrid to choose the smoothing parameter that gives the best accuracy on the held-out validationData. trainingData and validationData are lists ...
625941da4f6381625f114cee
def upload_template_and_reload(name, reload=True): <NEW_LINE> <INDENT> template = get_templates()[name] <NEW_LINE> local_path = template["local_path"] <NEW_LINE> if not os.path.exists(local_path): <NEW_LINE> <INDENT> project_root = os.path.dirname(os.path.abspath(__file__)) <NEW_LINE> local_path = os.path.join(project_...
Uploads a template only if it has changed, and if so, reload a related service.
625941da94891a1f4081bd5d
def _rindex(mylist: Sequence[T], x: T) -> int: <NEW_LINE> <INDENT> return len(mylist) - mylist[::-1].index(x) - 1
Index of the last occurrence of x in the sequence.
625941dabde94217f36830a1
def get_cache(backend, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if '://' in backend: <NEW_LINE> <INDENT> backend, location, params = parse_backend_uri(backend) <NEW_LINE> if backend in BACKENDS: <NEW_LINE> <INDENT> backend = 'djangocg.core.cache.backends.%s' % BACKENDS[backend] <NEW_LINE> <DEDENT> params...
Function to load a cache backend dynamically. This is flexible by design to allow different use cases: To load a backend with the old URI-based notation:: cache = get_cache('locmem://') To load a backend that is pre-defined in the settings:: cache = get_cache('default') To load a backend with its dotted im...
625941dab5575c28eb68e2b5
def test_compression_header_append2(self): <NEW_LINE> <INDENT> with fits.open(self.data('comp.fits')) as hdul: <NEW_LINE> <INDENT> header = hdul[1].header <NEW_LINE> while (len(header) < 1000): <NEW_LINE> <INDENT> header.append() <NEW_LINE> <DEDENT> header.append(("Q1_OSAVG", 1, "[adu] quadrant 1 overscan mean")) <NEW_...
Regression test for issue https://github.com/astropy/astropy/issues/5827
625941da1f037a2d8b9464b0
def privmsg(self, source, target, message): <NEW_LINE> <INDENT> if target[0] == "#": <NEW_LINE> <INDENT> print("<%s> %s" % (source[0], message)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("-%s- %s" % (source[0], message))
privmsg Event This event is triggered by the ``IRC`` Protocol Component for each message we receieve from the server.
625941dabe8e80087fb20ef2
def onChanged(self, obj, prop): <NEW_LINE> <INDENT> pass
Run this method when a property is changed. Override this method to handle the behavior of the object depending on changes that occur to its properties. By default it does nothing. Parameters ---------- obj : the scripted object. This commonly may be of types `Part::Part2DObjectPython`, `Part::FeaturePython`...
625941da26238365f5f0f124
def test_insert_element_out_of_range(self): <NEW_LINE> <INDENT> L=LinkedList() <NEW_LINE> insert(L,"hola",1) <NEW_LINE> self.assertEqual(L.head,None)
-- Inserta un elemento fuera de rango en una lista vacia y verificar su valor
625941da8c3a87329515866f
def encoder(enc_input, attn_bias, n_layer, n_head, d_key, d_value, d_model, d_inner_hid, prepostprocess_dropout, attention_dropout, relu_dropout, preprocess_cmd="n", postprocess_cmd="da"): <NEW_LINE> <INDENT> for i in range(n_layer): <NEW_LINE> <INDENT> enc_output = encoder_layer( enc_input, attn_bias, n_head, d_key, d...
The encoder is composed of a stack of identical layers returned by calling encoder_layer.
625941da004d5f362079a5e5
def reopen(self, user, repo, issue_id): <NEW_LINE> <INDENT> self._post('/'.join(['issues', 'reopen', user, repo, str(issue_id)]))
Reopen an issue.
625941dad7e4931a7ee9e1d1
def lock_parameter(self, name, par, lock=True): <NEW_LINE> <INDENT> name = self.roi.get_source_by_name(name).name <NEW_LINE> lck_params = self._lck_params.setdefault(name, []) <NEW_LINE> if lock: <NEW_LINE> <INDENT> self.free_parameter(name, par, False) <NEW_LINE> if not par in lck_params: <NEW_LINE> <INDENT> lck_param...
Set parameter to locked/unlocked state. A locked parameter will be ignored when running methods that free/fix sources or parameters. Parameters ---------- name : str Source name. par : str Parameter name. lock : bool Set parameter to locked (True) or unlocked (False) state.
625941daac7a0e7691ed437a
@task <NEW_LINE> def deploy(branch=None): <NEW_LINE> <INDENT> stage = shell.get_stage() <NEW_LINE> deployer_user = shell.get_user() <NEW_LINE> branch = branch or resolve_deployment_branch(stage) <NEW_LINE> commit = git.last_commit(remote=False, short=True) <NEW_LINE> notif.send(notification_types.DEPLOYMENT_STARTED, { ...
Deploy to remote source.
625941dacad5886f8bd2728b
def apply(self, args, env): <NEW_LINE> <INDENT> if not scheme_listp(args): <NEW_LINE> <INDENT> raise SchemeError('arguments are not in a list: {0}'.format(args)) <NEW_LINE> <DEDENT> python_args = [] <NEW_LINE> while args is not nil: <NEW_LINE> <INDENT> python_args.append(args.first) <NEW_LINE> args = args.second <NEW_L...
Apply SELF to ARGS in ENV, where ARGS is a Scheme list. >>> env = create_global_frame() >>> plus = env.bindings['+'] >>> twos = Pair(2, Pair(2, nil)) >>> plus.apply(twos, env) 4
625941da507cdc57c6306f93
def empty(self): <NEW_LINE> <INDENT> return len(self.queue) == 0
Check whether the queue is empty.
625941da7d43ff24873a2f54
@register.tag <NEW_LINE> def ifcansearch(parser, token): <NEW_LINE> <INDENT> search_nodelist = parser.parse(('else', 'endifcansearch',)) <NEW_LINE> token = parser.next_token() <NEW_LINE> if token.contents == 'else': <NEW_LINE> <INDENT> nosearch_nodelist = parser.parse(('endifcansearch',)) <NEW_LINE> parser.delete_first...
Outputs the contents of the block if search is enabled. Search is considered to be enabled _unless_ Haystack has been configured to use the "disabled" backend. Examples:: {% ifcansearch %} ... {% endifcansearch %} {% ifcansearch %} ... {% else %} ... {% endifcansearch %}
625941da711fe17d82542618
def create_batch(self, **kwargs): <NEW_LINE> <INDENT> if not self._max_message_size_on_link: <NEW_LINE> <INDENT> self._get_max_mesage_size() <NEW_LINE> <DEDENT> max_size_in_bytes = kwargs.get("max_size_in_bytes", None) <NEW_LINE> partition_id = kwargs.get("partition_id", None) <NEW_LINE> partition_key = kwargs.get("par...
Create an EventDataBatch object with the max size of all content being constrained by max_size_in_bytes. The max_size_in_bytes should be no greater than the max allowed message size defined by the service. :keyword str partition_id: The specific partition ID to send to. Default is None, in which case the service wil...
625941da5fc7496912cc3c31
def on_prepare_sync(self, world, memento): <NEW_LINE> <INDENT> return False
Determine how `on_check` failures on the server should be handled. When `on_check` fails on the server, it means that the client which sent the message is out of sync (since had it been in sync, it would've rejected the message locally). There are two ways to handle this situation, and the role of this handler is ...
625941dade87d2750b860047
def Errback(log, fmt, **kwargs): <NEW_LINE> <INDENT> def errback_func(err): <NEW_LINE> <INDENT> log.failure(fmt, err, **kwargs) <NEW_LINE> <DEDENT> return errback_func
Convenience class for logging an error on a Deferred.
625941da23849d37ff7b3340
def export_datastores(self): <NEW_LINE> <INDENT> view = navigate_to(self, "All") <NEW_LINE> view.export_all.click()
Export all classes and instances to a file
625941da24f1403a92600e17
def move_fit(fit_data, coor1, coor2): <NEW_LINE> <INDENT> print(str(coor2[0])+" "+str(coor2[1])+"\n") <NEW_LINE> dx = float(coor2[0]) - float(coor1[0]) <NEW_LINE> dy = float(coor2[1]) - float(coor1[1]) <NEW_LINE> b = [([0] * len(fit_data[0])) for i in range(len(fit_data))] <NEW_LINE> if dx == 0 and dy == 0: <NEW_LINE>...
:param fit_data: 需要平移图像的数据 :param coor1: 原图坐标点 :param coor2: 对应的需要平移图的坐标点 :return: 平移后的图像数据部分
625941daaad79263cf390cf8
def check_width(width): <NEW_LINE> <INDENT> if width > WIDTH_HIGH_CONSTANT or width < 2: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True
Checks whether the width is within reasonable bounds Args: width: The middle width of the worm Returns: Boolean True if width is acceptable
625941da73bcbd0ca4b2c329
def get_library_name(self): <NEW_LINE> <INDENT> return self.__lib_name
Return library name.
625941da07f4c71912b11737
def on_end(self, connection, request): <NEW_LINE> <INDENT> pass
Called at end of request
625941dad18da76e2353278b
def __init__(self, scale, width, height): <NEW_LINE> <INDENT> self.oddsarray = np.ones((height, width), np.float64) <NEW_LINE> self.scale = scale
Params: scale: the scale of the map in meters per pixel. width, height: the dimensions of the grid in tiles.
625941da379a373c97cfadf9
def test_updates_submission_with_meta(): <NEW_LINE> <INDENT> api = CROWDAI_API(AUTH_TOKEN) <NEW_LINE> challenge_id = "test_challenge" <NEW_LINE> api.authenticate_participant(EXAMPLE_API_KEY) <NEW_LINE> submission = api.create_submission(challenge_id) <NEW_LINE> assert type(submission.id) == int <NEW_LINE> assert submis...
Tests is it successfully updates submission with the meta param
625941daa934411ee3751947
def filtermove(df, cov=1): <NEW_LINE> <INDENT> df_ = df.loc[pd.notnull(df['end'])] <NEW_LINE> vals = df_.loc[:, ['transy', 'transx', 'dur']].values <NEW_LINE> gh = lambda x: gausshist(x, cov=cov) <NEW_LINE> h = np.apply_along_axis(gh, axis=1, arr=vals) <NEW_LINE> h = h.sum(axis=0) <NEW_LINE> h = h / h.sum() <NEW_LINE> ...
Apply Gaussian filter to all moves
625941da7b25080760e3970b
def air_permeability(self, e_ksat=None, qfit=0.5): <NEW_LINE> <INDENT> if e_ksat is None: <NEW_LINE> <INDENT> e_ksat = void_ratio_permeability.ConstantPermeabilityModel(ka=1.0) <NEW_LINE> <DEDENT> kd = e_ksat.k_from_e(self.profile.e) <NEW_LINE> kr = np.zeros_like(kd) <NEW_LINE> Sr = self.profile.Sr <NEW_LINE> kr = swcc...
Calculate the Air permeability based on saturation ka = kd * (1-Sr)**0.5*(1-Sr**(1/qfit))**(2*qfit) kd = fn(e) Parameters ---------- e_ksat : PermeabilityVoidRatioRelationship object PermeabilityVoidRatioRelationship object defining dependence of dry air permeability on void ratio. Default e_ksat=Cons...
625941daa8370b7717052b51
def shutdown(self): <NEW_LINE> <INDENT> self._connection.close()
Closes open database connections.
625941da50485f2cf553d04e
def _getStringsForText (self): <NEW_LINE> <INDENT> langStr = u' lang="{language}"'.format (language=self._dialog.language) <NEW_LINE> commonparams = self._getCommonParams() <NEW_LINE> startCommand = u'(:source{lang}{commonparams}:)\n'.format (lang=langStr, commonparams=commonparams) <NEW_LINE> endCommand = u'\n(:source...
Возвращает кортеж строк для случая оформления исходников из текста (не из файла)
625941dad6c5a10208144300
def goto(self, what, direction=None): <NEW_LINE> <INDENT> if what == 'error': <NEW_LINE> <INDENT> self._goto_error() <NEW_LINE> return <NEW_LINE> <DEDENT> from ast import ClassDef, FunctionDef, AsyncFunctionDef <NEW_LINE> here = tuple(self._vim.current.window.cursor) <NEW_LINE> if what == 'name': <NEW_LINE> <INDENT> cu...
Go to next location of type `what` in direction `direction`.
625941da7b25080760e3970c
def task_by_command(self, command): <NEW_LINE> <INDENT> query = self.__session.query(Task).filter( Task.task_command == command).all() <NEW_LINE> return query
return all task that have the same command
625941da3346ee7daa2b3021
def using_cumisc(handle=None): <NEW_LINE> <INDENT> if handle is None: <NEW_LINE> <INDENT> handle = get_cublas_handle() <NEW_LINE> <DEDENT> return CumiscUser(handle)
Temporarily set chainer's CUBLAS handle to scikit-cuda. The usage is similar to :func:`using_device`. Args: handle: CUBLAS handle. If ``None`` is specified, it uses CUBLAS handle for the current device. Returns: CumiscUser: Misc user object.
625941dacdde0d52a9e532e8
@fixture <NEW_LINE> def db_session(config, content, connection, request): <NEW_LINE> <INDENT> from transaction import abort <NEW_LINE> trans = connection.begin() <NEW_LINE> request.addfinalizer(trans.rollback) <NEW_LINE> request.addfinalizer(abort) <NEW_LINE> from kotti import DBSession <NEW_LINE> return DBSession()
returns a db session object and sets up a db transaction savepoint, which will be rolled back after the test.
625941da67a9b606de4a816b
def put_at_index(self, index: int, item: abc.Playable) -> None: <NEW_LINE> <INDENT> if self.is_full: <NEW_LINE> <INDENT> if not self._overflow: <NEW_LINE> <INDENT> raise QueueFull(f"Queue max_size of {self.max_size} has been reached.") <NEW_LINE> <DEDENT> self._drop() <NEW_LINE> <DEDENT> return self._insert(index, self...
Put the given item into the queue at the specified index.
625941da1b99ca400220ad66
def __init__(self): <NEW_LINE> <INDENT> threading.Thread.__init__(self) <NEW_LINE> self.in_pipe = None <NEW_LINE> self.out_pipe = None
Set up the Filter fields. Meant to be called first by subclasses.
625941dad486a94d0b98e3fa
def test_cmd_delete_auth(self, config_client_delete_auth_fixture): <NEW_LINE> <INDENT> mock_config_client_delete_auth = config_client_delete_auth_fixture <NEW_LINE> result = self.runner.invoke(cli, [ 'auth', 'delete', '--name', 'test1', '--auto-approve']) <NEW_LINE> mock_config_client_delete_auth.assert_called_with('te...
Delete an auth account Given - Account has been configured When - User deletes the auth account Then - Credentials are removed from the credential store
625941da4428ac0f6e5baaa7
def mfile_write_conclusion(fh): <NEW_LINE> <INDENT> fh.write("grid on\n")
Write the concluding commands to the open m-file after all strands have been writtein with mfile_write_strand(). This is instructions to turn on grid, etc. Parameters: fh - open filehandle of m-file to write to Return value: None
625941daad47b63b2c50a232
def message_process(self, cr, uid, model, message, custom_values=None, save_original=False, strip_attachments=False, context=None): <NEW_LINE> <INDENT> if isinstance(message, xmlrpclib.Binary): <NEW_LINE> <INDENT> message = str(message.data) <NEW_LINE> <DEDENT> model_pool = self.pool.get(model) <NEW_LINE> context = con...
Process an incoming RFC2822 email message related to the given thread model, relying on ``mail.message.parse()`` for the parsing operation, and then calling ``message_new`` (if the thread record did not exist) or ``message_update`` (if it did), then calling ``message_forward`` to automatically notify other people that ...
625941da63f4b57ef00013c6
def Start(self, pos): <NEW_LINE> <INDENT> if not self.scrollwin: <NEW_LINE> <INDENT> raise Exception('No ScrollWindow defined') <NEW_LINE> <DEDENT> self.pos = pos <NEW_LINE> self.scrollwin.SetCursor(wx.Cursor(wx.CURSOR_SIZING)) <NEW_LINE> if not self.scrollwin.HasCapture(): <NEW_LINE> <INDENT> self.scrollwin.CaptureMou...
Start a drag scroll operation
625941da656771135c3ebb25
def doOneFile(path, fh): <NEW_LINE> <INDENT> recnum = 0 <NEW_LINE> rec = "" <NEW_LINE> print("[") <NEW_LINE> while (True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> rec = fh.readline() <NEW_LINE> <DEDENT> except IOError as e: <NEW_LINE> <INDENT> sys.stderr.write("Error (%s) reading record %d of '%s'.\n" % (type(e), ...
Read and deal with one individual file.
625941dae1aae11d1e749f6d
def test_invalid_subtraction(self): <NEW_LINE> <INDENT> if VERSION_INFO >= '2.7': <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> _ = ehex(3) - 99 <NEW_LINE> _ = ehex('A') - 99 <NEW_LINE> _ = ehex(1) - ehex('Y') <NEW_LINE> del _ <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.ass...
Test out of bounds subtraction raises ValueError
625941da9b70327d1c4e1089
def initialize(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> requests.get('http://localhost:4242/poll') <NEW_LINE> state['connected_to_bot'] = True <NEW_LINE> <DEDENT> except requests.exceptions.ConnectionError: <NEW_LINE> <INDENT> state['connected_to_bot'] = False <NEW_LINE> <DEDENT> state['window'] = turtle.Screen(...
IMPORTANT: Call this function at the beginning of your program.
625941dabe8e80087fb20ef3
def testConstructor_009(self): <NEW_LINE> <INDENT> dependencies = ActionDependencies() <NEW_LINE> self.assertEqual(None, dependencies.afterList) <NEW_LINE> dependencies.afterList = [ "a", "b", ] <NEW_LINE> self.assertEqual(["a", "b"], dependencies.afterList)
Test assignment of afterList attribute, non-empty list, valid values.
625941da96565a6dacc8f97e
def __init__(self, parameters): <NEW_LINE> <INDENT> self._currentState = parameters.get_initial_health_state() <NEW_LINE> self._delta_t = parameters.get_delta_t() <NEW_LINE> self._survivalTime = 0 <NEW_LINE> self._timeToStroke = 0 <NEW_LINE> self._ifDevelopedStroke = False <NEW_LINE> self._numberOfStrokes = 0 <NEW_LINE...
:param parameters: patient parameters
625941dafbf16365ca6f647b
def get_qq_from_uin(self, uin, target_type=1, vfwebqq=""): <NEW_LINE> <INDENT> rsp_json = self._request_and_parse( method='GET', url='http://s.web2.qq.com/api/get_friend_uin2', data_dict={ 'tuin': uin, 'vfwebqq': vfwebqq if vfwebqq else self.vfwebqq, 't': int(time()), 'type': target_type } ) <NEW_LINE> dbgprint('获取QQ号'...
根据uin获取QQ号 :type target_type: int :type vfwebqq: str :type uin: int
625941da3617ad0b5ed681aa
def generate_file_name(url: str) -> str: <NEW_LINE> <INDENT> result = urlparse(url) <NEW_LINE> path = pathlib.Path(result.path) <NEW_LINE> current_date_str = datetime.now().date().strftime('%Y-%m-%d') <NEW_LINE> return f'{path.name}__{result.query}__{current_date_str}.xml'
'https://jira.foobar.ru/sr/jira.issueviews:searchrequest-xml/24381/SearchRequest-24381.xml?tempMax=1000' -> 'SearchRequest-24381.xml__tempMax=1000__2017-11-07.xml' :param url: :return:
625941da3cc13d1c6d3c762d
def __notifyGUIConsole(self, msg): <NEW_LINE> <INDENT> for widget in self.__gui_output: <NEW_LINE> <INDENT> event = LogCustomEvent(msg) <NEW_LINE> model.guiapi.postCustomEvent(event, widget)
notifies all GUI widgets registered IMPORTANT: the widgets MUST be able to handle a custom event
625941da3539df3088e2e5fe
def find_export_link(self, section_title, data_format='csv'): <NEW_LINE> <INDENT> data_link = (self.find_link(section_title) .tag .find_next_sibling('div') .find('a', string=data_format)) <NEW_LINE> return urllib.parse.urljoin(self.url, data_link['href'])
Assuming the section is already open, this returns the link to the data format for export.
625941da236d856c2ad44a91
def reproject_polygon(src, dst, t_srs): <NEW_LINE> <INDENT> save_path = os.path.dirname(dst) <NEW_LINE> os.makedirs(save_path, exist_ok=True) <NEW_LINE> name = DRIVERS[os.path.splitext(src)[-1]] <NEW_LINE> driver = ogr.GetDriverByName(name) <NEW_LINE> src_file = driver.Open(src) <NEW_LINE> src_layer = src_file.GetLayer...
Reproject a shapefile of polygons and write results to disk. Parameters ---------- src : str Path to source shapefile. dst : str Path to target file. tproj (int | str): Target coordinate projection system as an epsg code or proj4 string. Sometimes EPSG codes aren't available to GDAL installations, but ...
625941da7047854f462a16ba
def test_safe_ssl_socket(self): <NEW_LINE> <INDENT> self.assertEqual('TBD', 'TBD')
Test safeSSLSocket(self, host, port, timeout)
625941da73bcbd0ca4b2c32a
def isValidSerialization(self, preorder): <NEW_LINE> <INDENT> preorder = preorder.split(',') <NEW_LINE> N = len(preorder) <NEW_LINE> cnt = 0 <NEW_LINE> for i in range(N-1, -1, -1): <NEW_LINE> <INDENT> if preorder[i] == '#': <NEW_LINE> <INDENT> cnt += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if cnt <= 1: <NEW_LIN...
:type preorder: str :rtype: bool
625941da29b78933be1e595c
def set_location(self, job_id, location, foreign_id=(), state_new='?', message=None): <NEW_LINE> <INDENT> with self.db as c: <NEW_LINE> <INDENT> if foreign_id == (): <NEW_LINE> <INDENT> query = 'UPDATE job SET location = %s WHERE id = %s' <NEW_LINE> param = (location, job_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDEN...
Update the location, and optionally the foreign_id of a job. parameters; job_id (required), ingteger, identifies the job to update. location (required), string, where to process the job. foregin_id (option), string, None to set to NULL or empty tuple (default) to not alter the current value. state_new: new state to...
625941da7d847024c06be572
def test_stickers_random_get(self): <NEW_LINE> <INDENT> r = self.api.stickers_random_get(KEY) <NEW_LINE> self._validate(r)
Test case for stickers_random_get Random Sticker Endpoint
625941da21bff66bcd684c04
def save_index_as_labels(index, label_filename): <NEW_LINE> <INDENT> with open(label_filename, 'w', encoding='utf-8') as out: <NEW_LINE> <INDENT> for label in index: <NEW_LINE> <INDENT> print(label, file=out)
Save a pandas Index as a text file of labels.
625941da8a349b6b435e8427
def get_config(): <NEW_LINE> <INDENT> cfg = VersioneerConfig() <NEW_LINE> cfg.VCS = "git" <NEW_LINE> cfg.style = "pep440" <NEW_LINE> cfg.tag_prefix = "" <NEW_LINE> cfg.parentdir_prefix = "prlworkflows-" <NEW_LINE> cfg.versionfile_source = "prlworkflows/_version.py" <NEW_LINE> cfg.verbose = False <NEW_LINE> return cfg
Create, populate and return the VersioneerConfig() object.
625941da63d6d428bbe447a3
def __init__(self): <NEW_LINE> <INDENT> self.TraceId = None <NEW_LINE> self.BodyIds = None
:param TraceId: 人体轨迹ID。 :type TraceId: str :param BodyIds: 包含的人体轨迹图片Id列表。 :type BodyIds: list of str
625941da99cbb53fe6792e9a
def contains(self, geom): <NEW_LINE> <INDENT> geom = _geom_to_pygeos(geom) <NEW_LINE> filt = self._predicate(pg.contains, geom) <NEW_LINE> return PredicateFilters(filt, 'contains')
Returns True for elements where geom is completely inside GeoDataFrame geometry. Arguments: geom (str|bytes|pygeos.lib.Geometry): The geometry for the predicate. Returns: (PredicateFilters): A boolean array with the predicate for each index.
625941dabd1bec0571d908e3
def deserialize(self, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.header is None: <NEW_LINE> <INDENT> self.header = std_msgs.msg.Header() <NEW_LINE> <DEDENT> end = 0 <NEW_LINE> _x = self <NEW_LINE> start = end <NEW_LINE> end += 12 <NEW_LINE> (_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs,) =...
unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str``
625941da56b00c62f0f1490f
def show_list_feed(request, slug, template_name='podcast/show_feed.html'): <NEW_LINE> <INDENT> return object_detail(request, queryset=Show.objects.all(), mimetype='application/rss+xml', slug_field='slug', slug=slug, template_name=template_name)
Episode RSS feed for a given show Template: ``podcast/show_feed.html`` Context: object Story detail
625941da97e22403b379d24f
def build_evaluator(model): <NEW_LINE> <INDENT> vander = vander_builder(model.grid, model.exponents) <NEW_LINE> if model.is_periodic: <NEW_LINE> <INDENT> def restack(x): <NEW_LINE> <INDENT> return np.hstack((np.real(x), np.imag(x))) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> def restack(x): <NEW_LINE> <INDE...
Returns a method to evaluate the Fourier or Chebyshev expansion defined by `model`. The returned method takes a `fun` and a value (or array of values) `x` to evaluate the approximant.
625941da3539df3088e2e5ff
def speed(self, speed): <NEW_LINE> <INDENT> if speed > 3: <NEW_LINE> <INDENT> self.comm('SPE ' + str(speed)) <NEW_LINE> <DEDENT> return self.speeds(speed)
Set the integration speed
625941da187af65679ca53d3
def next_sibling(self): <NEW_LINE> <INDENT> idx = self.index() + 1 <NEW_LINE> dad = self.parent() <NEW_LINE> if not dad or idx >= len(dad): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return dad[idx]
Get next sibling element.
625941da45492302aab5e57a
def get_policy_param(self) -> Any: <NEW_LINE> <INDENT> raise NotImplementedError
Get policy's parameters.
625941dab57a9660fec33b3b
def test_pfizer(self): <NEW_LINE> <INDENT> file_name = 'tests_pfizer_ips.json' <NEW_LINE> self.tests = self._load_tests(self.tests_dir, file_name) <NEW_LINE> for test in self.tests['tests']: <NEW_LINE> <INDENT> headers = {"AH-Client-IP": '155.94.70.193'} <NEW_LINE> self._check_rule(test, headers)
Tests .htaccess rules for pfizer IPs on public URLs
625941da07f4c71912b11738
def __init__(self, text=None, resource=None, decision=None, action=None, evidence=None, extension_elements=None, extension_attributes=None): <NEW_LINE> <INDENT> self.text = text <NEW_LINE> self.resource = resource <NEW_LINE> self.decision = decision <NEW_LINE> self.action = action or [] <NEW_LINE> self.evidence = evide...
Constructor for AuthzDecisionStatement Args: text: str The text data in this element resource: Resource attribute decision: Decision attribute action: Action Elements evidence: Evidence Elements extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attr...
625941da30c21e258bdfa753
def euklidian_distance(P, Q=origin): <NEW_LINE> <INDENT> return sum((p - q) ** 2 for p, q in zip(P, Q)) ** 0.5
Straight-line (hypotenuse) distance between two points.
625941da50485f2cf553d04f
def read_int32(fid): <NEW_LINE> <INDENT> return _unpack_simple(fid, '>i4', np.int32)
Read 32bit integer from bti file.
625941da796e427e537b087c
def capacity(self): <NEW_LINE> <INDENT> return _AriaPy.DoubleVector_capacity(self)
capacity(self) -> size_type
625941dae8904600ed9f21e4