code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def on_connection_close(self, reason): <NEW_LINE> <INDENT> pass
This is called when server closed the connection.
625941ee6fb2d068a760f5ec
def serialize(self, root: TreeNode) -> str: <NEW_LINE> <INDENT> visitQueue = deque([root]) <NEW_LINE> serializedString = '[' <NEW_LINE> while visitQueue: <NEW_LINE> <INDENT> node = visitQueue.pop() <NEW_LINE> if node is not None: <NEW_LINE> <INDENT> serializedString += str(node.val) + ',' <NEW_LINE> visitQueue.appendle...
Encodes a tree to a single string. :type root: TreeNode :rtype: str
625941ee711fe17d825428a5
def recipients(self) -> Optional[str]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> person_emails = self.context_objects["person_emails"] <NEW_LINE> return person_emails <NEW_LINE> <DEDENT> except (KeyError, AttributeError): <NEW_LINE> <INDENT> return None
Assuming self.context is ready, overwrite email's recipients with selected ones.
625941ee97e22403b379d4e2
def _is_aegir_deployment(target): <NEW_LINE> <INDENT> return False if 'aegir' not in target or target.get('aegir') is False else True
Check if the target environment is an Aegir server.
625941ee50812a4eaa59c862
def testApiGetApplicationResponse(self): <NEW_LINE> <INDENT> pass
Test ApiGetApplicationResponse
625941eea4f1c619b28b0572
def setPeriod(self, period): <NEW_LINE> <INDENT> self.period = period
:param period: (Optional) 时间粒度,可选值:[oneMin,fiveMin,followTime],followTime只会返回一个汇总后的数据
625941eef548e778e58cdac6
def _check_reply(self): <NEW_LINE> <INDENT> self._more_packets_available = False <NEW_LINE> try: <NEW_LINE> <INDENT> if self._reply is None: <NEW_LINE> <INDENT> self._status = (3, '%s without reply' % REPLAY_INFO[unpack_dint(self._message[:2])]) <NEW_LINE> return False <NEW_LINE> <DEDENT> typ = unpack_uint(self._reply[...
check the replayed message for error
625941eef8510a7c17cf9c47
def add_widgets(self, widgetlist, box): <NEW_LINE> <INDENT> for x in widgetlist: <NEW_LINE> <INDENT> q = None <NEW_LINE> if x == "t": <NEW_LINE> <INDENT> q = Taskbar(self.conf, self.size) <NEW_LINE> <DEDENT> elif x == "p": <NEW_LINE> <INDENT> q = Pager(self.conf) <NEW_LINE> <DEDENT> elif x == "b": <NEW_LINE> <INDENT> q...
Add a list of widgets to one of our locations. Position should be one of the Clutter.Boxes. This function automatically adjusts for vertical/horizontal layouts.
625941ee1f037a2d8b946743
def smooth(ft_data, r, N, mode, data_in_fourier_space = True, f = lambda x, y: x**2+y): <NEW_LINE> <INDENT> if data_in_fourier_space: <NEW_LINE> <INDENT> return np.fft.irfftn(ft_sph_filter(r, N, mode, f) * ft_data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return np.fft.irfftn(ft_sph_filter(r, N, mode, f) * np.fft....
Smoothing data. !!!! By default data is already in Fourier space !!!! Args: ft_data: data (in the Fourier space or Real space) r: smoothing parameter N: size of the data cube mode: data_in_fourier_space: f:
625941ee44b2445a339325d8
def get_representation( self, sentences, batch_size, tokenize=False, strategy='max' ): <NEW_LINE> <INDENT> representations = [] <NEW_LINE> for name, model in self.models.items(): <NEW_LINE> <INDENT> if name == 'elmo': <NEW_LINE> <INDENT> embeddings = model.encode( sentences, bsize=batch_size, tokenize=tokenize ) <NEW_L...
Get model representations.
625941ee7d847024c06be807
def mySqrt(self, x): <NEW_LINE> <INDENT> if x == 0: return 0 <NEW_LINE> left, right = 1, x <NEW_LINE> while left <= right: <NEW_LINE> <INDENT> mid = left + (right-left) // 2 <NEW_LINE> if mid > x // mid: <NEW_LINE> <INDENT> right = mid - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> left = mid + 1 <NEW_LINE> <DEDENT>...
:type x: int :rtype: int
625941ee45492302aab5e80f
def currentTime(self, time): <NEW_LINE> <INDENT> dt = datetime.fromtimestamp(time) <NEW_LINE> t = dt.strftime("%Y-%m-%d %H:%M:%S.%f") <NEW_LINE> self.apiStatus = True <NEW_LINE> self.gateway.connected = True <NEW_LINE> log = VtLogData() <NEW_LINE> log.gatewayName = self.gatewayName <NEW_LINE> log.logContent = text.API_...
连接成功后推送当前时间
625941ee01c39578d7e75382
def _transform_issue(self, bz_issue, bz_comments): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> mongo_issue = Issue.objects(issue_system_id=self.issue_system_id, external_id=str(bz_issue['id'])).get() <NEW_LINE> <DEDENT> except DoesNotExist: <NEW_LINE> <INDENT> mongo_issue = Issue( issue_system_id=self.issue_system_id,...
Transforms the issue from an bugzilla issue to our issue model :param bz_issue: bugzilla issue (returned by the API) :param bz_comments: comments to the bugzilla issue (as the first comment is the description of the issue) :return:
625941ee66656f66f7cbc6f3
def buildScripts(self): <NEW_LINE> <INDENT> self.writeScript(self.source, "script1", ("#! /usr/bin/env python2.7\n" "# bogus script w/ Python sh-bang\n" "pass\n")) <NEW_LINE> self.writeScript(self.source, "script2.py", ("#!/usr/bin/python\n" "# bogus script w/ Python sh-bang\n" "pass\n")) <NEW_LINE> self.writeScript(se...
Write 3 types of scripts and run the L{build_scripts_twisted} command.
625941ee3346ee7daa2b32b7
def set_menu_helpers(self, slug): <NEW_LINE> <INDENT> slug = slug.strip("/") <NEW_LINE> parent_slug = lambda slug: "/".join(slug.split("/")[:-1]) + "/" <NEW_LINE> self.is_current_sibling = parent_slug(slug) == parent_slug(self.slug) <NEW_LINE> self.is_current_or_ascendant = (slug + "/").startswith(self.slug + "/") <NEW...
Called from the ``page_menu`` template tag and assigns a handful of properties based on the current URL that are used within the various types of menus.
625941ee4d74a7450ccd470b
def save_evaluations(self, evaluation, filename): <NEW_LINE> <INDENT> filename = self.result_dir + filename <NEW_LINE> with open(filename, 'w') as f: <NEW_LINE> <INDENT> for time, evaluation in evaluation.metrics.items(): <NEW_LINE> <INDENT> f.write("%-10s\t" % time) <NEW_LINE> f.write("%-20s\t%-20s\t%-20s\t%-20s\t%-20...
将一段时间内底层网络的性能指标输出到指定文件内
625941ee57b8e32f524839e5
def storing_recieved_pdus(self): <NEW_LINE> <INDENT> while self.socket.is_open is True: <NEW_LINE> <INDENT> R = self.socket.get_pdu_from_socket() <NEW_LINE> if(R is not None): <NEW_LINE> <INDENT> if R.command_id.value == command_ids.deliver_sm: <NEW_LINE> <INDENT> self.deliver_sms_response(R) <NEW_LINE> <DEDENT> elif(s...
Client background thread use this method to recieve response/request PDU's and storing them in dictionary.
625941eea79ad161976cc68c
def get_env_info(): <NEW_LINE> <INDENT> deps = [ ("oggm", lambda mod: mod.__version__), ("numpy", lambda mod: mod.__version__), ("scipy", lambda mod: mod.__version__), ("pandas", lambda mod: mod.__version__), ("geopandas", lambda mod: mod.__version__), ("netCDF4", lambda mod: mod.__version__), ("matplotlib", lambda mod...
Returns env information as a list of tuples
625941ee3c8af77a43ae3ced
def event_listener(self): <NEW_LINE> <INDENT> if self.version <= '5.9': <NEW_LINE> <INDENT> from cfme.utils.events_db import DbEventListener <NEW_LINE> return DbEventListener(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> from cfme.utils.events import RestEventListener <NEW_LINE> return RestEventListener(self)
Returns an instance of the event listening class pointed to this appliance.
625941ee8a43f66fc4b545a6
def save_route_to_db(name, start, end, travel_mode, user): <NEW_LINE> <INDENT> route = model.Route() <NEW_LINE> route.name = name <NEW_LINE> route.user_id = user <NEW_LINE> route.start = start <NEW_LINE> route.end = end <NEW_LINE> route.travel_mode = travel_mode <NEW_LINE> model.session.add(route) <NEW_LINE> model.sess...
Creates new route object and appends to db.
625941ee566aa707497f4aa8
def get_test_package_history(test_packages): <NEW_LINE> <INDENT> history_list = dict() <NEW_LINE> for package in test_packages: <NEW_LINE> <INDENT> db_package = Package.objects.filter(package_name = package) <NEW_LINE> duration = None <NEW_LINE> if db_package.count() > 0: <NEW_LINE> <INDENT> db_package = db_package[0] ...
Returns dictionary of test packages and their latest execution time. If time not available, then it is none @type test_packages: C{list} @param test_packages: List of test packages @rtype: C{dict} @return: Dictionary of test package names and execution times (in minute)
625941ee3cc13d1c6d3c78be
def avg_category(self, category): <NEW_LINE> <INDENT> if self._verify_category(category) == 1: <NEW_LINE> <INDENT> if self._err == 1: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> maxx = 0 <NEW_LINE> maxx_name = 'No_Data' <NEW_LINE> for item in COREDependencies.COREConstants.RADIO_VALUES[category]: <NEW_LINE> <INDE...
RADIO SPECIFIC FUNCTION which displays the option which appears most for the team. category : radio name that exists in the database. return : most common radio option.
625941eeff9c53063f47c737
def _to_base10(number): <NEW_LINE> <INDENT> return ''.join( str(int(x, 36)) for x in number)
Prepare the number to its base10 representation.
625941ee4c3428357757c86b
def create(self, ip_record_sid, sip_domain_sid): <NEW_LINE> <INDENT> data = values.of({'IpRecordSid': ip_record_sid, 'SipDomainSid': sip_domain_sid, }) <NEW_LINE> payload = self._version.create(method='POST', uri=self._uri, data=data, ) <NEW_LINE> return SourceIpMappingInstance(self._version, payload, )
Create the SourceIpMappingInstance :param unicode ip_record_sid: The unique string that identifies an IP Record :param unicode sip_domain_sid: The unique string that identifies a SIP Domain :returns: The created SourceIpMappingInstance :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingInstance
625941ee5fc7496912cc3ec4
def split_by(array, group_size, filler): <NEW_LINE> <INDENT> args = [iter(array)] * group_size <NEW_LINE> return list(map(list, zip_longest(*args, fillvalue=filler)))
Group elements into list of size `group_size` and fill empty cells with `filler`. Recipe from https://docs.python.org/3/library/itertools.html
625941ee5166f23b2e1a56a0
def get_castep_version(castep_command): <NEW_LINE> <INDENT> temp_dir = tempfile.mkdtemp() <NEW_LINE> curdir = os.getcwd() <NEW_LINE> os.chdir(temp_dir) <NEW_LINE> jname = 'dummy_jobname' <NEW_LINE> stdout, stderr = "", "" <NEW_LINE> try: <NEW_LINE> <INDENT> stdout, stderr = subprocess.Popen( castep_command.split() + [j...
This returns the version number as printed in the CASTEP banner.
625941ee596a89723608a000
def test_gnomesort(): <NEW_LINE> <INDENT> pass
>>> from random import * >>> for i in range(10): ... seq = [randrange(1000) for i in range(100)] ... seq2 = sorted(seq) ... gnomesort(seq) ... assert seq == seq2 ... >>>
625941ee60cbc95b062c6a8a
def get_type(self): <NEW_LINE> <INDENT> r <NEW_LINE> return self.type
Returns the type of the null point object.
625941ee8e71fb1e9831dcee
def __approximate_radius(self, geometry): <NEW_LINE> <INDENT> corners = geometry.GetEnvelope() <NEW_LINE> centroid = geometry.Centroid() <NEW_LINE> corner_point = ogr.CreateGeometryFromWkt('POINT({0} {1})'.format(corners[0], corners[2])) <NEW_LINE> return centroid.Distance(corner_point)
Return the approximate radius of a polygon geometry. :param geometry: an OGR geometry
625941ee56b00c62f0f14ba4
def check_auth(username, password): <NEW_LINE> <INDENT> if ph_app.args.AUTH: <NEW_LINE> <INDENT> user, pwd = ph_app.args.AUTH.split(':') <NEW_LINE> return username == user and password == pwd <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True
This function is called to check if a username / password combination is valid.
625941eecc40096d61595e95
def parkingfee(rate, hour, num): <NEW_LINE> <INDENT> print("Car No.%02i: %.2f Baht." % (num, int(hour)*rate))
Calculate Parking Fee
625941ee07d97122c4178ddf
def change_password(data, args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data.change_password(args.username, args.new_password) <NEW_LINE> data.save() <NEW_LINE> print("Password changed") <NEW_LINE> <DEDENT> except hass_auth.InvalidUser: <NEW_LINE> <INDENT> print("User not found")
Change password.
625941ee091ae3566866749c
def send(func, *args, **kwargs): <NEW_LINE> <INDENT> mine_func = kwargs.pop('mine_function', func) <NEW_LINE> if mine_func not in __salt__: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> data = {} <NEW_LINE> arg_data = salt.utils.arg_lookup(__salt__[mine_func]) <NEW_LINE> func_data = copy.deepcopy(kwargs) <NEW_LI...
Send a specific function to the mine. CLI Example: .. code-block:: bash salt '*' mine.send network.ip_addrs eth0 salt '*' mine.send eth0_ip_addrs mine_function=network.ip_addrs eth0
625941ee4e4d5625662d4917
def capture(self, region = None): <NEW_LINE> <INDENT> if region is None: <NEW_LINE> <INDENT> region = CG.CGRectInfinite <NEW_LINE> <DEDENT> image = CG.CGWindowListCreateImage( region, CG.kCGWindowListOptionOnScreenOnly, CG.kCGNullWindowID, CG.kCGWindowImageDefault) <NEW_LINE> self._data = CG.CGDataProviderCopyData(CG.C...
capture screenshot from region :region: tuple of (x, y, width, height)
625941ee29b78933be1e5bec
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``
625941ee3317a56b8693a192
def ctcp(self, ctcptype, target, parameter=""): <NEW_LINE> <INDENT> ctcptype = ctcptype.upper() <NEW_LINE> self.privmsg(target, "\001{0}{1}\001".format(ctcptype, parameter and (" " + parameter) or ""))
Send a CTCP command.
625941ee6aa9bd52df0372ee
def to_offset(freq): <NEW_LINE> <INDENT> if isinstance(freq, BaseCFTimeOffset): <NEW_LINE> <INDENT> return freq <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> freq_data = re.match(_PATTERN, freq).groupdict() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise ValueError("Invalid...
Convert a frequency string to the appropriate subclass of BaseCFTimeOffset.
625941ee293b9510aa2c37d7
def pip_list(args, pip): <NEW_LINE> <INDENT> stdout = run_command(args, pip + ['list'], capture=True)[0] <NEW_LINE> return stdout
:type args: EnvironmentConfig :type pip: list[str] :rtype: str
625941ee21bff66bcd684e95
def pieri_factors(self, *args, **keywords): <NEW_LINE> <INDENT> import sage.combinat.root_system.pieri_factors <NEW_LINE> ct = self.cartan_type() <NEW_LINE> if hasattr(ct, "PieriFactors"): <NEW_LINE> <INDENT> return ct.PieriFactors(self, *args, **keywords) <NEW_LINE> <DEDENT> raise NotImplementedError("Pieri factors fo...
Returns the set of Pieri factors in this Weyl group. For any type, the set of Pieri factors forms a lower ideal in Bruhat order, generated by all the conjugates of some special element of the Weyl group. In type `A_n`, this special element is `s_n\cdots s_1`, and the conjugates are obtained by rotating around this red...
625941ee31939e2706e4d3a9
def fit(self, y): <NEW_LINE> <INDENT> if self.classes is None: <NEW_LINE> <INDENT> classes = sorted(set(itertools.chain.from_iterable(y))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> classes = self.classes <NEW_LINE> <DEDENT> dtype = np.int if all(isinstance(c, int) for c in classes) else object <NEW_LINE> self.class...
Fit the label sets binarizer, storing `classes_` Parameters ---------- y : iterable of iterables A set of labels (any orderable and hashable object) for each sample. If the `classes` parameter is set, `y` will not be iterated. Returns ------- self : returns this MultiLabelBinarizer instance
625941ee796e427e537b0b12
def barycentric_radio_freq(self, toas): <NEW_LINE> <INDENT> tbl = toas.table <NEW_LINE> L_hat = self.ssb_to_psb_xyz_ICRS(epoch=tbl["tdbld"].astype(np.float64)) <NEW_LINE> v_dot_L_array = np.sum(tbl["ssb_obs_vel"] * L_hat, axis=1) <NEW_LINE> return tbl["freq"] * (1.0 - v_dot_L_array / const.c)
Return radio frequencies (MHz) of the toas corrected for Earth motion
625941ee0a366e3fb873ed67
def circles_intersect(x1, y1, r1, x2, y2, r2): <NEW_LINE> <INDENT> distance_between_circle_centres = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) <NEW_LINE> radius_sum = r1 + r2 <NEW_LINE> radius_diff = abs(r1 - r2) <NEW_LINE> if radius_sum < distance_between_circle_centres: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDEN...
Func. checks circles intersect :param x1: coordinate x of first circle :param y1: coordinate y of first circle :param r1: radius of first circle :param x2: coordinate x of second circle :param y2: coordinate y of second circle :param r2: radius of second circle :return: True if the circles intersect or False if not
625941ee6aa9bd52df0372ef
def husimi_from_wigner(wig): <NEW_LINE> <INDENT> l = len(wig) <NEW_LINE> sigma = sqrt(l/pi/4) <NEW_LINE> hus = zeros((l, l), Float) <NEW_LINE> for x1 in range(l): <NEW_LINE> <INDENT> for k1 in range(l): <NEW_LINE> <INDENT> sys.stderr.write("wigner -> husimi (very slow) ...%6.2f%%\r" % ((100.0*(x1*l+k1))/l/l)) <NEW_LINE...
calculate the husimi function out of the wigner function
625941ee63b5f9789fde762d
def refresh_times(): <NEW_LINE> <INDENT> global times_dict <NEW_LINE> date = arrow.utcnow().to('US/Pacific').format('YYYY-MM-DD') <NEW_LINE> city = Astral()['Seattle'] <NEW_LINE> sun = city.sun(date=datetime.date(int(date[:4]), int(date[5:-3]), int(date[8:])), local=True) <NEW_LINE> for key in times_dict: <NEW_LINE> <I...
Refreshes the sun times in the times_dict
625941eedc8b845886cb5a7e
def getIfaces(self): <NEW_LINE> <INDENT> route = [] <NEW_LINE> data = file('/proc/net/route').read().splitlines()[1:] <NEW_LINE> for line in data: <NEW_LINE> <INDENT> line = line.replace('\t',' ').strip().rsplit(' ') <NEW_LINE> if line[2] != '00000000': <NEW_LINE> <INDENT> route +=[ifacesObject(line[0], self.getIp(line...
get ifaces from /proc/net route and return an object array with the ip hwaddr of the iface and gateway
625941ee7b25080760e3999d
def __init__(self, id): <NEW_LINE> <INDENT> self.id = str(id) <NEW_LINE> self.distance = 0 <NEW_LINE> self.neighbors = [] <NEW_LINE> self.edges = {}
Classe vertex é iniciada com argumento id. >>> x = vertex(8) Arguments: id - identifier of object. Atributes: distance - to be used by dijkstra function neighbors - list to add pointers to neighbors edges - dictionary: [vertex:weight]
625941ee3346ee7daa2b32b8
def __init__(self, ilo, index_settings={}, ignore_unavailable=False, preserve_existing=False): <NEW_LINE> <INDENT> utils.verify_index_list(ilo) <NEW_LINE> if not index_settings: <NEW_LINE> <INDENT> raise exceptions.MissingArgument('Missing value for "index_settings"') <NEW_LINE> <DEDENT> self.client = ilo.client <N...
:arg ilo: A :class:`curator.indexlist.IndexList` object :arg index_settings: A dictionary structure with one or more index settings to change. :arg ignore_unavailable: Whether specified concrete indices should be ignored when unavailable (missing or closed) :arg preserve_existing: Whether to update existing set...
625941eea17c0f6771cbe596
def _rreplace(self, s, old, new, count=1): <NEW_LINE> <INDENT> li = s.rsplit(old, count) <NEW_LINE> return new.join(li)
A helper function to replace strings backwards.
625941ee004d5f362079a877
def log(sender, message): <NEW_LINE> <INDENT> logger.info("[%s] " % sender + message)
Log a message in the console
625941ee1f037a2d8b946744
def _is_nth_color(c): <NEW_LINE> <INDENT> return isinstance(c, str) and re.match(r"\AC[0-9]\Z", c)
Return whether *c* can be interpreted as an item in the color cycle.
625941ee4f6381625f114f83
def get_file_content(url, session): <NEW_LINE> <INDENT> scheme = get_url_scheme(url) <NEW_LINE> if scheme in ['http', 'https']: <NEW_LINE> <INDENT> resp = session.get(url) <NEW_LINE> raise_for_status(resp) <NEW_LINE> return resp.url, resp.text <NEW_LINE> <DEDENT> elif scheme == 'file': <NEW_LINE> <INDENT> url = url_to_...
Gets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content). Content is unicode. Respects # -*- coding: declarations on the retrieved files. :param url: File path or url. :param session: PipSession instance.
625941eeb7558d58953c5450
def rss_file(self, filename, extensions=True, pretty=False, encoding='UTF-8', xml_declaration=True): <NEW_LINE> <INDENT> feed, doc = self._create_rss(extensions=extensions) <NEW_LINE> doc.write(filename, pretty_print=pretty, encoding=encoding, xml_declaration=xml_declaration)
Generates an RSS feed and write the resulting XML to a file. :param filename: Name of file to write or a file-like object or a URL. :param extensions: Enable or disable the loaded extensions for the xml generation (default: enabled). :param pretty: If the feed should be split into multiple lines and properly i...
625941eebe7bc26dc91cdb3d
def _refresh(self, event=None): <NEW_LINE> <INDENT> self._ui.PackageTable.model().update()
Refresh cache informations
625941eecad5886f8bd27520
def test_recv_many_packets_in_order(): <NEW_LINE> <INDENT> packet_log = rdpcap("test/inputs/wget-36000-nums.pcap") <NEW_LINE> listener, conn = create_session(packet_log) <NEW_LINE> _, syn_ack, _, push_ack = packet_log[:4] <NEW_LINE> listener.dispatch(syn_ack) <NEW_LINE> payload = get_payload(push_ack) <NEW_LINE> conn.s...
We should be able to put multiple packets together, if they come in order
625941ee9b70327d1c4e131f
def test_03_regexp(self): <NEW_LINE> <INDENT> d = Domain( domain = 'dummy', url = 'dummy' ) <NEW_LINE> d.save() <NEW_LINE> s = Snapshot( domain_id = d.id, pulled_at = datetime.utcnow(), html = "find me with a regexp!!", ) <NEW_LINE> s.save() <NEW_LINE> dc = DomainCheck( domain_id = d.id, name = "dummy_...
regexp process test
625941ee236d856c2ad44d29
@skip_if_not_set('clients') <NEW_LINE> @tier3 <NEW_LINE> def test_positive_delete_with_system(session): <NEW_LINE> <INDENT> name = gen_string('alpha') <NEW_LINE> cv_name = gen_string('alpha') <NEW_LINE> env_name = gen_string('alpha') <NEW_LINE> product_name = gen_string('alpha') <NEW_LINE> org = entities.Organization()...
Delete an Activation key which has registered systems :id: 86cd070e-cf46-4bb1-b555-e7cb42e4dc9f :Steps: 1. Create an Activation key 2. Register systems to it 3. Delete the Activation key :expectedresults: Activation key is deleted :CaseLevel: System
625941eed7e4931a7ee9e467
def poll(self, poll_period_ms): <NEW_LINE> <INDENT> self.client.poll(poll_period_ms)
Poll the CoAP Client for new incoming messages :param poll_period_ms: Poll period in milliseconds
625941ee236d856c2ad44d2a
def chassis_callback(self, chassis_pb2): <NEW_LINE> <INDENT> speedmps = chassis_pb2.speed_mps <NEW_LINE> t = chassis_pb2.header.timestamp_sec <NEW_LINE> self.buff.append(speedmps) <NEW_LINE> if len(self.buff) < SmoothParam: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self.last_t is not None: <NEW_LINE> <INDENT> s...
Calculate ACC from Chassis Speed
625941ee3539df3088e2e893
def __hash__(self): <NEW_LINE> <INDENT> return hash((self.name, self.filename, self.lineno))
Statistics can be a key.
625941eed6c5a10208144597
def z(a): <NEW_LINE> <INDENT> return R(a.polynomial()) % h
Function returned by cyclotomic_restriction_tower. INPUT: an element alpha in L OUTPUT: a polynomial `f(x)` in `K[x]` such that `f(zeta_m) = alpha`. EXAMPLES:: sage: L = CyclotomicField(121) ; K = CyclotomicField(11) sage: z = sage.modular.modform.eisenstein_submodule.cyclotomic_restriction_tower(L,K) ...
625941eee8904600ed9f247e
@bottle.post('/login') <NEW_LINE> def login(): <NEW_LINE> <INDENT> username = post_get('username') <NEW_LINE> password = post_get('password') <NEW_LINE> sess = bottle.request.environ.get('beaker.session') <NEW_LINE> sess['name'] = username <NEW_LINE> return bottle.template('index', username=username)
Authenticate users
625941ee0fa83653e46574ff
def unload_model(self, model_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._client.unload_model(model_name) <NEW_LINE> logger.debug(f'Model {model_name} unloaded') <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.info(f'Model {model_name} unload failed: {e}') <NEW_LINE> return -1
Request the inference server to unload a particular model in explicit model control mode. Parameters ---------- model_name : str name of the model to load from repository Raises ------ TritonModelAnalyzerException If server throws Exception
625941ee71ff763f4b549bdd
def writePairs(File, val1, val2): <NEW_LINE> <INDENT> File.write(str(val1)) <NEW_LINE> File.write("\t") <NEW_LINE> File.write(str(val2)) <NEW_LINE> File.write("\n")
Writes a pair of integers to a file. Input: File: a file object to write to. val1: an integer to write to the file va12: an integer to write to the file Return: Nothing
625941ee656771135c3ebdbd
def testImageGroupPropertyDefinitionResource(self): <NEW_LINE> <INDENT> pass
Test ImageGroupPropertyDefinitionResource
625941ee379a373c97cfb08e
def value_learn(self, obs, value): <NEW_LINE> <INDENT> data_size = obs.shape[0] <NEW_LINE> if self.value_learn_buffer is None: <NEW_LINE> <INDENT> obs_train, value_train = obs, value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> obs_train = np.concatenate([obs, self.value_learn_buffer[0]]) <NEW_LINE> value_train = np.c...
Fit model to current data batch + previous data batch
625941ee379a373c97cfb08f
def hangman(secretWord): <NEW_LINE> <INDENT> print("Welcome to the game, Hangman!") <NEW_LINE> print("I am thinking of a word that is " + str(len(secretWord)) + "letters long.") <NEW_LINE> guesschances = 0 <NEW_LINE> won = 0 <NEW_LINE> guessedletters = [] <NEW_LINE> while guesschances < 8 and won!= 1: <NEW_LINE> <INDEN...
secretWord: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secretWord contains. * Ask the user to supply one guess (i.e. letter) per round. * The user should receive feedback immediately after each guess about whet...
625941eecc0a2c11143dd3d9
@hug.get(output=hug.output_format.text) <NEW_LINE> @hug.cli() <NEW_LINE> def rcfile(): <NEW_LINE> <INDENT> with open('samples/sample_vimrc') as f: <NEW_LINE> <INDENT> rcfile = '' <NEW_LINE> for line in f: <NEW_LINE> <INDENT> rcfile += f.readline() <NEW_LINE> <DEDENT> <DEDENT> return rcfile
Returns a vimrc file
625941eebd1bec0571d90b77
def test_soup_url_count(self): <NEW_LINE> <INDENT> html = "" <NEW_LINE> for url in self.__urls: <NEW_LINE> <INDENT> html += "\n" + url["test"] <NEW_LINE> <DEDENT> request = Request(self.__host) <NEW_LINE> response = Response(self.__host) <NEW_LINE> response.text = html <NEW_LINE> finder = HTMLSoupFormScraper(Options(),...
Test if the amount of URLs found complies with the expected amount.
625941ee50485f2cf553d2e4
def get_countprimarysegments(self): <NEW_LINE> <INDENT> n = 0 <NEW_LINE> for r in self.record: <NEW_LINE> <INDENT> if r.role and r.content != -1: <NEW_LINE> <INDENT> n += 1 <NEW_LINE> <DEDENT> <DEDENT> return n
Returns number of primary segments
625941ee442bda511e8be958
def get_layout_pointer_position(self): <NEW_LINE> <INDENT> x, y = self._main_layout.get_pointer() <NEW_LINE> x += self._hadjust.get_value() <NEW_LINE> y += self._vadjust.get_value() <NEW_LINE> return x, y
Return a 2-tuple with the x and y coordinates of the pointer on the main layout area, relative to the layout.
625941ee6e29344779a62b58
def connect(self, **kwargs): <NEW_LINE> <INDENT> host = kwargs.pop('host', None) or self.host <NEW_LINE> port = kwargs.pop('port', None) or self.port <NEW_LINE> auth = kwargs.pop('auth', None) or self.auth <NEW_LINE> if not self.connected(): <NEW_LINE> <INDENT> for _ in range(5): <NEW_LINE> <INDENT> self._con = ESLconn...
Reconnect if disconnected
625941ee91af0d3eaac9bf66
def SetPointIds(self, *args): <NEW_LINE> <INDENT> return _itkCellInterfacePython.itkCellInterfaceDQEMCTI3_AutoPointer_SetPointIds(self, *args)
SetPointIds(self, unsigned long first) SetPointIds(self, unsigned long first, unsigned long last)
625941ee4e696a04525c9995
def lighten(image): <NEW_LINE> <INDENT> return tf.image.adjust_brightness(image, 0.5)
lighten image.
625941ee31939e2706e4d3aa
def show_path_2D(start, end, coordinates, clear = True): <NEW_LINE> <INDENT> global L, N, delta_t <NEW_LINE> plt.ion() <NEW_LINE> fig = plt.figure() <NEW_LINE> for time_step in range(start, end): <NEW_LINE> <INDENT> colours = cm.rainbow(np.linspace(0, 1, N)) <NEW_LINE> for i in range(N): <NEW_LINE> <INDENT> plt.scatter...
Function which takes in the coordinates as described in straight_particle and plots the result on a scatter graph.
625941ee5fcc89381b1e1c0b
def __init__(self, style, parent=None): <NEW_LINE> <INDENT> super().__init__(parent) <NEW_LINE> self.setWindowTitle('Rename RSA keys — KRIS') <NEW_LINE> main_lay = QGridLayout() <NEW_LINE> self.setLayout(main_lay) <NEW_LINE> main_lay.addWidget(QLabel("Keys' name :"), 0, 0) <NEW_LINE> self.keys_opt = QComboBox() <NEW_LI...
Initiate the RenKeyWin window.
625941eea934411ee3751bdd
def score_classifier(X, y, clf, nfeats=None, scoring=default_scorers, score_aggreg=default_score_aggreg, scale=None, decompose=None, select=None, decompose_params={}, nfolds=10, shuffle=True, random_fold_state=None, include_train_stats=False): <NEW_LINE> <INDENT> scoring = scoring or default_scorers <NEW_LINE> scoring ...
Tests the CLF classifier with NFOLDS of train/test splits, and scores the results using one or several score functions (specified by SCORING), returning a pandas Series listing the aggregate(s) (specified by SCORE_AGGREG) of the scores.
625941eeac7a0e7691ed460a
@api_view(['GET', 'POST']) <NEW_LINE> @authentication_classes((TokenAuthentication,)) <NEW_LINE> @permission_classes((IsAuthenticated,)) <NEW_LINE> def goal_list(request, weekly=False): <NEW_LINE> <INDENT> weekly_param = request.GET.get('weekly','false') <NEW_LINE> weekly = weekly or weekly_param != 'false' <NEW_LINE> ...
List current goals, or create a new one
625941ee94891a1f4081bff4
def get_customer(self): <NEW_LINE> <INDENT> return self._customer
Return name of the customer
625941eeeab8aa0e5d26e0a2
def main(): <NEW_LINE> <INDENT> num = int(input()) <NEW_LINE> count = 0 <NEW_LINE> for i in range(2, num+1): <NEW_LINE> <INDENT> if check(i): <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> <DEDENT> print(count)
Find All Primes
625941ee91f36d47f21aca41
def ModifyWorkspace(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('ModifyWorkspace') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params)
Applies an ordered sequence of file modification actions to a workspace. Returns ABORTED if current_snapshot_id in the request does not refer to the most recent update to the workspace. Args: request: (SourceProjectsReposWorkspacesModifyWorkspaceRequest) input message global_params: (StandardQuer...
625941eed268445f265b53b7
def removeDuplicates(self, A): <NEW_LINE> <INDENT> if not A: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> count = 0 <NEW_LINE> i = 1 <NEW_LINE> j = 0 <NEW_LINE> while i < len(A) and j < len(A): <NEW_LINE> <INDENT> if i <= 1 or A[i] != A[j] or A[i] != A[j-1]: <NEW_LINE> <INDENT> j += 1 <NEW_LINE> A[j] = A[i] <NEW_LI...
count = 0 i = 0 state = 0 while i < len(A): if state == 0: if i == 0 or A[i] != A[count-1]: A[count] = A[i] state = 0 count += 1 elif A[i] == A[count-1]: A[count] = A[i] state = 1 count += 1 else: if A[i] != A[count-...
625941ee097d151d1a22339e
def get_complete_motifs_synteny(iadhore_with_aligned_motifs_dict): <NEW_LINE> <INDENT> for key, value in iadhore_with_aligned_motifs_dict.items(): <NEW_LINE> <INDENT> for ke, val in value.items(): <NEW_LINE> <INDENT> if "motifs" not in val.keys(): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> num_of_species = len(li...
Get complete pairs, which have pair in all of the segments :param iadhore_with_aligned_motifs_dict: i-ADHoRe dict with aligned motifs :return: complete motifs synteny
625941eecc40096d61595e96
def GetISOLanguageInfo(self): <NEW_LINE> <INDENT> l_request = skypekit.XCallRequest("ZR\000\317\001", 0, 207) <NEW_LINE> l_response = self.transport.xcall(l_request) <NEW_LINE> l_result = (l_response.get(1, [])), <NEW_LINE> l_result += (l_response.get(2, [])), <NEW_LINE> return l_result
Returns two string lists. First of them will contain list of two-letter language codes (ISO 639-1) The second list contains names of corresponding languages. B{Return values:} - B{language_code_list} - B{language_name_list} - assumes UI has set correct language
625941ee6fece00bbac2dc8d
def compBin(astr, bstr): <NEW_LINE> <INDENT> result = "" <NEW_LINE> chgCount = 0 <NEW_LINE> for c in range(len(astr)): <NEW_LINE> <INDENT> if astr[c] == bstr[c]: <NEW_LINE> <INDENT> result += astr[c] <NEW_LINE> <DEDENT> elif astr[c] != 'X' and bstr[c] != 'X': <NEW_LINE> <INDENT> result += 'X' <NEW_LINE> chgCount += 1 <...
Compare strings with matching lengths containing 0s, 1s and Xs. If Xs are aligned in both strings and only one other character is different, return a string containing an X where a 1 in one string aligns with a 0 in the other string. If an appropriate comparison is not found, return an empty string.
625941ee67a9b606de4a83ff
def take_action(self, position, action): <NEW_LINE> <INDENT> new_position = position <NEW_LINE> if position == -1000: <NEW_LINE> <INDENT> if action == 0: <NEW_LINE> <INDENT> new_position = 1000 <NEW_LINE> <DEDENT> <DEDENT> elif position == 0: <NEW_LINE> <INDENT> if action == 0: <NEW_LINE> <INDENT> new_position = 1000 <...
: action = 0 --> BUY : action = 1 --> SELL : action = 2 --> HOLD
625941eecc0a2c11143dd3da
def t3(): <NEW_LINE> <INDENT> pretty = common.get_test_pretty() <NEW_LINE> print(pretty) <NEW_LINE> b = Broker() <NEW_LINE> w = b.get({'type':'workspace'}) <NEW_LINE> file_name = 'test.log' <NEW_LINE> test_text = 'Log Line 2' <NEW_LINE> guid = base64.urlsafe_b64encode(uuid.uuid1().bytes).replace('=', '') <NEW_LINE> log...
Verifying that a temporary down flocker connection does not cause dropped log lines
625941ee32920d7e50b2871d
def formatweekheader(self): <NEW_LINE> <INDENT> s = ''.join(self.formatweekday(i) for i in self.iterweekdays()) <NEW_LINE> return '<tr><th class="weeknumber"></th>%s</tr>' % s
Return a header for a week as a table row.
625941ee1f5feb6acb0c5092
def timer(step, callback, *args): <NEW_LINE> <INDENT> s = internet.TimerService(step, callback, *args) <NEW_LINE> s.startService() <NEW_LINE> return s
定时器
625941ee5fdd1c0f98dc077e
def __lt__(self, other): <NEW_LINE> <INDENT> if isinstance(other, self.__class__): <NEW_LINE> <INDENT> if self.sign != other.sign: return self.sign < other.sign <NEW_LINE> return self._field_values < other._field_values <NEW_LINE> <DEDENT> elif isinstance(other, Predicate): <NEW_LINE> <INDENT> return self.raw < other.r...
Overloaded boolean operator.
625941eea4f1c619b28b0574
def retrieve_tpu_embedding_adam_parameters_eager_fallback(num_shards, shard_id, table_id=-1, table_name="", name=None, ctx=None): <NEW_LINE> <INDENT> _ctx = ctx if ctx else _context.context() <NEW_LINE> num_shards = _execute.make_int(num_shards, "num_shards") <NEW_LINE> shard_id = _execute.make_int(shard_id, "shard_id"...
This is the slowpath function for Eager mode. This is for function retrieve_tpu_embedding_adam_parameters
625941eecb5e8a47e48b7fea
def p_group_subquery(p): <NEW_LINE> <INDENT> p[0] = ('lambda', p[2])
group : LEFT_PARENTHESIS character RIGHT_PARENTHESIS
625941eef548e778e58cdac8
@to_dict <NEW_LINE> def construct_chain_config_params( args: argparse.Namespace) -> Iterable[Tuple[str, Union[int, str, Tuple[str, ...]]]]: <NEW_LINE> <INDENT> yield 'network_id', args.network_id <NEW_LINE> if args.data_dir is not None: <NEW_LINE> <INDENT> yield 'data_dir', args.data_dir <NEW_LINE> <DEDENT> if args.nod...
Helper function for constructing the kwargs to initialize a ChainConfig object.
625941eef8510a7c17cf9c49
def changeLongCastle(self, boolean): <NEW_LINE> <INDENT> self.long_castle = boolean
Changes long castling rights.
625941eea8ecb033257d3613
def init_moments(self, sample_count): <NEW_LINE> <INDENT> X = self.sample_from_gn(sample_count) <NEW_LINE> P = self.mom_match_proj.get_value(borrow=False) <NEW_LINE> mu, sigma = projected_moments(X, P, ary_type='numpy') <NEW_LINE> self.dist_cov.set_value(to_fX(sigma)) <NEW_LINE> self.dist_mean.set_value(to_fX(mu)) <NEW...
Initialize estimates of the generator distribution's 1st and 2nd-order moments based on some large sample of input noise to the generator network. Estimates will be performed, and subsequently tracked, in a transformed space based on self.mom_match_proj.
625941ee45492302aab5e811
def saver(self, time_step=1 * 60 * 60): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> logging.info(u"CSDNBlogVisitor-save:保存统计信息...") <NEW_LINE> re_try_times = 5 <NEW_LINE> for i in range(re_try_times): <NEW_LINE> <INDENT> info = self.article_info() <NEW_LINE> if info is not None: <NEW_LINE> <INDENT> break <NEW_L...
保存统计数据到数据库
625941ee3539df3088e2e894
def _get_expected_score(player_rating, opponent_rating): <NEW_LINE> <INDENT> expected_score = 1 / (1 + 10 ** ((opponent_rating - player_rating) / 400)) <NEW_LINE> return round(expected_score, 2)
ERROR: type should be string, got "https://wikimedia.org/api/rest_v1/media/math/render/svg/51346e1c65f857c0025647173ae48ddac904adcb\n\nReturns the expected score rounded to two decimals\n\nFor instance, a player with 100 less ELO points than their opponent has an expected score\nof 0.35993500019711494, which is rounded to 0.36 (a 36% 'chance' of winning)"
625941ee5166f23b2e1a56a1
def create_timestamp_anti_leech_url(host, file_name, query_string_dict, encrypt_key, deadline): <NEW_LINE> <INDENT> if query_string_dict is not None and len(query_string_dict) > 0: <NEW_LINE> <INDENT> query_string_items = [] <NEW_LINE> for k, v in query_string_dict.items(): <NEW_LINE> <INDENT> query_string_items.append...
创建时间戳防盗链 Args: host: 带访问协议的域名 file_name: 原始文件名,不需要urlencode query_string_dict: 查询参数,不需要urlencode encrypt_key: 时间戳防盗链密钥 deadline: 链接有效期时间戳(以秒为单位) Returns: 带时间戳防盗链鉴权访问链接
625941ee4527f215b584c99a
def is_protein(string): <NEW_LINE> <INDENT> import re <NEW_LINE> if re.search("[^ARNDCQEGHIKLMFPSTWYV]", string): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
Checks a string using list comprehension for any unallowed characte is_dna("ARQGHI") should return Truers: ['A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'K', 'L', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V'] returns True if it only contains those characters, and False otherwise For Example: is_dna("XPLNNO") should retu...
625941ee15baa723493c44c2
def save_model(self, request, entry, form, change): <NEW_LINE> <INDENT> if not form.cleaned_data.get('excerpt') and entry.status == PUBLISHED: <NEW_LINE> <INDENT> entry.excerpt = Truncator(strip_tags(entry.content)).words(50) <NEW_LINE> <DEDENT> if entry.pk and not request.user.has_perm('zinnia.can_change_author'): <NE...
Save the authors, update time, make an excerpt
625941ee01c39578d7e75384
def _add_edge_op2data( self, agraph: pgv.AGraph, n0: GraphNodeOperation, n1: GraphNodeData, edge_attrs: dict, ): <NEW_LINE> <INDENT> edge_name = edge_attrs.get(DAGNodesGraph.GraphAttrs.OUTPUT_PORT, "") <NEW_LINE> agraph.add_edge( n0, n1, label=f"{edge_name}", **(self._data_edge_style(n1, edge_attrs)), )
Adds an edge from an Operation node to a Data node Args: agraph (pgv.AGraph): graph to add the edge to n0 (GraphNodeOperation): starting node n1 (GraphNodeData): ending node edge_attrs (dict): edge attributes
625941ee7b25080760e3999e