code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def extract_reactions(self) -> PartialPost: <NEW_LINE> <INDENT> url = self.post.get('post_url') <NEW_LINE> post_id = self.post.get('post_id') <NEW_LINE> if url: <NEW_LINE> <INDENT> w3_fb_url = utils.urlparse(url)._replace(netloc='www.facebook.com').geturl() <NEW_LINE> resp = self.request(w3_fb_url) <NEW_LINE> for item ...
Fetch share and reactions information with a existing post obtained by `get_posts`. Return a merged post that has some new fields including `reactions`, `w3_fb_url`, `fetched_time`, and reactions fields `LIKE`, `ANGER`, `SORRY`, `WOW`, `LOVE`, `HAHA` if exist. Note that this method will raise one http request per post,...
625941e299fddb7c1c9de762
def test_str(self): <NEW_LINE> <INDENT> pi = progress.TrackerItem("testitem") <NEW_LINE> pi.items = 10 <NEW_LINE> str(pi)
Test str() of a TrackerItem.
625941e22c8b7c6e89b35b90
def make_melon_type_lookup(melon_types): <NEW_LINE> <INDENT> melons_dict = {} <NEW_LINE> for melon in melon_types: <NEW_LINE> <INDENT> melons_dict[melon.code] = melon <NEW_LINE> <DEDENT> return melons_dict
Takes a list of MelonTypes and returns a dictionary of melon type by code.
625941e282261d6c526ab878
def noun_phrases_matching_endings(self, document): <NEW_LINE> <INDENT> lines = document.split('\n') <NEW_LINE> phrase_start = 0 <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> if not self.only_bulleted_lines or is_bulleted(line): <NEW_LINE> <INDENT> for noun_phrase, context in noun_phrases_in_line_with_context(line):...
From the given document, generate noun phrases ending with one of the configured terms Args: document (string) A raw text document, such as a job posting Yields: tuples, each with: - a noun phrase - the context of the noun phrase (currently defined as the surrounding sentence) - the in...
625941e2925a0f43d254a24d
def __init__(self): <NEW_LINE> <INDENT> pygame.sprite.Sprite.__init__(self) <NEW_LINE> self.image =pygame.image.load('minigalli.png') <NEW_LINE> self.rect = self.image.get_rect()
Constructor function
625941e216aa5153ce36284b
def json_dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, sort_keys=False, **kw): <NEW_LINE> <INDENT> return json.dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, encoding, def...
Exactly the same as json.dumps.
625941e25510c4643540f7ad
def get_drivId(self): <NEW_LINE> <INDENT> return self.__drivId
getter for driver's id :return: int driver's id
625941e24428ac0f6e5babc8
def neighbors(kmer, d): <NEW_LINE> <INDENT> kmers = set((kmer,)) <NEW_LINE> processed = set() <NEW_LINE> for _ in range(1, d + 1): <NEW_LINE> <INDENT> for item in kmers: <NEW_LINE> <INDENT> if item in processed: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> imm_neighbors = immediate_neighbors(item) <NEW_LINE> kmers ...
Returns the d-neighbors of a given k-mer. :param kmer: The k-mer, a DNA string. :param d: The value for d paramter, a non-negative integer. :return: All the d-neighbots of the k-mer, a list of strings.
625941e276d4e153a657ef05
def target_has_classes(self, document): <NEW_LINE> <INDENT> return HasClasses(self._target_flowable(document))
Filter selection on a set of classes of the target flowable
625941e22c8b7c6e89b35b91
def findMinArrowShots(self, points): <NEW_LINE> <INDENT> end, k = None, 0 <NEW_LINE> points.sort(key=lambda points: points[1]) <NEW_LINE> for point in points: <NEW_LINE> <INDENT> if end is None or point[0]>end: <NEW_LINE> <INDENT> k+=1 <NEW_LINE> end = point[1] <NEW_LINE> <DEDENT> <DEDENT> return k
:type points: List[List[int]] :rtype: int
625941e28c0ade5d55d3ed91
def complex_polar(z : complex): <NEW_LINE> <INDENT> a = z.real;b= z.imag <NEW_LINE> r = (a**2 + b**2)**(1/2) <NEW_LINE> theta = atan(b / a,iterations=50) <NEW_LINE> if a < 0: <NEW_LINE> <INDENT> theta += pi <NEW_LINE> <DEDENT> return [r,theta]
Returns the the mangitude of the Vector of a complex number z and the angle it forms in the x-axis z : complex => [r,theta] from : r * (cos(x) + i*sin(x))
625941e2ec188e330fd5ab6b
def apply_firewall(self, prechange_callback=None, networks=None, allow_empty_ruleset=False): <NEW_LINE> <INDENT> self._rules_to_delete = [] <NEW_LINE> self._rules_to_insert = [] <NEW_LINE> self._rules_to_update = [] <NEW_LINE> if not self.current_rules: <NEW_LINE> <INDENT> self.refresh_current_rules() <NEW_LINE> <DEDEN...
Enforce the expected firewall rules on the project. Args: prechange_callback (function): An optional callback function that will get called if the firewall policy for a project does not match the expected policy, before any changes are actually applied. If the callback returns False then no...
625941e25fdd1c0f98dc0608
def create_empty_dirstate(self): <NEW_LINE> <INDENT> state = dirstate.DirState.initialize('dirstate') <NEW_LINE> return state
Return a locked but empty dirstate
625941e2b545ff76a89141e8
def create(self, parent): <NEW_LINE> <INDENT> super().create(parent) <NEW_LINE> self.ui.history = UndoHistory() <NEW_LINE> self._last_save = 0
Create and set the toolkit-specific contents of the editor.
625941e2d4950a0f3b08c71c
def gtk_alignment(alignment): <NEW_LINE> <INDENT> return { LEFT_ALIGNED: (0.0, 0.5), RIGHT_ALIGNED: (1.0, 0.5), CENTER_ALIGNED: (0.5, 0.5), JUSTIFIED_ALIGNED: (0.0, 0.0), NATURAL_ALIGNED: (0.0, 0.5), }[alignment]
Convert Toga alignments in to arguments compatible with Gtk.set_alignment
625941e26fece00bbac2db16
def timeit(function, parameter): <NEW_LINE> <INDENT> start = time.time() <NEW_LINE> result = function(parameter) <NEW_LINE> end = time.time() <NEW_LINE> runtime = end-start <NEW_LINE> print('The runtime of {} is {}'.format(function, runtime)) <NEW_LINE> return result
A function used for testing speed performance of a function. Input is of the form: variable = timeit(function, parameter)
625941e2287bf620b61d3e34
def test_maximum04(self): <NEW_LINE> <INDENT> labels = numpy.array([[1, 2], [2, 3]]) <NEW_LINE> for type in self.types: <NEW_LINE> <INDENT> input = numpy.array([[1, 2], [3, 4]], type) <NEW_LINE> output = ndimage.maximum(input, labels = labels, index = [2, 3, 8]) <NEW_LINE> self.failUnless(numpy.all(output == [3.0, 4.0,...
maximum 4
625941e2d53ae8145f87a63b
def test_kinight_threatening_zone_boundary_1_7(self): <NEW_LINE> <INDENT> kinight = chess.Kinight((1, 7)) <NEW_LINE> expected = [ (3, 6), (0, 5), (2, 5) ] <NEW_LINE> self.assertEqual( sorted(kinight.threatening_zone(8)), sorted(expected) )
Kinight Boundary Testing
625941e2009cb60464c63782
def min(self) -> "ArrayMin": <NEW_LINE> <INDENT> return ArrayMin(self)
Minimum value.
625941e230c21e258bdfa873
def forward(self, x): <NEW_LINE> <INDENT> if len(x.shape) > 1: <NEW_LINE> <INDENT> self.mu_batch = x[:, 0] <NEW_LINE> self.sigma_batch = F.softplus(x[:, 1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.mu = x[0] <NEW_LINE> self.distr = Normal(self.mu, self.sigma) <NEW_LINE> <DEDENT> return self.distr
Takes input x as new distribution parameters
625941e2099cdd3c635f102c
def izip_longest(*iterables, **kwargs): <NEW_LINE> <INDENT> fillvalue = kwargs.get("fillvalue") <NEW_LINE> def sentinel(counter=([fillvalue] * (len(iterables) - 1)).pop): <NEW_LINE> <INDENT> yield counter() <NEW_LINE> <DEDENT> fillers = itertools.repeat(fillvalue) <NEW_LINE> iters = [chain(it, sentinel(), fillers) for ...
Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with `fillvalue`. Iteration continues until the longest iterable is exhausted. If one of the iterables is potentially infinite, then the :func:`izip_longest` function should be wrap...
625941e2d8ef3951e3243911
def get_createur(self, objet): <NEW_LINE> <INDENT> return objet.createur and objet.createur.nom or "inconnu"
Retourne le créateur
625941e2a17c0f6771cbe422
def rest_show_syslog(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> t = test.Test() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> c = t.controller('master') <NEW_LINE> try: <NEW_LINE> <INDENT> url = '/rest/v1/model/syslog-server/' <NEW_LINE> helpers.log(...
Execute CLI command "show syslog" and return o/p Returns dictionary of o/p
625941e25fc7496912cc3d51
def spider_closing(): <NEW_LINE> <INDENT> log.msg("Closing reactor", level=log.INFO) <NEW_LINE> reactor.stop()
Activates on spider closed signal
625941e2462c4b4f79d1daa2
@main.route('/posts/<int:id>', methods=['GET', 'POST']) <NEW_LINE> def post(id): <NEW_LINE> <INDENT> post = Post.query.get_or_404(id) <NEW_LINE> form = CommentForm() <NEW_LINE> if form.validate_on_submit(): <NEW_LINE> <INDENT> comment = Comment(body=form.body.data, post=post, author=current_user._get_current_object()) ...
单独文章页 :param id: :return:
625941e2be8e80087fb21010
def singleton(cls): <NEW_LINE> <INDENT> instances = {} <NEW_LINE> def get_instance(): <NEW_LINE> <INDENT> if cls not in instances: <NEW_LINE> <INDENT> instances[cls] = cls() <NEW_LINE> <DEDENT> return instances[cls] <NEW_LINE> <DEDENT> return get_instance
decorator for Singleton Pattern
625941e23c8af77a43ae3b77
def ResampleImage3D(imagedata, value): <NEW_LINE> <INDENT> spacing = imagedata.GetSpacing() <NEW_LINE> extent = imagedata.GetExtent() <NEW_LINE> size = imagedata.GetDimensions() <NEW_LINE> width = float(size[0]) <NEW_LINE> height = float(size[1] / value) <NEW_LINE> resolution = (height / (extent[1] - extent[0]) + 1) * ...
Resample vtkImageData matrix.
625941e224f1403a92600f36
def set_mail_forwarding(self, user_id, fwd_email): <NEW_LINE> <INDENT> if not self.is_forwarding_address(user_id=user_id, fwd_email=fwd_email): <NEW_LINE> <INDENT> self.create_forwarding_address(user_id=user_id, fwd_email=fwd_email) <NEW_LINE> <DEDENT> forwarding_settings = { 'emailAddress': fwd_email, 'enabled': True,...
Enables mail forwarding for the user. :param user_id: userId :param fwd_email: emailAddress :return: bool
625941e207d97122c4178c67
def test_option_str(): <NEW_LINE> <INDENT> option = mommy.prepare(Option) <NEW_LINE> assert str(option) == option.name
Test string representation for Option object.
625941e23eb6a72ae02ec8ba
def get_devices(**query): <NEW_LINE> <INDENT> devices = [] <NEW_LINE> for dev in get_all_devices(): <NEW_LINE> <INDENT> for (name, value) in query.items(): <NEW_LINE> <INDENT> if hasattr(dev, name): <NEW_LINE> <INDENT> if getattr(dev, name) != value: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else:...
Somewhat experimental function to get device info as a list of Device objects.
625941e25510c4643540f7ae
def __init__(self, id=None, name=None, brand=None): <NEW_LINE> <INDENT> self._id = None <NEW_LINE> self._name = None <NEW_LINE> self._brand = None <NEW_LINE> self.discriminator = None <NEW_LINE> if id is not None: <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <DEDENT> if name is not None: <NEW_LINE> <INDENT> self.name = ...
VehicleModelListList - a model defined in Swagger
625941e22eb69b55b151cc88
def div_(input0, input1, output): <NEW_LINE> <INDENT> return definitions.Instruction(definitions.DIV, input0, input1, output)
Performs an unsigned division on the two input operands. The first input operand is the dividend, the second input operand is the divisor. The two input operands can be either registers or literals while the output operand must be a register.
625941e2baa26c4b54cb14ef
def get_article_placeholders(self, article): <NEW_LINE> <INDENT> placeholders_search_list = getattr(settings, 'CMS_ARTICLES_PLACEHOLDERS_SEARCH_LIST', {}) <NEW_LINE> included = placeholders_search_list.get('include', []) <NEW_LINE> excluded = placeholders_search_list.get('exclude', []) <NEW_LINE> diff = set(included) -...
In the project settings set up the variable CMS_ARTICLES_PLACEHOLDERS_SEARCH_LIST = { 'include': [ 'slot1', 'slot2', etc. ], 'exclude': [ 'slot3', 'slot4', etc. ], } or leave it empty CMS_ARTICLES_PLACEHOLDERS_SEARCH_LIST = {}
625941e22ae34c7f2600d504
def original_solution(n): <NEW_LINE> <INDENT> if n == 1: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> a, b = 0, 1 <NEW_LINE> for i in range(1, n - 1): <NEW_LINE> <INDENT> a, b = b, (a + b) <NEW_LINE> <DEDENT> return b
Return the nth fibonacci number.
625941e29b70327d1c4e11aa
def getMeasureField(self, *args): <NEW_LINE> <INDENT> return _MEDCouplingRemapper.MEDCouplingFieldDiscretizationGaussNE_getMeasureField(self, *args)
getMeasureField(self, MEDCouplingMesh mesh, bool isAbs) -> MEDCouplingFieldDouble 1
625941e292d797404e30455f
def setup(tel, lib_name): <NEW_LINE> <INDENT> command,error_msg = gen_command(lib_name) <NEW_LINE> if command: <NEW_LINE> <INDENT> info = '' <NEW_LINE> p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) <NEW_LINE> for out in p.stdout: <NEW_LINE> <INDENT> out = out.decode("utf-8...
开始安装
625941e28e05c05ec3eea74b
def descending(self, qfield): <NEW_LINE> <INDENT> return self.__sort(qfield, DESCENDING)
Sort the result based on ``qfield`` in ascending order. These calls can be chained to sort by multiple fields. :param qfield: Instance of :class:``mongoalchemy.query.QueryField`` specifying which field to sort by.
625941e230c21e258bdfa874
def rank(self, key): <NEW_LINE> <INDENT> node = self.__find_node(key) <NEW_LINE> if node is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> index = node.left.size if node.left else 0 <NEW_LINE> while node.parent is not None: <NEW_LINE> <INDENT> if node.parent.left is not node: <NEW_LINE> <INDENT> if node.pare...
Finds the index of the node mapped by the provided key. :param key: The key of the node to fetch the index of. :return: The index if this tree contains the key, otherwise None.
625941e2d7e4931a7ee9e2f2
def affine_backward(dout, cache): <NEW_LINE> <INDENT> x, w, b = cache <NEW_LINE> dx, dw, db = None, None, None <NEW_LINE> N = x.shape[0] <NEW_LINE> xx = np.reshape(x,(N,-1)) <NEW_LINE> dx = dout.dot(w.T).reshape(x.shape) <NEW_LINE> dw = xx.T.dot(dout) <NEW_LINE> db = np.sum(dout, axis=0) <NEW_LINE> return dx, dw, db
Computes the backward pass for an affine layer. Inputs: - dout: Upstream derivative, of shape (N, M) - cache: Tuple of: - x: Input data, of shape (N, d_1, ... d_k) - w: Weights, of shape (D, M) - b: A numpy array of biases, of shape (M, Returns a tuple of: - dx: Gradient with respect to x, of shape (N, d1, ...,...
625941e24e4d5625662d47a6
def get_list(data_dict, key, optional=False): <NEW_LINE> <INDENT> if key not in data_dict: <NEW_LINE> <INDENT> if optional: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Key "{}" not present in data'.format(key)) <NEW_LINE> <DEDENT> <DEDENT> l = data_dict[key] <NEW_LINE...
Extract a list from a data_dict and do a bit of error checking
625941e2be383301e01b5852
def _build(self, inputs): <NEW_LINE> <INDENT> self._input_shape = tuple(inputs.get_shape().as_list()) <NEW_LINE> if len(self._input_shape) != 4: <NEW_LINE> <INDENT> raise base.IncompatibleShapeError( "Input Tensor must have shape (batch_size, input_height, " "input_width, input_channels)") <NEW_LINE> <DEDENT> if self._...
Connects the module into the graph, with input Tensor `inputs`. Args: inputs: A 4D Tensor of shape: [batch_size, input_height, input_width, input_channels]. Returns: A 4D Tensor of shape: [batch_size, output_height, output_width, output_channels]. Raises: ValueError: If connecting the module into t...
625941e25e10d32532c5f2f9
def _handle_message(self, sock, msg): <NEW_LINE> <INDENT> logging.debug("received: {0}".format(msg)) <NEW_LINE> msg_type = msg['type'] <NEW_LINE> if msg_type == 'REG': <NEW_LINE> <INDENT> self.reservations.add(msg['data']) <NEW_LINE> MessageSocket.send(self, sock, 'OK') <NEW_LINE> <DEDENT> elif msg_type == 'QUERY': <NE...
Args: sock: msg: Returns:
625941e23cc13d1c6d3c774c
def att_ctl_debug_encode(self, head_setpt, head_rate_setpt, head_ctl_p, head_ctl_d, pitch_setpt, pitch_rate_setpt, roll_setpt, roll_rate_setpt): <NEW_LINE> <INDENT> msg = MAVLink_att_ctl_debug_message(head_setpt, head_rate_setpt, head_ctl_p, head_ctl_d, pitch_setpt, pitch_rate_setpt, roll_setpt, roll_rate_setpt) <NEW_L...
attitude controller status head_setpt : heading setpoint (float) head_rate_setpt : heading rate setpoint (float) head_ctl_p : (float) head_ctl_d : (float) pitch_setpt : (float) pitch_rate_setpt : (float) roll_setpt : (flo...
625941e2d4950a0f3b08c71d
def test_should_end_task(self): <NEW_LINE> <INDENT> task_config = self.task_config <NEW_LINE> task_container = self.task_container <NEW_LINE> task = self.task <NEW_LINE> msg = "Task should not be ended because the ending state does not match container state" <NEW_LINE> self.assertFalse(task_config.should_end_task(task_...
Test different cases for the 'should_end_task' method.
625941e3b7558d58953c52e0
def _lock(self, filename): <NEW_LINE> <INDENT> lckfile = open(filename + '.lck', 'w') <NEW_LINE> fcntl.flock(lckfile.fileno(), fcntl.LOCK_EX) <NEW_LINE> return lckfile
Get a lock for the index file.
625941e3f9cc0f698b1409cc
def drawBox(self,line,color): <NEW_LINE> <INDENT> p1 = line.getP1() <NEW_LINE> p2 = line.getP2() <NEW_LINE> numBoxs = 0 <NEW_LINE> if p1.getX() == p2.getX(): <NEW_LINE> <INDENT> right,left = self.vertical(line) <NEW_LINE> if right != False: <NEW_LINE> <INDENT> right.setFill(color) <NEW_LINE> right.draw(self.win) <NEW_L...
Checks if the corrisponding lines are in the self.lines list to create a box, and if so then it draws a box between the lines.
625941e366673b3332b92465
def __repr__(self): <NEW_LINE> <INDENT> return ('Fraction(%s, %s)' % (self._numerator, self._denominator))
repr(self)
625941e356ac1b37e626459d
def _zoom_image(self, image_id): <NEW_LINE> <INDENT> if image_id in self.__visible_items: <NEW_LINE> <INDENT> self._snap_to_ratio(image_id, self._tiles[image_id].get_ratio()) <NEW_LINE> self._handle_resize_complete(image_id)
Resizes the image
625941e3a4f1c619b28b0404
def fromline(self, line): <NEW_LINE> <INDENT> if WHITESPACES_RE.sub('', line) == '': <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> cols = WHITESPACES_RE.split(line) <NEW_LINE> if len(cols) < 4: <NEW_LINE> <INDENT> msg = "Rule {0} has too few columns." <NEW_LINE> raise PgHbaValueError(msg.format(line)) <NEW_LINE> <DEDE...
split into 'type', 'db', 'usr', 'src', 'mask', 'method', 'options' cols
625941e3442bda511e8be7e7
def save_all(self): <NEW_LINE> <INDENT> location = self.location <NEW_LINE> weather = self.weather <NEW_LINE> location.save() <NEW_LINE> weather.save() <NEW_LINE> self.location = location <NEW_LINE> self.weather = weather <NEW_LINE> self.save()
Saves this model along with all related ones. :return: None
625941e33eb6a72ae02ec8bb
def getOptimalLineup(playerData, salaryCap): <NEW_LINE> <INDENT> current_team_salary = 0 <NEW_LINE> constraints = { 'PG': 2, 'SG': 2, 'SF': 2, 'PF': 2, 'C': 1 } <NEW_LINE> counts = { 'PG':0, 'SG':0, 'SF':0, 'PF':0, 'C':0 } <NEW_LINE> playerData.sort(key=lambda x: x["value"], reverse=True) <NEW_LINE> team = [] <NEW_LINE...
Takes in finalProjs playerData array of objs + salaryCap int Finds optimal lineup Returns optimal lineup
625941e3090684286d50f0be
def test_str_success(self): <NEW_LINE> <INDENT> result = base.VerificationResult({'status': 'okay', 'email': 'a@example.com'}) <NEW_LINE> eq_(six.text_type(result), '<VerificationResult Success email=a@example.com>') <NEW_LINE> result = base.VerificationResult({'status': 'okay'}) <NEW_LINE> eq_(six.text_type(result), '...
If the result is successful, include 'Success' and the email in the string.
625941e3507cdc57c63070b7
def raw(self, raw_method, raw_uri, **kwargs): <NEW_LINE> <INDENT> headers = kwargs.setdefault('headers', {}) <NEW_LINE> headers['X-Kloudless-Raw-Method'] = raw_method <NEW_LINE> headers['X-Kloudless-Raw-URI'] = raw_uri <NEW_LINE> return self.post('raw', get_raw_response=True, **kwargs)
Method for `Pass-Through API <https://developers.kloudless.com/docs/ latest/core#header-pass-through-api-1>`_ :param str raw_method: The value stand for ``X-Kloudless-Raw-Method`` header :param raw_uri: The value stand for ``X-Kloudless-Raw-URI`` header :param kwargs: kwargs passed to :func:`kloudless.client.C...
625941e37c178a314d6ef839
def _xmodem_putc(self, data, timeout=1): <NEW_LINE> <INDENT> self.logger.debug('XMODEM PUTC: {}'.format(repr(data))) <NEW_LINE> self.console.write(data) <NEW_LINE> return len(data)
called by the xmodem.XMODEM instance to write protocol data to the console
625941e3d18da76e235328ae
def test_migration_latest_version(self): <NEW_LINE> <INDENT> uninitToThree = Migration(Uninitialized, 3, "foo", "/path/to/foo") <NEW_LINE> twoToThree = Migration(2, 3, "foo", "/path/to/foo") <NEW_LINE> uninitToTwo = Migration(Uninitialized, 2, "foo", "/path/to/foo") <NEW_LINE> class TestMigMgr(SchemaMigMgr): <NEW_LINE>...
Verify the Migration less than operator works as expected by verifying that the max version gets set correctly.
625941e3b57a9660fec33c5d
def KLP_Revoke_Permissions(request, permissionType): <NEW_LINE> <INDENT> KLP_user_Perm(request.user, 'Users', None) <NEW_LINE> user_id = request.POST.get('userId') <NEW_LINE> opStatus = 'success' <NEW_LINE> try: <NEW_LINE> <INDENT> if permissionType == 'permissions': <NEW_LINE> <INDENT> userObj = User.objects.get(pk=us...
This method is used to revoke user permissions
625941e376d4e153a657ef06
def batch_receive_message(self, num_of_msg, polling_wait_seconds=None): <NEW_LINE> <INDENT> params = {'queueName': self.queue_name, 'numOfMsg': num_of_msg} <NEW_LINE> if polling_wait_seconds is not None: <NEW_LINE> <INDENT> params['UserpollingWaitSeconds'] = polling_wait_seconds <NEW_LINE> params['pollingWaitSeconds'] ...
批量消费消息 @type num_of_msg: int @param num_of_msg: 本次请求最多获取的消息条数 @type polling_wait_seconds: int @param polling_wait_seconds: 本次请求的长轮询时间,单位:秒 @rtype: list of Message object @return 多条消息的属性,包含消息的基本属性、临时句柄
625941e3bd1bec0571d90a03
def _get_partitioned_variable(self, var_store, name, shape=None, dtype=None, initializer=None, regularizer=None, trainable=None, collections=None, caching_device=None, partitioner=None, validate_shape=True, use_resource=None, constraint=None, synchronization=VariableSynchronization.AUTO, aggregation=VariableAggregation...
Gets an existing variable with this name or create a new one.
625941e3bf627c535bc135a4
def set_device_map(self, to: str, device_map: Dict[DeviceType, DeviceType]): <NEW_LINE> <INDENT> full_device_map = _to_device_map(device_map) <NEW_LINE> curr_device_maps = super().device_maps <NEW_LINE> if to in curr_device_maps: <NEW_LINE> <INDENT> for k, v in full_device_map.items(): <NEW_LINE> <INDENT> if k in curr_...
Set device mapping between each RPC caller and callee pair. This function can be called multiple times to incrementally add device placement configurations. Args: worker_name (str): Callee name. device_map (Dict of int, str, or torch.device): Device placement mappings from this worker to the callee. Th...
625941e36fece00bbac2db17
def resolveReferences(self): <NEW_LINE> <INDENT> pass
Replaces the reference to an object by its value if there are references not resolved. Ex. /Length 3 0 R @return: A tuple (status,statusContent), where statusContent is empty in case status = 0 or an error message in case status = -1
625941e3d164cc6175783123
def calculate_accuracy(pred_vector, label_vector): <NEW_LINE> <INDENT> n = len(pred_vector) <NEW_LINE> TP = sum([(label_vector[i] == 1) and (pred_vector[i] == 1) for i in range(n)]) <NEW_LINE> TN = sum([(label_vector[i] == 0) and (pred_vector[i] == 0) for i in range(n)]) <NEW_LINE> if n > 0: <NEW_LINE> <INDENT> result ...
Calculate the accuracy of the predicted values.
625941e3a05bb46b383ecbf3
def __repr__(self): <NEW_LINE> <INDENT> itgs = ", ".join(repr(itg) for itg in self.integrals()) <NEW_LINE> r = "Form([" + itgs + "])" <NEW_LINE> return r
Compute repr string of form. This can be huge for complicated forms.
625941e376e4537e8c351a4a
def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return ParcelProtectionQuoteRequestShipmentInfoConsigneeInfo( address = pbshipping.models.parcel_protection_quote_request_shipment_info_shipper_info_address.ParcelProtectionQuoteRequest_shipmentInfo_shipperInfo_addr...
Test ParcelProtectionQuoteRequestShipmentInfoConsigneeInfo include_option is a boolean, when False only required params are included, when True both required and optional params are included
625941e316aa5153ce36284c
def read_world_data(N=10, fn='../data/2001rank.txt'): <NEW_LINE> <INDENT> gdp, labels= [], [] <NEW_LINE> for i, row in enumerate(csv.reader(open(fn), delimiter='\t')): <NEW_LINE> <INDENT> if i > 3: <NEW_LINE> <INDENT> gdp_value = re.sub(r'[\$, ]', '', row[2]) <NEW_LINE> gdp.append(float(gdp_value)/1e9) <NEW_LINE> label...
A function to read CIA World Factbook file. N is the number of countries to process. See https://www.cia.gov/library/publications/the-world-factbook/ rankorder/2001rank.txt.
625941e37b25080760e3982b
def get_frame_assignments(trajnames, n_cross_val_sets=5): <NEW_LINE> <INDENT> set_assignment = [] <NEW_LINE> traj_n_frames = [] <NEW_LINE> for n in range(len(trajnames)): <NEW_LINE> <INDENT> length = 0 <NEW_LINE> for chunk in md.iterload(trajnames[n], top=topfile, chunk=1000): <NEW_LINE> <INDENT> length += chunk.n_fram...
Randomly assign trajectory frames to sets
625941e3a8ecb033257d34a0
def test_add_new_method_does_not_add_existing_user(self): <NEW_LINE> <INDENT> self.new_user = UserAccount() <NEW_LINE> self.new_user.add_new("mel", "mel@gmail.com", "123") <NEW_LINE> result = self.new_user.add_new("mel", "mel@gmail.com", "123") <NEW_LINE> self.assertEqual(result, "exists")
test whether a user gets a message if they already have an account
625941e31b99ca400220ae87
def get_sequence(self, index=0): <NEW_LINE> <INDENT> fstr= self.indv_block(st=self.read) <NEW_LINE> fstr=fstr[index] <NEW_LINE> fstr= fstr.splitlines() <NEW_LINE> for f in fstr: <NEW_LINE> <INDENT> if f.startswith('>'): <NEW_LINE> <INDENT> fstr.remove(f) <NEW_LINE> <DEDENT> <DEDENT> fstr= "".join(fstr) <NEW_LINE> retur...
Given a fasta file, return the sequence at the given index Args: index(int): For a fasta file with muyltiple proteins, is the zero indexed position of the desired protein within the file Returns: The sequence of the specified protein, as a single string, with newline characters removed.
625941e3097d151d1a22322c
def dictvec(): <NEW_LINE> <INDENT> dict = DictVectorizer() <NEW_LINE> data = dict.fit_transform([{"city":"北京","temperature":100},{"city":"上海","temperature":60},{"city":"深圳","temperature":30}]) <NEW_LINE> print(dict.get_feature_names()) <NEW_LINE> print(data) <NEW_LINE> return None
字典数据抽取 :return:None
625941e392d797404e304560
def get_sign(self): <NEW_LINE> <INDENT> if max(self.direction.to_list()) == 1: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return -1
Return the current sign of the backtracking head's direction.
625941e326238365f5f0f248
def myfunction(): <NEW_LINE> <INDENT> pass
Dummy metric function.
625941e301c39578d7e75210
def get_position_of_all_letters(self,): <NEW_LINE> <INDENT> position_list = [] <NEW_LINE> for x in range(len(self.spaces)): <NEW_LINE> <INDENT> for y in range(len(self.spaces[0])): <NEW_LINE> <INDENT> position = Position(x, y) <NEW_LINE> if not self.is_blank(position): <NEW_LINE> <INDENT> position_list.append(position)...
Returns a Position for each letter currently placed on the board
625941e3b830903b967e9cdc
def run_tests(self, test_labels): <NEW_LINE> <INDENT> argv = [] <NEW_LINE> if self.select is not None: <NEW_LINE> <INDENT> argv.append(f"-k {self.select}") <NEW_LINE> <DEDENT> if self.verbosity == 0: <NEW_LINE> <INDENT> argv.append("--quiet") <NEW_LINE> <DEDENT> if self.verbosity == 2: <NEW_LINE> <INDENT> argv.append("...
Run pytest and return the exitcode. It translates some of Django's test command option to pytest's.
625941e350812a4eaa59c6f3
def hourly_trace_data(self, trace): <NEW_LINE> <INDENT> if trace.data.empty: <NEW_LINE> <INDENT> return pd.Series([]) <NEW_LINE> <DEDENT> data = [ value / ((e - s).seconds/3600.) for value, s, e in zip(trace.data.value, trace.data.index, trace.data.index[1:]) ] + [np.nan] <NEW_LINE> retval = pd.Series(data, index=trace...
Transforms a trace for this formatter to a hourly series
625941e3ab23a570cc25055a
def _makeDateCSVs(CSV_DIR, csvGener): <NEW_LINE> <INDENT> for DATE in csvGener.fileDates: <NEW_LINE> <INDENT> newGen = csvGenerator(sys.argv[1], FileParserPath=os.path.join(os.getcwd(), os.path.dirname(__file__), "PyFiles")) <NEW_LINE> newGen.setOpts( ' '.join([str(item) for item in csvGener.optsChosen]) ) <NEW_LINE> O...
This will create all of the Date specific CSVs, based on the files in csvGener
625941e37b25080760e3982c
def transparent_gzip(afile): <NEW_LINE> <INDENT> if afile.read(2) == b'\x1f\x8b': <NEW_LINE> <INDENT> afile.seek(0) <NEW_LINE> return gzip.GzipFile(fileobj=afile, mode='r') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> afile.seek(0) <NEW_LINE> return afile
If `afile` is gzipped, return a `gzip.GzipFile`, otherwise return `afile Args: afile: a bytes-like object Returns: the decompressed bytes-like object
625941e323849d37ff7b3461
def comment_line(intent, session): <NEW_LINE> <INDENT> card_title = "Success" <NEW_LINE> session_attributes = {} <NEW_LINE> should_end_session = True <NEW_LINE> if 'line_number' in intent['slots']: <NEW_LINE> <INDENT> line_number = int(intent['slots']['line_number']['value']) <NEW_LINE> post_params = {"command":"commen...
Comments line in a sublime window. line_number is the input within intent
625941e321bff66bcd684d24
def test_case_distribute(self): <NEW_LINE> <INDENT> print ("id: " + self.id()) <NEW_LINE> self.assertEqual(realloc.distribute([0, 2, 7, 0]), [2, 4, 1, 2])
realloc memory
625941e345492302aab5e69c
def multi_replace(s, replace_from, replace_to=""): <NEW_LINE> <INDENT> if isinstance(replace_to, str) and (len(replace_from) != len(replace_to)): <NEW_LINE> <INDENT> replace_to = [replace_to for _ in replace_from] <NEW_LINE> <DEDENT> if len(replace_from) != len(replace_to): <NEW_LINE> <INDENT> raise ValueError("len(rep...
A function like str.replace() with multiple replacements. ``replace_from`` is a list of things you want to replace. Ex: ['a','bc','d'] ``replace_to`` is a list of what you want to replace to. If ``replace_to`` is a list and has the same length as ``replace_from``, ``replace_from`` items will be translated to correspon...
625941e3851cf427c661a8e1
def grouped_response(self, code, m): <NEW_LINE> <INDENT> self.code = code <NEW_LINE> self.marketcode = m <NEW_LINE> self.grouped_payload = '{{"packageCode":"{}","searchFromDateTime":"{}","cabins":[{{"passengers":[{{"ageCategory":"ADULT","guestType":"REGULAR"}},{{"ageCategory":"ADULT","guestType":"REGULAR"}}]}}],"curren...
Sends travel code and date to intermediate API. Use the date from the gateways_response() and code from travel_codes() in payload to recieve a response containing voyage ID and quote ID which is needed for the final API call to get available price.
625941e3596a897236089e91
def getRepositories(self): <NEW_LINE> <INDENT> result = self.get(self.repositoryUrl, **self.extArgs) <NEW_LINE> if (type(result) == HTTPError): <NEW_LINE> <INDENT> raise RuntimeException() <NEW_LINE> <DEDENT> workspaceElements = result.getElementsByTagNameNS(APP_NS, 'workspace') <NEW_LINE> repositories = [] <NEW_LINE> ...
Returns a dict of high-level info about the repositories available at this service. The dict contains entries for 'repositoryId' and 'repositoryName'. >>> client.getRepositories() [{'repositoryName': u'Main Repository', 'repositoryId': u'83beb297-a6fa-4ac5-844b-98c871c0eea9'}]
625941e34428ac0f6e5babca
def pc_noutput_items(self): <NEW_LINE> <INDENT> return _Quacho_swig.ssdr_sink_sptr_pc_noutput_items(self)
pc_noutput_items(ssdr_sink_sptr self) -> float
625941e367a9b606de4a828c
def ls_regret( x_1, x_2, um_function=lin_utility, um_kwargs={}, weight=1, ): <NEW_LINE> <INDENT> return um_function(x_1, **um_kwargs) + weight * ( um_function(x_1, **um_kwargs) - um_function(x_2, **um_kwargs) )
classic regret function proposed by Loomes and Sugden 1982
625941e3be7bc26dc91cd9ce
def getGuessedWord(secretWord, lettersGuessed): <NEW_LINE> <INDENT> revealed = [] <NEW_LINE> for l in secretWord: <NEW_LINE> <INDENT> if l in lettersGuessed: <NEW_LINE> <INDENT> revealed.append(l) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> revealed.append('_ ') <NEW_LINE> <DEDENT> <DEDENT> return ''.join(revealed)
secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far.
625941e32c8b7c6e89b35b93
def _draw_output_boxes(self, cr): <NEW_LINE> <INDENT> nb_outputs = len(self.patch.channels[self.channel - 1]) <NEW_LINE> if nb_outputs <= 8: <NEW_LINE> <INDENT> self._draw_one_line(cr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._draw_two_lines(cr)
Draw outputs boxes Args: cr: Cairo context
625941e338b623060ff0b1c2
def testGetFile(self): <NEW_LINE> <INDENT> client_mock = action_mocks.GetFileClientMock() <NEW_LINE> pathspec = rdf_paths.PathSpec( pathtype=rdf_paths.PathSpec.PathType.OS, path=os.path.join(self.base_path, "test_img.dd")) <NEW_LINE> for _ in flow_test_lib.TestFlowHelper( transfer.GetFile.__name__, client_mock, token=s...
Test that the GetFile flow works.
625941e3ec188e330fd5ab6d
def loaded(self): <NEW_LINE> <INDENT> return bool(self.inspect())
如果至少有一个元素,返回True, 否则返回False
625941e3287bf620b61d3e36
def PredictRaw(studentRecord): <NEW_LINE> <INDENT> studentRecord=formatStudent(studentRecord) <NEW_LINE> pred_data=pd.DataFrame().from_records([studentRecord]) <NEW_LINE> pred_data.columns=["ID","FI","E","E","E"] <NEW_LINE> pred_data_pro=Preprocessor.preprocess(pred_data,train=False) <NEW_LINE> FI=list(Preprocessor.get...
Predicts the data from DATA/test.csv :studentRecord: data of the format [ID,FI,E1...E2] ID and FI are must :return: list of subjects he should have studied
625941e3091ae3566866732c
def add_nn_to_vx_no_flag(self): <NEW_LINE> <INDENT> vx_register = (self.opcode & 0x0F00) >> 8 <NEW_LINE> self.registers['v'][vx_register] = numpy.add(self.registers['v'][vx_register], numpy.uint8(self.opcode & 0x00FF)) <NEW_LINE> mnemonic = "ADD V" + str(vx_register) + ", " + str(self.opcode & 0x00FF) <NEW_LINE> human ...
Suma a Vx nn sin establecer la bandera en caso de overflow
625941e3566aa707497f4938
def init_tape(self, string): <NEW_LINE> <INDENT> for char in string: <NEW_LINE> <INDENT> if char not in self.alphabet and not char.isspace() and char != self.EMPTY_SYMBOL: <NEW_LINE> <INDENT> raise RuntimeError('Invalid symbol: "' + char + '"') <NEW_LINE> <DEDENT> <DEDENT> self.check() <NEW_LINE> self.state = self.STAR...
Init system values.
625941e3d53ae8145f87a63d
def get_sb_log_name(self, port): <NEW_LINE> <INDENT> sb_log_name = 'sb_{}_{}_db{}.log'.format(self._target, self._threads, port) <NEW_LINE> return os.path.join(self._dir, sb_log_name)
Get sysbench logfile name. :param port: :return:
625941e3f8510a7c17cf9ad4
def choose_feature_by_cart_r_(self,X,y,columns,weight): <NEW_LINE> <INDENT> features_use_n=self.features_use_n <NEW_LINE> feature_n=len(columns) <NEW_LINE> if features_use_n>feature_n: <NEW_LINE> <INDENT> features_use_n=feature_n <NEW_LINE> <DEDENT> features_idx=pd.Series(range(feature_n)) <NEW_LINE> features_idx=featu...
X:所有参与选择的特征列,narray类型 y:回归值列,narray类型 columns: 列索引,list(int)类型 weight: 样本权重,narray类型 return 0: 最优分裂特征的索引 ,int类型 1: 最优分裂子集索引,narray类型 2: 最优分裂子集标签,list(tuple(str,float/int/list(int)))类型
625941e30c0af96317bb85bd
def get_pcp_statistics(self, spic=None, timeout=300): <NEW_LINE> <INDENT> self.fn_checkin("Retrieving PCP statistics") <NEW_LINE> if spic is None: <NEW_LINE> <INDENT> raise self.MissingMandatoryArgument('spic') <NEW_LINE> <DEDENT> cmd = 'show services pcp statistics interface ' + spic <NEW_LINE> entry = self.get_xml_ou...
Fetch PCP statistics as dictionary :param string spic: **REQUIRED** Service PIC interface :param int timeout: **OPTIONAL** Cli command timeout. Default is 300 :return: Dictionary containing the PCP statistics data :rtype: dict Example:: Python: pcp.get_pcp_statistics() Robot: pcp.G...
625941e3f7d966606f6aa3de
def delete(self, s): <NEW_LINE> <INDENT> if self.t[s] == 'OPEN': <NEW_LINE> <INDENT> self.t[s] = 'CLOSED' <NEW_LINE> <DEDENT> self.OPEN.remove(s)
delete: move state s from OPEN set to CLOSED set. :param s: state should be deleted
625941e360cbc95b062c6918
def calc_deriv(function,x0,delta): <NEW_LINE> <INDENT> return (function(x0+delta)-function(x0-delta))/(2*delta)
This function approximates the derivates by using the formula of tengente approximation Approximation de la derivee en utlisant la formule du taux d'accroissement
625941e39f2886367277ac60
def read_temp(self): <NEW_LINE> <INDENT> temp = self.bus.read_byte_data(self.address, TEMP) <NEW_LINE> return temp
Read data from the temperature sensor.
625941e323e79379d52ee934
def test_get_index_file_date_header(): <NEW_LINE> <INDENT> global mock_recv_content <NEW_LINE> global mock_send_content <NEW_LINE> mock_socket = get_mock_socket() <NEW_LINE> mock_recv_content = b'GET /index.html HTTP/1.1\r\n\r\n' <NEW_LINE> mock_send_content = b'' <NEW_LINE> handle_request(mock_socket) <NEW_LINE> asser...
Checks the existance of the Date header
625941e3bde94217f36831c2
def uniformCostSearch(problem): <NEW_LINE> <INDENT> return UCSMethod().solveProblem(problem)
Search the node of least total cost first.
625941e34c3428357757c6fb
def _validate_forbidden(self, forbidden_values, field, value): <NEW_LINE> <INDENT> if isinstance(value, Sequence) and not isinstance(value, _str_type): <NEW_LINE> <INDENT> forbidden = set(value) & set(forbidden_values) <NEW_LINE> if forbidden: <NEW_LINE> <INDENT> self._error(field, errors.FORBIDDEN_VALUES, list(forbidd...
{'type': 'list'}
625941e3d53ae8145f87a63e
def fc1(): <NEW_LINE> <INDENT> image = Input(shape=(25088,)) <NEW_LINE> layer = Dense(2048, activation='relu')(image) <NEW_LINE> model = Model(image, layer) <NEW_LINE> return model
Block 6 is the first fully connected layer in VGG16.
625941e3baa26c4b54cb14f1
def put(self, *args, **kwargs): <NEW_LINE> <INDENT> return super(APIWorkflowView, self).put(*args, **kwargs)
Edit the selected workflow.
625941e37d847024c06be694