code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def sign(ikey, skey, method, host, uri, date, sig_version, params): <NEW_LINE> <INDENT> canonical = canonicalize(method, host, uri, params, date, sig_version) <NEW_LINE> if isinstance(skey, unicode): <NEW_LINE> <INDENT> skey = skey.encode('utf-8') <NEW_LINE> <DEDENT> sig = hmac.new(skey, canonical, hashlib.sha1) <NEW_L...
Return basic authorization header line with a Duo Web API signature.
625941e0e8904600ed9f22b9
def p1(self): <NEW_LINE> <INDENT> result = self.root_node.recursive_sum() <NEW_LINE> return result
The sleigh is much easier to pull than you'd expect for something its weight. Unfortunately, neither you nor the Elves know which way the North Pole is from here. You check your wrist device for anything that might help. It seems to have some kind of navigation system! Activating the navigation system produces more ba...
625941e0a79ad161976cc4cc
def getDiff(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> right_data = self.right.get() <NEW_LINE> right_data = pickle.loads(right_data) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> raise NotFoundException('No data on right endpoint.') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> left_data = self.lef...
Retrieve previusly stored data from left and right and returns a python object describing the differences (if any)
625941e0d4950a0f3b08c6d1
def bakeResults(*args, **kwargs): <NEW_LINE> <INDENT> pass
This command allows the user to replace a chain of dependency nodes which define the value for an attribute with a single animation curve. Returns: `int` - The number of channels baked
625941e066673b3332b92419
def regex_sub(data): <NEW_LINE> <INDENT> regexs = regex_lists() <NEW_LINE> for pair in regexs: <NEW_LINE> <INDENT> pattern = pair[0] <NEW_LINE> replacement = pair[1] <NEW_LINE> data = re.sub(pattern, replacement, data) <NEW_LINE> <DEDENT> return data
Subsitute latex for words
625941e0a934411ee3751a1c
def mutate(self): <NEW_LINE> <INDENT> cpool = model_constraintpool.ConstraintPool.get_pool() <NEW_LINE> if model_random.is_mutating(): <NEW_LINE> <INDENT> self._randomize_mapping(cpool) <NEW_LINE> <DEDENT> size_constraint = cpool.get(self, GLYPHFONTSIZE_CONSTRAINT) <NEW_LINE> self.size = model_random.jitter_constrained...
Make small random changes to the layers components.
625941e0283ffb24f3c55c85
def write_all_rpc_commands(dirname, node): <NEW_LINE> <INDENT> filename = os.path.join(dirname, REFERENCE_FILENAME) <NEW_LINE> if os.path.isfile(filename): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> help_output = node.help().split('\n') <NEW_LINE> commands = set() <NEW_LINE> for line in help_output: <NEW_LINE...
Write out a list of all RPC functions available in `sap-cli` for coverage comparison. This will only happen once per coverage directory. Args: dirname (str): temporary test dir node (AuthServiceProxy): client Returns: bool. if the RPC interface file was written.
625941e0d268445f265b51f6
def get_cloud_filter(self, x_ind, y_ind): <NEW_LINE> <INDENT> if self.memo_data is None: <NEW_LINE> <INDENT> self.get_cloud_saturation_mask() <NEW_LINE> <DEDENT> return np.nonzero(self.memo_data.cloud_masks[:, x_ind, y_ind])
Extracts cloud filter for sample image pixel :param x_ind: x_coordinate :param y_ind: y_coordinate :return: list of cloud masks for corresponding image pixel
625941e0dd821e528d63b52e
def get_project(self, project_id): <NEW_LINE> <INDENT> req = requests.get(self.api_base + 'projects/{}'.format(project_id)) <NEW_LINE> if req.status_code == 404: <NEW_LINE> <INDENT> raise ValueError(req.json()['detail']) <NEW_LINE> <DEDENT> req.raise_for_status() <NEW_LINE> return req.json()
Get a single project by project ID
625941e0ac7a0e7691ed444e
def test_invalid_email(self): <NEW_LINE> <INDENT> self.assertIsNone(process_email("dude@home@example.com")) <NEW_LINE> self.assertIsNone(process_email("")) <NEW_LINE> self.assertIsNone(process_email(None))
Should return None for invalid email.
625941e0956e5f7376d711f3
def __init__(self, version): <NEW_LINE> <INDENT> Drmaa2Object.__init__(self) <NEW_LINE> if isinstance(version, POINTER(drmaa2_version)): <NEW_LINE> <INDENT> self._struct = POINTER(drmaa2_version)() <NEW_LINE> self._struct.contents = drmaa2_version() <NEW_LINE> if version: <NEW_LINE> <INDENT> self.major = ByteString(get...
Constructor. :param version: Low-level drmaa2_version struct. :type version: drmaa2_version
625941e0435de62698dfdfd5
def __call__(self, age, *args, retirement_age=None, **kwargs): <NEW_LINE> <INDENT> allocation = super().__call__( age, *args, retirement_age=retirement_age, **kwargs) <NEW_LINE> return self._balance_allocation(allocation)
Returns a dict of {account, Money} pairs.
625941e07cff6e4e81117d0d
def _add_text(self, elem): <NEW_LINE> <INDENT> words = WORD_SEPARATORS.split(elem.string.lower()) <NEW_LINE> for word in words: <NEW_LINE> <INDENT> word = word.strip() <NEW_LINE> if word in self._ignored_words: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self._curr_words.append((self.crawler.word_id(word), self._f...
Add some text to the document. This records word ids and word font sizes into the self._curr_words list for later processing.
625941e08e71fb1e9831db30
def put_bucket(oss, bucket_name, acl, headers): <NEW_LINE> <INDENT> res = oss.put_bucket(bucket_name, acl=acl, headers = {}) <NEW_LINE> if (res.status / 100) == 2: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Create bucket
625941e060cbc95b062c68cb
def send_email(sendto, subject, message, mime_type, config, file_path=None): <NEW_LINE> <INDENT> if config["protocol"] == "ssl": <NEW_LINE> <INDENT> mail_server = smtplib.SMTP_SSL(host=config["server"], port=int(config["port"]), timeout=float(config["timeout"])) <NEW_LINE> <DEDENT> elif config["protocol"] == "tls": <NE...
发送邮件 :param str or list sendto: 接收邮件的邮箱 :param str subject: 邮件主题 :param str message: 邮件正文内容 :param str mime_type: 邮件类型 :param dict config: 邮件发件人配置信息 :param str file_path: 邮件附件路径
625941e0d53ae8145f87a5f1
def _pack_call_args(self, args, kwargs): <NEW_LINE> <INDENT> assert bool(args) != bool(kwargs), 'either positional or keyword, but not both' <NEW_LINE> assert U.is_signature_compatible(self.forward, *args, **kwargs), 'self.forward() should have the same signature as placeholder call' <NEW_LINE> if...
Handle variable positional and keyword args. Can be overriden to change behavior for __call__ signature Returns: pack args into a single nested structure of placeholders or tensors, depending on the actual call
625941e0187af65679ca54a8
def test_assert_truth(self) : <NEW_LINE> <INDENT> self.assertTrue(___)
We shall contemplate the truth about selects..
625941e04e696a04525c97d5
def virtualValue(self , iIndex , bIsBinary , aValue = None): <NEW_LINE> <INDENT> if (iIndex <= 0) or (iIndex > self.vtQty) or (self.ePlatform == Platform.BASC_NONE): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> index = int(iIndex - 1 + self.vtBase) <NEW_LINE> if aValue == None: <NEW_LINE> <INDENT> value = self.r...
Reads or writes a virtual point using 1-based index (BO1..)
625941e02ae34c7f2600d4b9
def __getattr__(self, name): <NEW_LINE> <INDENT> return self._extend(AttrOp(name))
Indicate that the source or target should be traversed by attribute access.
625941e09f2886367277ac13
def _read_temp(self): <NEW_LINE> <INDENT> with open(self.template, 'r', encoding='cp1252') as template: <NEW_LINE> <INDENT> lines = template.readlines() <NEW_LINE> <DEDENT> return lines
Open template file and return a list of lines.
625941e0d164cc61757830d7
def balance_sides(self): <NEW_LINE> <INDENT> if self.teams[0].aff_count < self.teams[1].aff_count: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif self.teams[0].aff_count > self.teams[1].aff_count: <NEW_LINE> <INDENT> self.teams.reverse() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> random.shuffle(self.teams)
Puts whoever has affirmed less on the affirmative side, or chooses randomly if they've done it equally.
625941e021a7993f00bc807e
def __setitem__(self, key, item): <NEW_LINE> <INDENT> self.__dict__[key] = item
Make the class subscriptable, so that someone can access the class attributes as in dicts.example response['placement_name'] :param: the item/key to be accessed.
625941e08e05c05ec3eea700
def create_new_peer_id(self): <NEW_LINE> <INDENT> self.SID0 = 0 <NEW_LINE> self.CID0 = 0 <NEW_LINE> if len(self.SI.clients) >= self.SI.nClients: <NEW_LINE> <INDENT> self.id = -1 <NEW_LINE> return <NEW_LINE> <DEDENT> active_ids = frozenset(self.SI.clients.keys()) <NEW_LINE> unused_ids = frozenset((range(self.SI.nClients...
Determine the lowest unused client ID and set self.id.
625941e060cbc95b062c68cc
def CreateBucket( self, name: str, region: Optional[str] = None, acl: str = 'private', tags: Optional[Dict[str, str]] = None, policy: Optional[str] = None) -> Dict[str, Any]: <NEW_LINE> <INDENT> client = self.aws_account.ClientApi(common.S3_SERVICE) <NEW_LINE> try: <NEW_LINE> <INDENT> desired_region = region or self.aw...
Create an S3 storage bucket. Args: name (str): The name of the bucket. region (str): Optional. The region in which the bucket resides. acl (str): Optional. The canned ACL with which to create the bucket. Default is 'private'. tags (Dict[str, str]): Optional. A dictionary of tags to add to the bucket, f...
625941e0d58c6744b4257fe7
def _polar_graph(m, q, g, intersection_size=None): <NEW_LINE> <INDENT> from sage.libs.gap.libgap import libgap <NEW_LINE> from itertools import combinations <NEW_LINE> W=libgap.FullRowSpace(libgap.GF(q), m) <NEW_LINE> B=libgap.Elements(libgap.Basis(W)) <NEW_LINE> V = libgap.Orbit(g,B[0],libgap.OnLines) <NEW_LINE> gp = ...
The helper function to build graphs `(D)U(m,q)` and `(D)Sp(m,q)` Building a graph on an orbit of a group `g` of `m\times m` matrices over `GF(q)` on the points (or subspaces of dimension ``m//2``) isotropic w.r.t. the form `F` left invariant by the group `g`. The only constraint is that the first ``m//2`` elements of...
625941e076e4537e8c3519fd
def zenith_nadir(x, y): <NEW_LINE> <INDENT> if y == 'm': <NEW_LINE> <INDENT> bb = [] <NEW_LINE> cc = [] <NEW_LINE> for i in range(x.shape[1]): <NEW_LINE> <INDENT> bb.append(amax(x[:, i:i + 1])) <NEW_LINE> b = array(bb) <NEW_LINE> cc.append(amin(x[:, i:i + 1])) <NEW_LINE> c = array(cc) <NEW_LINE> <DEDENT> return (b, c) ...
zenith and nadir virtual action function; x is the weighted normalized decision matrix and y is the action used. For min/max input 'm' and for absolute input enter 'a'
625941e0b57a9660fec33c11
def test_source_out_attribute_is_smaller_than_source_in_attribute(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError) as cm: <NEW_LINE> <INDENT> self.test_shot.source_out = self.test_shot.source_in - 2 <NEW_LINE> <DEDENT> self.assertEqual( str(cm.exception), 'Shot.source_out can not be smaller than Shot.sourc...
testing if a ValueError will be raised when the source_out attribute is set to a value smaller than source_in
625941e0bde94217f3683176
def main(): <NEW_LINE> <INDENT> initial_clusters = aggregate_vertices() <NEW_LINE> edges_groups = formulate_edges(initial_clusters) <NEW_LINE> accum = 0 <NEW_LINE> for edges in edges_groups: <NEW_LINE> <INDENT> heapify(edges) <NEW_LINE> clusters = [set(x) for x in map(itemgetter(1, 2), edges)] <NEW_LINE> while len(edge...
Main function
625941e02c8b7c6e89b35b47
def __init__(self, A, H, x, P, Q, R): <NEW_LINE> <INDENT> self.A = A <NEW_LINE> self.H = H <NEW_LINE> self.x = x <NEW_LINE> self.P = P <NEW_LINE> self.Q = Q <NEW_LINE> self.R = R <NEW_LINE> self.I = Matrix.identity(max(x.size())) <NEW_LINE> self.measurements = None <NEW_LINE> self.counter = None
Initialize the Kalman Filter matrices. This implementation skips the control input vector. Symbols used: :param Matrix A: state transition matrix - predict next state from current one :param Matrix H: observation matrix, calculate measurement from the state :param Matrix x: initial estimate of the state :param Matrix ...
625941e0b545ff76a891419e
def ngram_freq(textstring, max_n=10): <NEW_LINE> <INDENT> tokenlist = nltk.Text(nltk.word_tokenize(textstring)) <NEW_LINE> ngram_freqdist = FreqDist() <NEW_LINE> for n in arange(1,max_n): <NEW_LINE> <INDENT> for gram in ngrams(tokenlist,n): <NEW_LINE> <INDENT> ngram_freqdist[gram] += 1 <NEW_LINE> <DEDENT> <DEDENT> retu...
Construct an ngram frequency distribution from a string for 0 < n < max_n. Args: textstring: string to extract ngrams from max_n: the longest ngram length counted Returns: FreqDist obeject with tuple representation of ngrams as keys and the frequency with which each ngram occurs in textstring
625941e00a50d4780f66721d
def uploadFile(self, request_iterator, timeout, metadata=None, with_call=False, protocol_options=None): <NEW_LINE> <INDENT> raise NotImplementedError()
upload
625941e045492302aab5e650
def print_sudoku(self, puzzle): <NEW_LINE> <INDENT> dim = 13 <NEW_LINE> row_index = 0 <NEW_LINE> puzzle_copy = copy.deepcopy(puzzle) <NEW_LINE> for i in range(dim): <NEW_LINE> <INDENT> if i % 4 == 0: <NEW_LINE> <INDENT> if i == 0 or i == dim - 1: <NEW_LINE> <INDENT> print(' '.join(['-'] * dim)) <NEW_LINE> <DEDENT> else...
Print a particular puzzle in the Sudoku style. Parameter: puzzle (list): The puzzle to be printed.
625941e073bcbd0ca4b2c3fe
def binscatter(self, y, x, controls=None, n_bins=20, line_kwargs=None, scatter_kwargs=None, recenter_x=False, recenter_y=True, bins=None): <NEW_LINE> <INDENT> if line_kwargs is None: <NEW_LINE> <INDENT> line_kwargs = {} <NEW_LINE> <DEDENT> if scatter_kwargs is None: <NEW_LINE> <INDENT> scatter_kwargs = {} <NEW_LINE> <D...
:param self: matplotlib.axes.Axes object. i.e., fig, axes = plt.subplots(3) axes[0].binscatter(y, x) :param y: 1d numpy array or pandas series :param x: 1d numpy array or Pandas Series :param controls: numpy array or sparse matrix :param n_bins: int, default 20 :param line_kwargs: dict :param scatter_kwa...
625941e023e79379d52ee8e8
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Author): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941e00383005118ecf96a
def add_plugin(self, plugin): <NEW_LINE> <INDENT> pass
Add a plugin to the manager.
625941e0283ffb24f3c55c86
def s_one_set(topics): <NEW_LINE> <INDENT> s_one_set = [] <NEW_LINE> for top_words in topics: <NEW_LINE> <INDENT> s_one_set_t = [] <NEW_LINE> for w_prime in top_words: <NEW_LINE> <INDENT> s_one_set_t.append((w_prime, top_words)) <NEW_LINE> <DEDENT> s_one_set.append(s_one_set_t) <NEW_LINE> <DEDENT> return s_one_set
This function performs s_one_set segmentation on a list of topics. s_one_set segmentation is defined as: s_one_set = {(W', W*) | W' = {w_i}; w_i belongs to W; W* = W} Example: >>> topics = [np.array([9, 10, 7]) >>> s_one_set(topics) [[(9, array([ 9, 10, 7])), (10, array([ 9, 10, 7])), (7, arra...
625941e0f7d966606f6aa391
def merge_accumulators( self, accumulators ): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for shard_types in accumulators: <NEW_LINE> <INDENT> for feature_name, feature_type in shard_types.items(): <NEW_LINE> <INDENT> if (feature_name not in result or (_type_hierarchy_level(feature_type) > _type_hierarchy_level( result[...
Merge the feature types inferred from the different partitions. Args: accumulators: A list of dicts containing the feature types inferred from the different partitions of the data. Returns: A dict containing the merged feature types.
625941e0435de62698dfdfd6
def test_with_coord_distance_different(self): <NEW_LINE> <INDENT> response = self.query_region("coords/{coord}/stop_areas?distance=300".format(coord=r_coord)) <NEW_LINE> stops = get_not_null(response, 'stop_areas') <NEW_LINE> for s in stops: <NEW_LINE> <INDENT> is_valid_stop_area(s) <NEW_LINE> <DEDENT> eq_(len(stops), ...
same as test_with_coord, but with 300m radius. so we find all stops
625941e00fa83653e4657341
def rsync(original, new, mode='-a'): <NEW_LINE> <INDENT> assert os.path.exists(original) or '*' in original, 'original file found or is not a wildcard.' <NEW_LINE> assert mode[0] == '-', 'Mode is an option for rsync and must start with \'-\'' <NEW_LINE> if os.path.exists(new): <NEW_LINE> <INDENT> assert os.path.isdir(n...
Uses subprocess.call to rsync from 'filename' to 'new' If new is directory, copies original in. If new is new file, copies original to that name. mode '-a' for archiving (recursively). '-ptgo' better for files or when using wildcard.
625941e0a8ecb033257d3454
@singleton <NEW_LINE> def Float32b(): <NEW_LINE> <INDENT> return FormatField(">", "f")
Big endian, 32-bit IEEE floating point number
625941e04428ac0f6e5bab7d
def to_dr (self, sf:int, bw:int) -> DRxDef: <NEW_LINE> <INDENT> if bw >= 1000: bw //= 1000 <NEW_LINE> return self.sfbw2dr.get((sf,bw),NONE_DR)
Convert low level Lora radio parameters into a datarate.
625941e094891a1f4081be34
@pytest.mark.parametrize('tuples', [np.array([[[2.5], [0.1], [2.6]], [[1.6], [4.8], [9.1]], [[5.6], [2.8], [6.1]]]), np.array([[[2], [0], [2]], [[1], [4], [9]], [[1], [5], [3]]]), [[[2], [0], [2]], [[1], [4], [9]], [[3], [4], [29]]], (((2, 1), (0, 2), (2, 3)), ((1, 2), (4, 4), (9, 3)), ((3, 1), (4, 4), (29, 4)))]) <NEW...
Test that valid inputs when using no preprocessor raises no warning
625941e0b830903b967e9c90
def get_constraint_formset_class(self): <NEW_LINE> <INDENT> return self.constraint_formset_class
Returns ``self.constraint_formset_class``
625941e067a9b606de4a8240
def test_stronghold(self): <NEW_LINE> <INDENT> self.excepted_results = { 'vouched': {'vouched': True, 'unvouched': False, 'public': False}, 'unvouched': {'vouched': True, 'unvouched': True, 'public': False}, 'public': {'vouched': True, 'unvouched': True, 'public': True}, 'excepted': {'vouched': True, 'unvouched': True,...
Test stronhold middleware functionality.
625941e0d10714528d600070
def expand_all(start, end, tags): <NEW_LINE> <INDENT> if len(tags) == 1: <NEW_LINE> <INDENT> for branch in expand(start, end, tags[0]): <NEW_LINE> <INDENT> yield [branch] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> first, rest = tags[0], tags[1:] <NEW_LINE> for middle in range(start+1, end+1-len(rest)): <NEW...
Yield all sequences of branches for tags over words[start:end].
625941e031939e2706e4d1ee
@commandWrap <NEW_LINE> def PolyBrushMarkingMenuPopDown(*args, **kwargs): <NEW_LINE> <INDENT> return cmds.PolyBrushMarkingMenuPopDown(*args, **kwargs)
:rtype: list|str|DagNode|AttrObject|ArrayAttrObject|Components1Base
625941e0f9cc0f698b140981
def deserialize(self, data: dict): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.name = data["name"] <NEW_LINE> self.category = data["category"] <NEW_LINE> if isinstance(data["available"], bool): <NEW_LINE> <INDENT> self.available = data["available"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise DataValidatio...
Deserializes a Pet from a dictionary Args: data (dict): A dictionary containing the Pet data
625941e0004d5f362079a6ba
def test_add_contacts(self): <NEW_LINE> <INDENT> self.driver.find_element_by_id('com.android.calculator2:id/digit9').click()
el = self.driver.find_element_by_name("Add Contact") el.click() textfields = self.driver.find_elements_by_class_name("android.widget.EditText") textfields[0].send_keys("Appium User") textfields[2].send_keys("someone@appium.io") self.assertEqual('Appium User', textfields[0].text) self.assertEqual('someone@appium.io', ...
625941e04527f215b584c7dc
def test_delete_list(self): <NEW_LINE> <INDENT> self.mimi.delete_list(self.list_name) <NEW_LINE> expected_url = '%saudience_lists/%s' % ( self.mimi.base_url, quote(self.list_name)) <NEW_LINE> self.expected_args['_method'] = 'delete' <NEW_LINE> expected_args = urlencode(self.expected_args) <NEW_LINE> self.mimi.urlopen.a...
Test that a delete list request is properly formatted.
625941e0f7d966606f6aa392
def today_node(**kw): <NEW_LINE> <INDENT> if "default" not in kw: <NEW_LINE> <INDENT> kw['default'] = deferred_today <NEW_LINE> <DEDENT> widget_options = kw.pop('widget_options', {}) <NEW_LINE> return colander.SchemaNode( colander.Date(), widget=get_date_input(**widget_options), **kw )
Return a schema node for date selection, defaulted to today
625941e0eab8aa0e5d26dee2
def communicate(tensors, communication_op, attention=False): <NEW_LINE> <INDENT> flat_tensor = flatten_tensors(tensors) <NEW_LINE> import datetime <NEW_LINE> communication_op(tensor=flat_tensor, async_op=True) <NEW_LINE> if attention: <NEW_LINE> <INDENT> return tensors/flat_tensor <NEW_LINE> <DEDENT> for f, t in zip(un...
Reference: https://github.com/facebookresearch/stochastic_gradient_push Communicate a list of tensors. Arguments: tensors (Iterable[Tensor]): list of tensors. communication_op: a method or partial object which takes a tensor as input and communicates it. It can be a partial object around someth...
625941e0b7558d58953c5296
def getStatus(self): <NEW_LINE> <INDENT> return self.residency
Returns the status
625941e04428ac0f6e5bab7e
def get_new_messages_raw(self): <NEW_LINE> <INDENT> messages = [] <NEW_LINE> try: <NEW_LINE> <INDENT> last_message_id = max( self.vk.messages.get(count=1)['items'][0]['id'], self.vk.messages.get(count=1, out=1)['items'][0]['id'] ) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDE...
:return: all messages with id > self.last_message_id as a list of dicts
625941e076d4e153a657eebb
def centroid_y(polygon, a): <NEW_LINE> <INDENT> length = len(polygon) <NEW_LINE> i, cy = 0, 0 <NEW_LINE> while i != length - 1: <NEW_LINE> <INDENT> cy += (longitude(polygon[i])+longitude(polygon[i+1])) * ( latitude(polygon[i])*longitude(polygon[i+1]) - ( latitude(polygon[i+1])*longitude(polygon[i]))) <NEW_LINE> i += 1 ...
Returns the y coordinate of the centroid of a polygon, where a is the area of the polygon
625941e0d6c5a102081443d7
def list( self, resource_group_name, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = "2019-12-01" <NEW_LINE> acc...
Gets all the application security groups in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ApplicationSecurityGroupListResu...
625941e0cc0a2c11143dd21b
def getCenter(image,Nim): <NEW_LINE> <INDENT> Ny,Nx,Nc = image.shape; <NEW_LINE> Ny+=Ny%2; <NEW_LINE> Nx+=Nx%2; <NEW_LINE> if Ny>Nim and Nx>Nim: <NEW_LINE> <INDENT> image = image[int(Ny/2-Nim/2):int(Ny/2+Nim/2),int(Nx/2-Nim/2):int(Nx/2+Nim/2),:]; <NEW_LINE> <DEDENT> return image
Takes the central Nim by Nim square from the center of the image.
625941e0cad5886f8bd27362
def normalise_input(user_input): <NEW_LINE> <INDENT> no_punct = remove_punct(user_input).lower() <NEW_LINE> words = filter_words(user_input, skip_words) <NEW_LINE> return words
This function removes all punctuation from the string and converts it to lower case. It then splits the string into a list of words (also removing any extra spaces between words) and further removes all "unimportant" words from the list of words using the filter_words() function. The resulting list of "important" words...
625941e07d847024c06be648
def refine_vocab(myvocab, lemmadata, lemmafilter=False, dehyphenation=True): <NEW_LINE> <INDENT> if len(lemmadata) > 0: <NEW_LINE> <INDENT> changes, deletions = [], [] <NEW_LINE> for token in myvocab: <NEW_LINE> <INDENT> lemma = filter_lemmaform(token, lemmadata, lemmafilter) <NEW_LINE> if lemma is None: <NEW_LINE> <IN...
Refine the word list, currently: lemmatize, regroup forms with/without hyphens, and convert time series to numpy array.
625941e0460517430c394505
def execute(self, app, arguments): <NEW_LINE> <INDENT> return super().execute(app, arguments)
Override execute method. Signatures: pluginlib.Command.execute(arguments) appkit.cron.Command.execute(application, arguments) We need to pass correct arguments to base class in order to adapt it to our application model
625941e0cb5e8a47e48b7e2e
def status(self, message_id): <NEW_LINE> <INDENT> status_request = etree.Element('request') <NEW_LINE> status_request.set('id', message_id) <NEW_LINE> status_request.text = 'status' <NEW_LINE> response = self.__request( SMS_STATUS_URL, etree.tostring(status_request) ) <NEW_LINE> status = self.parse_status_response(resp...
Get status of sent message by its id
625941e0dd821e528d63b52f
@auth.required(Role.admin) <NEW_LINE> def api_get_sysrepo_module_by_name(sysrepo_module_name): <NEW_LINE> <INDENT> module_type = request.args.get('sysrepo_module_type') <NEW_LINE> module = sr_model.get_module_by_name(sysrepo_module_name, module_type) <NEW_LINE> resp = {'name': sysrepo_module_name} <NEW_LINE> resp.updat...
Returns single Sysrepo module
625941e0e76e3b2f99f3ab8f
def sum_by(collection, iteratee=None): <NEW_LINE> <INDENT> return sum(result[0] for result in iteriteratee(collection, iteratee))
Sum each element in `collection`. If iteratee is passed, each element of `collection` is passed through a iteratee before the summation is computed. Args: collection (list|dict|number): Collection to process or first number to add. iteratee (mixed|number, optional): Iteratee applied per iteration or second num...
625941e0ff9c53063f47c57b
def make_specgrid(specfile='syncmd_spec.grid.hd5', fakein='syncmd_final-loz_parsec.fits', distanceModulus=18.96, zsol=0.0142, trimspec=False, grngspec=[1.15e3,3.0e4], use_btsettl=False, btsettl_medres=False): <NEW_LINE> <INDENT> idistanceModulus = distanceModulus * units.mag <NEW_LINE> dmod = idistanceModulus.to(units....
Create spectral grid from FAKE output Parameters ---------- specfile: str file into which save the spectral grid; format = .grid.hd5 fakein: str output file from FAKE used as input
625941e0460517430c394506
@app.route("/login", methods=["POST"]) <NEW_LINE> def process_login(): <NEW_LINE> <INDENT> username = request.form['email'] <NEW_LINE> entered_password = request.form['password'] <NEW_LINE> if username in customers.read_customers_from_file("customers.txt"): <NEW_LINE> <INDENT> customer = customers.get_by_email(username...
Log user into site. Find the user's login credentials located in the 'request.form' dictionary, look up the user, and store them in the session.
625941e0baa26c4b54cb14a5
def inv_mod(self, m): <NEW_LINE> <INDENT> from sympy.ntheory import totient <NEW_LINE> if not self.is_square: <NEW_LINE> <INDENT> raise NonSquareMatrixError() <NEW_LINE> <DEDENT> N = self.cols <NEW_LINE> phi = totient(m) <NEW_LINE> det_K = self.det() <NEW_LINE> if gcd(det_K, m) != 1: <NEW_LINE> <INDENT> raise ValueErro...
Returns the inverse of the matrix `K` (mod `m`), if it exists. Method to find the matrix inverse of `K` (mod `m`) implemented in this function: * Compute `\mathrm{adj}(K) = \mathrm{cof}(K)^t`, the adjoint matrix of `K`. * Compute `r = 1/\mathrm{det}(K) \pmod m`. * `K^{-1} = r\cdot \mathrm{adj}(K) \pmod m`. Example...
625941e026238365f5f0f1fc
def get_album_info(self): <NEW_LINE> <INDENT> url = 'http://download.csdn.net/addalbum/%d' % self.album_id <NEW_LINE> page = netx.get(url, cookies=self.cookies, need_print=False) <NEW_LINE> soup = BeautifulSoup(page, "html.parser") <NEW_LINE> key_list = [ 'title', ('discription', 'textarea'), 'tag', ('categorys', 'sele...
获取专辑信息
625941e063f4b57ef0001498
def plusOne(self, digits): <NEW_LINE> <INDENT> digits_data = "".join(map(str,digits)) <NEW_LINE> return map(int,list(str(int(digits_data) + 1)))
:type digits: List[int] :rtype: List[int]
625941e0a219f33f34628cee
def getblockhash(self, blockheight): <NEW_LINE> <INDENT> for block in self.blocks: <NEW_LINE> <INDENT> if block["height"] == int(blockheight): <NEW_LINE> <INDENT> return block["hash"]
Get block by blockheight. :type blockheight: int :rtype: dict
625941e099cbb53fe6792f6f
def get_grid_mask(self, M, georef): <NEW_LINE> <INDENT> ac = ((self.xy - (georef[0], georef[3])) / (georef[1], georef[5])).astype(np.int32) <NEW_LINE> N = np.logical_and(ac >= (0, 0), ac < ( M.shape[1], M.shape[0])).all(axis=1) <NEW_LINE> ac = ac[N] <NEW_LINE> MM = np.zeros((self.xy.shape[0],), dtype=np.bool) <NEW_LINE...
Get the boolean mask indicating which points lie within a (nrows,ncols) mask. Args: M: A numpy boolean array of shape (nrows,ncols). georef: The GDAL style georefence of the input mask. Returns: A numpy 1d boolean mask.
625941e0a934411ee3751a1e
@docstring._snippet_manager <NEW_LINE> def set_saturation(color, saturation, space='hcl'): <NEW_LINE> <INDENT> def func(channels): <NEW_LINE> <INDENT> channels[1] = saturation <NEW_LINE> return channels <NEW_LINE> <DEDENT> return _transform_color(func, color, space)
Return a color with a different saturation and the same hue and luminance as the input color. Parameters ---------- %(utils.color)s saturation : float, optional The new saturation. Should lie between ``0`` and ``360`` degrees. %(utils.space)s Returns ------- %(utils.hex)s See also -------- set_hue set_luminance ...
625941e0167d2b6e31218f1e
def get_local_branch_by_name(self, branch_name): <NEW_LINE> <INDENT> for branch in self.get_local_branches(): <NEW_LINE> <INDENT> if branch.name == branch_name: <NEW_LINE> <INDENT> return branch <NEW_LINE> <DEDENT> <DEDENT> return None
Get a local Branch tuple from branch name.
625941e0d268445f265b51f8
def test_create_invalid_ingredient_failed(self): <NEW_LINE> <INDENT> payload = {'name': ''} <NEW_LINE> res = self.client.post(INGREDIENTS_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
Test creating invalid-named ingredient failed
625941e03617ad0b5ed68280
def try_to_flip(self, turn: int, spot_col: int, spot_row: int, put_here: list, direction: tuple) -> list: <NEW_LINE> <INDENT> column_direction = direction[0] <NEW_LINE> row_direction = direction[1] <NEW_LINE> try: <NEW_LINE> <INDENT> if spot_col < 0 or spot_row < 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> eli...
Returns list of discs to flip in ONE direction
625941e085dfad0860c3b1e5
def run_tokenization(text): <NEW_LINE> <INDENT> single_observation = text <NEW_LINE> clean_observation, idx_list = clean_string(single_observation) <NEW_LINE> data = tokenization(clean_obs=clean_observation, MAX_SENTENCE_NUM=94, MAX_FEATURES=1182, MAX_WORD_NUM=34) <NEW_LINE> return data
- Presupposition: A text file containing english written words needs to be given. - Result: Returns the transcript in an Array of shape (94, 34). - Effect: None
625941e0ad47b63b2c50a308
def _get_user_id(self, username: str, channel: int = 1) -> str: <NEW_LINE> <INDENT> userlist = self.command(["user", "list", str(channel)], is_safe=True) <NEW_LINE> for line in userlist.splitlines(): <NEW_LINE> <INDENT> words = line.split() <NEW_LINE> if words[0] == "ID": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT...
Get the user ID associated with a given username. Arguments: username (str): The username to search for channel (int): The channel number for the user list; Default: 1 Raises: spicerack.ipmi.IpmiError: if unable to find the given username. Returns: str: the user ID associated with the username
625941e010dbd63aa1bd2f2c
def operator(exp): <NEW_LINE> <INDENT> return head(exp)
(define (operator exp) (car exp))
625941e0956e5f7376d711f5
def add_if(__code): <NEW_LINE> <INDENT> __code = str(__code) <NEW_LINE> term_for_if = logical_term(__code) <NEW_LINE> if term_for_if == "Error": <NEW_LINE> <INDENT> return term_for_if <NEW_LINE> <DEDENT> ast_of_if = ast.If(test=ast.parse(term_for_if).body[0].value, body=[], orelse=[]) <NEW_LINE> ast_of_if.body.append(a...
:param __code: код, куда надо добавить if :return: возвращает if с сгенерированным выражением
625941e02c8b7c6e89b35b48
@user_passes_test(user_can_view_data) <NEW_LINE> def certificates_listing(request,option=None): <NEW_LINE> <INDENT> if option == "csv": <NEW_LINE> <INDENT> return generate_cert_csv(request) <NEW_LINE> <DEDENT> return generate_cert_jtable(request, option)
Generate Certificate Listing template. :param request: Django request object (Required) :type request: :class:`django.http.HttpRequest` :param option: Whether or not we should generate a CSV (yes if option is "csv") :type option: str :returns: :class:`django.http.HttpResponse`
625941e0507cdc57c630706c
def __check_win(self, board: list, player: str) -> bool: <NEW_LINE> <INDENT> for x, y, z in self.__win_combo: <NEW_LINE> <INDENT> if board[x] == board[y] == board[z] == player: <NEW_LINE> <INDENT> return True
Private method for checking win :param board: list of board fields values :param player: sign to test :return: True or False depending of the win state for specified sign
625941e0cb5e8a47e48b7e2f
def conv_bn_leaky(x, identifier, *args, **kwargs): <NEW_LINE> <INDENT> @add_config("conv_bn_leaky", get_config=get_config, wraps=DarknetConv2D) <NEW_LINE> def LeakyConv2D(identifier, *args, **kwargs): <NEW_LINE> <INDENT> return DarknetConv2D(identifier, *args, **kwargs) <NEW_LINE> <DEDENT> x = LeakyConv2D(identifier, *...
Darknet convolutional (without bias) + batch normalization + leaky ReLU :param x: symbolic tensor input :param identifier: identifier for layer name :param args: additional layer configuration :param kwargs: additional named layer configuration :returns: symbolic tensor output after applying convolutional + batch norm...
625941e0009cb60464c63739
def adjust_results4_isadog(results_dic, dogfile): <NEW_LINE> <INDENT> dog_names = dict() <NEW_LINE> with open(dogfile, "r") as infile: <NEW_LINE> <INDENT> for i in infile: <NEW_LINE> <INDENT> if i not in dog_names: <NEW_LINE> <INDENT> i = i.strip('\n') <NEW_LINE> dog_names[i] = 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> f...
Adjusts the results dictionary to determine if classifier correctly classified images 'as a dog' or 'not a dog' especially when not a match. Demonstrates if model architecture correctly classifies dog images even if it gets dog breed wrong (not a match). Parameters: results_dic - Dictionary with 'key' as image file...
625941e05510c4643540f765
def show_path_changes(path_changes): <NEW_LINE> <INDENT> sources, destinations = zip(*path_changes) <NEW_LINE> sources = list(map(util.displayable_path, sources)) <NEW_LINE> destinations = list(map(util.displayable_path, destinations)) <NEW_LINE> col_width = (term_width() - len(' -> ')) // 2 <NEW_LINE> max_width = len(...
Given a list of tuples (source, destination) that indicate the path changes, log the changes as INFO-level output to the beets log. The output is guaranteed to be unicode. Every pair is shown on a single line if the terminal width permits it, else it is split over two lines. E.g., Source -> Destination vs. Source ...
625941e023849d37ff7b3417
def noexit(func): <NEW_LINE> <INDENT> class SystemExitCaught(StandardError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @functools.wraps(func) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return func(*args, **kwargs) <NEW_LINE> <DEDENT> except SystemExit: <NEW_LINE> <INDENT> r...
If argparse or arvados_fuse tries to exit, fail the test instead
625941e0a219f33f34628cef
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pyblog.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you sure ...
Run administrative tasks.
625941e0aad79263cf390dd0
def setUp(self): <NEW_LINE> <INDENT> self.stack = Stack() <NEW_LINE> self.stack.add('a')
Set up a Stack with a single element.
625941e026238365f5f0f1fd
def draw(self, draw_type=None, link_prefix=None): <NEW_LINE> <INDENT> return graph.router(self, draw_type=draw_type, link_prefix=link_prefix)
Generate drawing data. :param str draw_type: [dot|blockdiag|linkdraw]
625941e0bde94217f3683177
def recordChannelInfo( self, agi ): <NEW_LINE> <INDENT> self.uniqueChannelId = agi.variables['agi_uniqueid'] <NEW_LINE> self.currentChannel = currentChannel = agi.variables['agi_channel'] <NEW_LINE> self.callbackChannel = currentChannel.rsplit( '-', 1)[0] <NEW_LINE> df = menu.CollectDigits( soundFile = 'your-account', ...
Records relevant channel information, creates manager watcher
625941e0293b9510aa2c361c
def memoizemethod_noargs(method): <NEW_LINE> <INDENT> cache = weakref.WeakKeyDictionary() <NEW_LINE> @functools.wraps(method) <NEW_LINE> def new_method(self, *args, **kwargs): <NEW_LINE> <INDENT> if self not in cache: <NEW_LINE> <INDENT> cache[self] = method(self, *args, **kwargs) <NEW_LINE> <DEDENT> return cache[self]...
Decorator to cache the result of a method (without arguments) using a weak reference to its object
625941e024f1403a92600eed
def filter_refs(refs: Dict[bytes, bytes]) -> Dict[bytes, HexBytes]: <NEW_LINE> <INDENT> return { name: HexBytes(target) for name, target in refs.items() if not ignore_branch_name(name) }
Filter the refs dictionary using the policy set in `ignore_branch_name`
625941e050812a4eaa59c6a8
def quantify_field_dict(field_dict, precision=None, date_precision=None, cleaner=str.strip): <NEW_LINE> <INDENT> if cleaner: <NEW_LINE> <INDENT> d = clean_field_dict(field_dict, cleaner=cleaner) <NEW_LINE> <DEDENT> for k, v in viewitems(d): <NEW_LINE> <INDENT> if isinstance(d[k], datetime.datetime): <NEW_LINE> <INDENT>...
Convert strings and datetime objects in the values of a dict into float/int/long, if possible Arguments: field_dict (dict): The dict to have any values (not keys) that are strings "quantified" precision (int): Number of digits of precision to enforce cleaner: A string cleaner to apply to all string before FIXM...
625941e0a05bb46b383ecba9
def _check_access(request, func, *args, **kwargs): <NEW_LINE> <INDENT> if request.META.get('HTTP_AUTHORIZATION'): <NEW_LINE> <INDENT> user = base_auth(request.META['HTTP_AUTHORIZATION']) <NEW_LINE> if user: <NEW_LINE> <INDENT> repo = Repository.objects.get(owner=user, name=kwargs['repository']) <NEW_LINE> access = Repo...
Checks user's authentication and access to repository.
625941e050485f2cf553d125
def noiseErr(n_ph, n_r, n_s, n_samp, lmda): <NEW_LINE> <INDENT> import numpy as np <NEW_LINE> numerator = np.pi**2 * n_r**2 * n_s**4 <NEW_LINE> denominator = 3 * n_ph**2 * n_samp**2 <NEW_LINE> alphan_squared = numerator/denominator <NEW_LINE> wfe = np.sqrt(alphan_squared)/np.pi/2.*lmda*1e9 <NEW_LINE> return wfe
compute RON-related phase error (nm) from S. Thomas 2005 paper Eq. (12) used when the centroid algorithm is CoG
625941e076d4e153a657eebc
def get_propagator(name): <NEW_LINE> <INDENT> from .j2 import J2 <NEW_LINE> from .kepler import Kepler <NEW_LINE> from .keplernum import KeplerNum <NEW_LINE> from .none import NonePropagator <NEW_LINE> from .sgp4 import Sgp4 <NEW_LINE> from .sgp4beta import Sgp4Beta <NEW_LINE> scope = { "J2": J2, "Kepler": Kepler, "Kep...
Retrieve a named propagator Args: name (str): Name of the desired propagator Return: Propagator class
625941e0e64d504609d74bca
def __safe_handler_callback(self, handler, method_name, *args, **kwargs): <NEW_LINE> <INDENT> if handler is None or method_name is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> only_boolean = kwargs.pop('only_boolean', False) <NEW_LINE> none_as_true = kwargs.pop('none_as_true', False) <NEW_LINE> try: <NEW_L...
Calls the given method with the given arguments in the given handler. Logs exceptions, but doesn't propagate them. Special arguments can be given in kwargs: * 'none_as_true': If set to True and the method returned None or doesn't exist, the result is considered as True. If set to F...
625941e05fcc89381b1e1a4b
def forward_encoder(self, x, do_emb=True): <NEW_LINE> <INDENT> if do_emb: <NEW_LINE> <INDENT> assert_check(x, [-1, self.n_len], torch.long) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert_check(x, [-1, self.n_len, self.d_emb], torch.float) <NEW_LINE> <DEDENT> if do_emb: <NEW_LINE> <INDENT> x_emb = self.x_emb(x) <N...
Encoder step, emulating z ~ E(x) = q_E(z|x) :param x: (n_batch, n_len) of longs or (n_batch, n_len, d_emb) of floats, input sentence x :param do_emb: whether do embedding for x or not :return: (n_batch, d_z) of floats, sample of latent vector z :return: float, kl term component of loss
625941e02eb69b55b151cc3e
def test_post_answer_empty_body(self): <NEW_LINE> <INDENT> response = self.client.post("/api/v1/questions/1/answers", data=json.dumps(dict(answer_body=" ")), content_type="application/json") <NEW_LINE> self.assertEqual(response.status_code, 401) <NEW_LINE> response_msg = json.loads(response.data.decode("UTF-8")) <NEW_L...
Tests user cannnot answer a question without body
625941e0d58c6744b4257fe8
def _vars(self, t: int) -> AnalysisVars: <NEW_LINE> <INDENT> return AnalysisVars( model_prior=self.model_prior, parameter_priors=self.parameter_priors, model_perturbation_kernel=self.model_perturbation_kernel, transitions=self.transitions, models=self.models, summary_statistics=self.summary_statistics, x_0=self.x_0, di...
Create a dictionary of analysis variables of interest. These variables are passed to the sampler, as some need to create simulation settings themselves.
625941e07d43ff24873a302d
def find_best(results, per='sample', score='tra_score', k=3, lower_is_better=True): <NEW_LINE> <INDENT> drop = list(set(results.keys()).intersection(set(nonrelevant_keys))) <NEW_LINE> results = results.drop(columns=drop) <NEW_LINE> results = results.replace(np.nan, NAN_PLACEHOLDER) <NEW_LINE> results = results.sort_val...
Find the best configurations for each of the given samples in one experiment.
625941e0d58c6744b4257fe9
def access_required(config=None): <NEW_LINE> <INDENT> def _access_required(http_method_handler): <NEW_LINE> <INDENT> def secure_http_method_handler(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.__provider_config__.authentication: <NEW_LINE> <INDENT> _message = "Service available to authenticated users only, n...
Authenticates a HTTP method handler based on a custom set of arguments
625941e0656771135c3ebbfd
def get_corr_drug_random_genes(top_k, emb_node_lst): <NEW_LINE> <INDENT> gene_expr_mat = get_gene_expr_mat() <NEW_LINE> embedding_and_expression_genes = list(set(emb_node_lst ).intersection(gene_expr_mat.keys())) <NEW_LINE> random.shuffle(embedding_and_expression_genes) <NEW_LINE> return embedding_and_expression_genes[...
Returns a dictionary where each key is a drug, and each value is another dictionary d_2, where each key is a gene, and each value is a p-value corresponding to the correlation between the drug and the gene. We pick top_k random genes for each drug.
625941e0bde94217f3683178