code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> buff.write(_struct_B.pack(self.needs_learning)) <NEW_LINE> <DEDENT> except struct.error as se: self._check_types(se) <NEW_LINE> except TypeError as te: self._check_types(te)
serialize message into buffer :param buff: buffer, ``StringIO``
625941e8167d2b6e31219018
def selPedaleurChanged(self, pedaleur): <NEW_LINE> <INDENT> self.selectedPedaleur=pedaleur <NEW_LINE> self.refreshToolBar()
la selection du Pedaleur a changee modification des actions toolbar
625941e8b830903b967e9d8a
def test_set_url_base_through_init_none_given(self) -> None: <NEW_LINE> <INDENT> given = None <NEW_LINE> expected = "http://localhost:8001" <NEW_LINE> query_tool = CollectionQueryTool(url_base=given) <NEW_LINE> actual = query_tool.url_base <NEW_LINE> self.assertEqual(expected, actual)
Tests the overwritting of the URL to work from through the class constructor. In this test, we test the case that the URL base is not given.
625941e863d6d428bbe44974
def create_builder(package_name, build_tag, build_version, options, pkg_config, build_dir, global_config, user_config, args, builder_class=None): <NEW_LINE> <INDENT> if builder_class in BUILDER_SHORTCUTS: <NEW_LINE> <INDENT> builder_class = BUILDER_SHORTCUTS[builder_class] <NEW_LINE> <DEDENT> if builder_class is None: ...
Create (but don't run) the builder class. Builder object may be used by other objects without actually having run() called.
625941e8a219f33f34628de7
def qs2summary(ar, objects, separator=comma, max_items=5, **kw): <NEW_LINE> <INDENT> elems = [] <NEW_LINE> n = 0 <NEW_LINE> for i in objects: <NEW_LINE> <INDENT> if n: <NEW_LINE> <INDENT> elems.append(separator()) <NEW_LINE> <DEDENT> n += 1 <NEW_LINE> elems += list(ar.summary_row(i, **kw)) <NEW_LINE> if n >= max_items:...
Render a collection of objects as a single paragraph. :param max_items: don't include more than the specified number of items.
625941e8796e427e537b0a4e
def _tag_from_clark(name): <NEW_LINE> <INDENT> match = CLARK_TAG_REGEX.match(name) <NEW_LINE> if match and match.group("namespace") in NAMESPACES_REV: <NEW_LINE> <INDENT> args = { "ns": NAMESPACES_REV[match.group("namespace")], "tag": match.group("tag")} <NEW_LINE> return "%(ns)s:%(tag)s" % args <NEW_LINE> <DEDENT> ret...
Get a human-readable variant of the XML Clark notation tag ``name``. For a given name using the XML Clark notation, return a human-readable variant of the tag name for known namespaces. Otherwise, return the name as is.
625941e8b545ff76a8914299
def debug_exception(type, value, tb): <NEW_LINE> <INDENT> if hasattr(sys, 'ps1') or not sys.stderr.isatty() or not sys.stdin.isatty() or not sys.stdout.isatty() or type==SyntaxError: <NEW_LINE> <INDENT> sys.__excepthook__(type, value, tb) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> import traceback, pdb <NEW_LI...
Provides an interactive debugging session on unhandled exceptions See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65287
625941e8ec188e330fd5ac1a
def disconnect(self,comn): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> comn.close() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(f"断开数据库异常,异常信息为{e}")
断开连接 :param comn: :return:
625941e8e1aae11d1e74a13f
def getStartedBackground(): <NEW_LINE> <INDENT> return "#FFFF00"
Returns the started button color
625941e85fc7496912cc3e01
def get_doc_count_per_site(session): <NEW_LINE> <INDENT> query = session.query(func.count(Document.id), Document.site).group_by(Document.site) <NEW_LINE> pairs = query.all() <NEW_LINE> count_dict = {} <NEW_LINE> for pair in pairs: <NEW_LINE> <INDENT> count, site_str = pair <NEW_LINE> count_dict[Document.Site[site_str]]...
Returns a dict (site -> doc_count) with the current count of documents in the database. Arguments: session -- the db session to use to make the query
625941e8cdde0d52a9e534ba
def click_on_action_button(self, itemText): <NEW_LINE> <INDENT> self.webElement.click()
Selects the provided itemText in the drop down
625941e8a934411ee3751b18
def ocr_metrics(predicts, ground_truth, norm_accentuation=False, norm_punctuation=False): <NEW_LINE> <INDENT> if len(predicts) == 0 or len(ground_truth) == 0: <NEW_LINE> <INDENT> return (1, 1, 1) <NEW_LINE> <DEDENT> cer, wer, ser = [], [], [] <NEW_LINE> for (pd, gt) in zip(predicts, ground_truth): <NEW_LINE> <INDENT> i...
Calculate Character Error Rate (CER), Word Error Rate (WER) and Sequence Error Rate (SER)
625941e810dbd63aa1bd3026
def setUp(self): <NEW_LINE> <INDENT> super(TestPowerFlexDriver, self).setUp() <NEW_LINE> self.configuration = conf.Configuration(driver.powerflex_opts, conf.SHARED_CONF_GROUP) <NEW_LINE> self._set_overrides() <NEW_LINE> self.driver = mocks.PowerFlexDriver(configuration=self.configuration) <NEW_LINE> self.driver.primary...
Setup a test case environment. Creates a ``PowerFlexDriver`` instance Mocks the ``requests.get/post`` methods to return ``MockHTTPSResponse``'s instead.
625941e8956e5f7376d712f0
def bootstrap(self): <NEW_LINE> <INDENT> pass
You can intialize more configs or settings in here
625941e85e10d32532c5f3a9
def indent(elem, level=0, tab=' '): <NEW_LINE> <INDENT> i = '\n' + level * tab <NEW_LINE> j = i + tab <NEW_LINE> indent_parent = False <NEW_LINE> if len(elem): <NEW_LINE> <INDENT> if _is_empty(elem.text): <NEW_LINE> <INDENT> elem.text = j <NEW_LINE> <DEDENT> if _is_empty(elem.tail): <NEW_LINE> <INDENT> elem.tail = i <...
Recursive in-place pretty indenting for an Element Tree. Source: http://effbot.org/zone/element-lib.htm#prettyprint
625941e84a966d76dd551498
def makeSourcePackageRelease(self, archive=None, sourcepackagename=None, distroseries=None, maintainer=None, creator=None, component=None, section_name=None, urgency=None, version=None, builddepends=None, builddependsindep=None, build_conflicts=None, build_conflicts_indep=None, architecturehintlist='all', dsc_maintaine...
Make a `SourcePackageRelease`.
625941e8d4950a0f3b08c7cc
@app.route('/catalog/<string:item_title>/json') <NEW_LINE> def itemJSON(item_title): <NEW_LINE> <INDENT> itemToSerialize = session.query(Item).filter_by( title=item_title).one_or_none() <NEW_LINE> return jsonify(Item=itemToSerialize.serialize)
method/class name: generate json for an item Args: item title Returns: serialized item
625941e8435de62698dfe0d1
def test_orderby_secondary(self): <NEW_LINE> <INDENT> Address, addresses, users, User = (self.classes.Address, self.tables.addresses, self.tables.users, self.classes.User) <NEW_LINE> mapper(Address, addresses) <NEW_LINE> mapper(User, users, properties = dict( addresses = relationship(Address, lazy='select'), )) <NEW_LI...
tests that a regular mapper select on a single table can order by a relationship to a second table
625941e896565a6dacc8fb4e
def getReportInfo(self): <NEW_LINE> <INDENT> self.printMode = False <NEW_LINE> self.teacher = self.db.owner
This version replaces the printer version.
625941e8046cf37aa974d1c7
def timerator(time): <NEW_LINE> <INDENT> if (time[12] == ':'): <NEW_LINE> <INDENT> time = time[slice(0, 11)] + "0" + time[slice(11, 18)] <NEW_LINE> <DEDENT> meridian = slice(-2, 20) <NEW_LINE> hour_str = slice(11, 13) <NEW_LINE> if (time[meridian] == 'AM') and (time[hour_str] == '12'): <NEW_LINE> <INDENT> time = time[s...
This function converts a timestamp from one format to another. Parameters: time (str) : a timestamp, formatted thusly: MM/DD/YYYY HH:MM AM or thusly: MM/DD/YYYY H:MM AM Returns: time (str) : a timestamp, formatted thusly: YYYY-MM-DD_HH:MM
625941e838b623060ff0b271
def overlap(self, other, method='fraction'): <NEW_LINE> <INDENT> checkopts(method, ['fraction', 'rates']) <NEW_LINE> coords_self = self.coordinates.tolist() <NEW_LINE> coords_other = other.coordinates.tolist() <NEW_LINE> intersection = [a for a in coords_self if a in coords_other] <NEW_LINE> nhit = float(len(intersecti...
Compute the overlap between this region and another. Optional methods are a symmetric measure of overlap based on the fraction of intersecting pixels relative to the union ('fraction'), or an assymmetric measure of overlap using precision and recall rates ('rates'). Parameters ---------- other : one region The ...
625941e855399d3f05588b3b
def confirm_url_gen(user): <NEW_LINE> <INDENT> token = default_token_generator.make_token(user) <NEW_LINE> uid = int_to_base36(user.id) <NEW_LINE> url = reverse('consumers:confirm-registration', args=(uid, token,)) <NEW_LINE> return url
Генерация ссылки токена для активации пользователя
625941e8f7d966606f6aa48e
def zip(*iterables): <NEW_LINE> <INDENT> sentinel = object() <NEW_LINE> iterators = [iter(it) for it in iterables] <NEW_LINE> while iterators: <NEW_LINE> <INDENT> result = [] <NEW_LINE> for it in iterators: <NEW_LINE> <INDENT> elem = next(it, sentinel) <NEW_LINE> if elem is sentinel: <NEW_LINE> <INDENT> return <NEW_LIN...
pick one elem from all the input iterables, pack into one elem for output, only terminate when one iterables come to its tail
625941e83617ad0b5ed6837b
def br_case_root_org(person_id): <NEW_LINE> <INDENT> db = current.db <NEW_LINE> s3db = current.s3db <NEW_LINE> if person_id: <NEW_LINE> <INDENT> ctable = s3db.br_case <NEW_LINE> otable = s3db.org_organisation <NEW_LINE> left = otable.on(otable.id == ctable.organisation_id) <NEW_LINE> query = (ctable.person_id == person...
Get the root organisation managing a case Args: person_id: the person record ID Returns: root organisation record ID
625941e81b99ca400220af38
def test_field_filter_prefix(self): <NEW_LINE> <INDENT> return self._field_filter_value( 'title__prefix', self.prefix, self.prefix_count )
Test filter prefix. Example: http://localhost:8000/api/articles/?tags__prefix=bio
625941e891f36d47f21ac97b
def validate_twitter_buffer(driver): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> validate_twitter_buffer = driver.find_element_by_id("twitterBufferLayer_layer") <NEW_LINE> if validate_twitter_buffer.is_displayed(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> retur...
Validation for twitter buffer on map
625941e832920d7e50b28658
def boolean_get(value): <NEW_LINE> <INDENT> if isinstance(value, bool): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> elif isinstance(value, int): <NEW_LINE> <INDENT> return True if value > 0 else False <NEW_LINE> <DEDENT> elif isinstance(value, str): <NEW_LINE> <INDENT> lower_value = value.lower() <NEW_LINE> if...
Get a boolean value from a string. Raise a GetError if the string is not a valid boolean.
625941e882261d6c526ab92a
def test_case_5(self): <NEW_LINE> <INDENT> pass
Test w/ a fix in this commit w/ a committed fix in this code base. :avocado: tags=all :avocado: tags=harness,test_skips :avocado: tags=test_case_5
625941e8187af65679ca55a4
def prep_level(self): <NEW_LINE> <INDENT> self.level_image = self.font.render(str(self.stats.level), True, self.text_color, self.alinv_settings.background_color) <NEW_LINE> self.level_rect = self.level_image.get_rect() <NEW_LINE> self.level_rect.right = self.score_rect.right <NEW_LINE> self.level_rect.top = self.score_...
Turn the level into a rendered image.
625941e8283ffb24f3c55d81
def get_dhcp_addr_from_rt(**kwargs): <NEW_LINE> <INDENT> t.log("inside get_dhcp_addr_from_rt, kwargs is {}".format(kwargs)) <NEW_LINE> rt_handle = t.get_handle(kwargs.get('rt_device_id', 'rt0')) <NEW_LINE> address = list() <NEW_LINE> subs = kwargs.get('subs', bbe.get_subscriber_handles()) <NEW_LINE> for subscriber in s...
get dhcp stats from tester :param kwargs rt_device_id: e.g. 'rt0' subs: bbe subscriber object type: ipv4/ipv6 :return: a list of dhcp stats information
625941e80383005118ecfa65
def evaluate_hessian_at(self, nodes, component=None): <NEW_LINE> <INDENT> if not component is None: <NEW_LINE> <INDENT> values = self.hessian_n[component * self.number_components + component](nodes) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> values = tuple([ f(nodes) for f in self.hessian_n ]) <NEW_LINE> <DEDENT> re...
Evaluate the hessian at some grid nodes :math:`\gamma` for each component :math:`V_{i,j}` of the potential. :param nodes: The grid nodes :math:`\gamma` the hessian gets evaluated at. :param component: The index tuple :math:`\left(i,j\right)` that specifies the potential's entry of which the hessian is evaluated. (Or '...
625941e8097d151d1a2232db
def systemd_unescape(value): <NEW_LINE> <INDENT> parts = value.split('-') <NEW_LINE> return '/'.join(i.encode('ascii').decode('unicode_escape') for i in parts)
abc\x2ddef-ghi -> abc-def/ghi
625941e86aa9bd52df03722b
def update_cookies(cookies=None): <NEW_LINE> <INDENT> if cookies is None: <NEW_LINE> <INDENT> ctrl.COOKIES = requests.get(url=url_index.get('url'), proxies=ctrl.PROXIES, timeout=bs.TIMEOUT).cookies <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ctrl.COOKIES = cookies <NEW_LINE> <DEDENT> logger.info(ctrl.COOKIES) <NEW_LI...
更新或获取cookies :param cookies: :return:
625941e824f1403a92600fe7
def _trunc_to_size(self, subject, message): <NEW_LINE> <INDENT> len_json_sbj = len(json.dumps(subject)) <NEW_LINE> len_sbj = len(subject) <NEW_LINE> len_json_msg = len(json.dumps(message)) <NEW_LINE> len_msg = len(message) <NEW_LINE> if (len_json_sbj + len_json_msg) > 1400: <NEW_LINE> <INDENT> number_to_remove = (len_j...
Truncates the message and subject to fit in a notification message. :param subject: subject of the message to send. :param message: message body of the message. :return: (subject, message) in a truncated form to fit the limitations.
625941e8498bea3a759b9f32
def __init__( self, *, members: Optional[List["JobTarget"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(JobTargetGroup, self).__init__(**kwargs) <NEW_LINE> self.members = members
:keyword members: Members of the target group. :paramtype members: list[~azure.mgmt.sql.models.JobTarget]
625941e830bbd722463cc24d
def testDestroyCIDNotOnly(t, env): <NEW_LINE> <INDENT> res = env.c1.compound([op.destroy_clientid(0), op.reclaim_complete(TRUE)]) <NEW_LINE> check(res, NFS4ERR_NOT_ONLY_OP)
destroy a clientid without session with other compound FLAGS: destroy_clientid all CODE: DESCID7
625941e8cc40096d61595dd3
@public_required <NEW_LINE> @check_object_name <NEW_LINE> def object_export(request, simulation, object_name): <NEW_LINE> <INDENT> dir_name = functions.get_export_directory() <NEW_LINE> filename = functions.object_export_function( simulation, object_name, dir_name) <NEW_LINE> if filename is None: <NEW_LINE> <INDENT> ra...
View to export all instances of a network object.
625941e8ab23a570cc25060b
def test_create(self): <NEW_LINE> <INDENT> nactivity = Activity.objects.count() <NEW_LINE> PersonaFactory() <NEW_LINE> self.assertEqual(Activity.objects.count(), nactivity)
Personaの作成イベントは通知されない
625941e8cc0a2c11143dd316
def testStagesReportReleaseTag(self): <NEW_LINE> <INDENT> current_version = "release_tag_string" <NEW_LINE> archive_urls = { 'board1': 'http://foo.com/bucket/bot-id1/version/index.html', 'board2': 'http://foo.com/bucket/bot-id2/version/index.html',} <NEW_LINE> results_lib.Results.Record('Pass', results_lib.Results.SUCC...
Tests Release Tag entry in stages report.
625941e84f88993c3716c4e7
def apply_selector(objs, selector): <NEW_LINE> <INDENT> out = [] <NEW_LINE> for obj in objs: <NEW_LINE> <INDENT> timer.log('Applying selector: %s' % selector) <NEW_LINE> out += list(jsonselect.match(selector, objs)) <NEW_LINE> timer.log('done applying selector') <NEW_LINE> <DEDENT> return out
Returns a list of objects which match the selector in any of objs.
625941e845492302aab5e74c
def function_with_timestamp(self): <NEW_LINE> <INDENT> return (datetime.now(), self.function())
Return a tuple (timestamp, result). This is the value we actually store in the cache; the benefit is that we can find the time a record was entered. Storing them in the same record helps to avoid race conditions.
625941e8eab8aa0e5d26dfde
def test_ssh_tunnel_bad_port(self): <NEW_LINE> <INDENT> def test(): <NEW_LINE> <INDENT> with mock.patch('paramiko.SSHClient', side_effect=socket.error): <NEW_LINE> <INDENT> Client(endpoint=self.endpoint, ssh_tunnel='unknown_host:2222') <NEW_LINE> <DEDENT> <DEDENT> self.assertRaises(ValueError, test)
When SSHClient returns a socket.error for a bad port, we return ValueError
625941e8d58c6744b42580e3
def get_cached_model(app_label, model_name, regenerate=False, local_hash=lambda i: i._hash): <NEW_LINE> <INDENT> previous_model = models.get_model(app_label, model_name) <NEW_LINE> if previous_model is not None and not regenerate: <NEW_LINE> <INDENT> CACHE_KEY = HASH_CACHE_TEMPLATE % (app_label, model_name) <NEW_LINE> ...
Return the locally cached model (from Django's model cache). Returns None if there is no cached model, or if it is out of date.
625941e844b2445a33932517
def test_delete_comment_keep_notification(self): <NEW_LINE> <INDENT> s = mixer.blend('solution.solution', title="My Solution") <NEW_LINE> bill = mixer.blend('joltem.user', first_name="Bill") <NEW_LINE> jill = mixer.blend('joltem.user', first_name="Jill") <NEW_LINE> s.add_comment(bill, "Bill was here.") <NEW_LINE> jill_...
Test comment deleted but notification should be kept.
625941e81f037a2d8b946681
def gen_random(): <NEW_LINE> <INDENT> num1 = [] <NEW_LINE> num2 = [] <NEW_LINE> while len(num1) != 5: <NEW_LINE> <INDENT> new_num1 = randint(1, 50) <NEW_LINE> if new_num1 not in num1: <NEW_LINE> <INDENT> num1.append(new_num1) <NEW_LINE> <DEDENT> <DEDENT> num1.sort() <NEW_LINE> while len(num2) != 2: <NEW_LINE> <INDENT> ...
Just randomize the combination
625941e82eb69b55b151cd3a
def parse_line(line, parser): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return parser.parse(line) <NEW_LINE> <DEDENT> except apachelog.ApacheLogParserError as err: <NEW_LINE> <INDENT> logger.error(err)
Parse line from Apache log and return parsed request as dictionary.
625941e8851cf427c661a98f
def get_tasks(queue_name, index=None, expected_count=None): <NEW_LINE> <INDENT> from google.appengine.api import apiproxy_stub_map <NEW_LINE> stub = apiproxy_stub_map.apiproxy.GetStub('taskqueue') <NEW_LINE> tasks = stub.GetTasks(queue_name) <NEW_LINE> if expected_count is not None: <NEW_LINE> <INDENT> assert len(tasks...
Retrieves Tasks from the supplied named queue. Args: queue_name: The queue to access. index: Index of the task (ordered by ETA) to retrieve from the queue. expected_count: If not None, the number of tasks expected to be in the queue. This function will raise an AssertionError exception if there are more ...
625941e826068e7796caf16b
def get_balance(self, force_refresh=False): <NEW_LINE> <INDENT> return self.__socket.balance()
获取资金账户信息 :param force_refresh: 强制刷新,暂未开放,默认既为强制刷新 :type force_refresh: bool :return: 返回股票持仓 :rtype: list
625941e87b25080760e398db
def _cast_ints(items): <NEW_LINE> <INDENT> new_items = [] <NEW_LINE> for item in items: <NEW_LINE> <INDENT> new_item = {} <NEW_LINE> for key, value in item.items(): <NEW_LINE> <INDENT> if isinstance(value, list): <NEW_LINE> <INDENT> new_item[key] = [_cast_num(x) for x in value] <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND...
Temp method to cast int fields until we find a better way.
625941e8cad5886f8bd2745d
def default(self, args): <NEW_LINE> <INDENT> functions = {"all": self.do_all, "update": self.do_update, "show": self.do_show, "count": self.do_count, "destroy": self.do_destroy, "update": self.do_update} <NEW_LINE> args = (args.replace("(", ".").replace(")", ".") .replace('"', "").replace(",", "").split(".")) <NEW_LINE...
Catches all the function names that are not expicitly defined.
625941e8566aa707497f49e7
@infix_operator('|') <NEW_LINE> def contains(left, right): <NEW_LINE> <INDENT> return right in left
Return ``True`` if sequence *right* occurs in sequence *left*. Delimited by ``|``. This is an alias for Python expression ``right in left``. Examples:: >>> [1, 2, 3] |contains| 1 True >>> [1, 2, 3] |contains| 0 False >>> "foobar" |contains| "a" True
625941e899cbb53fe679306a
def add_pic_to_html(qchtml, pic): <NEW_LINE> <INDENT> relpath = os.path.relpath(pic,os.path.dirname(qchtml.name)) <NEW_LINE> qchtml.write('<a href="'+ relpath + '" >') <NEW_LINE> qchtml.write('<img src="' + relpath + '" > ') <NEW_LINE> qchtml.write('</a><br>\n') <NEW_LINE> return qchtml
Adds a pic to an html page with this handler "qchtml"
625941e8cc0a2c11143dd317
def transpose(node: BaseNode, permutation: Sequence[Union[Text, int]], name: Optional[Text] = None, axis_names: Optional[List[Text]] = None) -> BaseNode: <NEW_LINE> <INDENT> if not hasattr(node, 'backend'): <NEW_LINE> <INDENT> raise AttributeError('Node {} of type {} has no `backend`'.format( node, type(node))) <NEW_LI...
Transpose `node` Args: node: A `BaseNode`. permutation: A list of int or str. The permutation of the axis. name: Optional name to give the new node. axis_names: Optional list of names for the axis. Returns: A new node. The transpose of `node`. Raises: AttributeError: If `node` has no `backend` attribute,...
625941e8dc8b845886cb59bb
def get_topmost_card(self): <NEW_LINE> <INDENT> if len(self.cards) > 0: <NEW_LINE> <INDENT> return self.cards[-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
returns top card in the pile, but DOES NOT remove it from pile
625941e88e05c05ec3eea7fd
def check_spam(self, user, message): <NEW_LINE> <INDENT> if not self.enable_spam_check: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> msg = message.lower() <NEW_LINE> for nick in self.bot.userlist[self.channel]: <NEW_LINE> <INDENT> msg = msg.replace(nick.lower(), "<user>") <NEW_LINE> <DEDENT> self.msg_buffer[use...
Check if message is just repeated spam
625941e815baa723493c43fe
def get_storagestats(self): <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> self.stats['bytesfree'] = 0 <NEW_LINE> self.stats['bytesused'] = 0 <NEW_LINE> self.stats['quota'] = 0 <NEW_LINE> self.stats['filecount'] = 0
Here goes all the necessary logic to query the storage endpoint to obtain the storage stats. Check existing SubClasses for examples. Ideally we need to assing values to the following attributes, either obtained from the endpoint, from the endpoints.conf file or defaults
625941e8462c4b4f79d1db54
def list_template_functions(self, ctxt, template_version, with_condition=False): <NEW_LINE> <INDENT> return self.call(ctxt, self.make_msg('list_template_functions', template_version=template_version, with_condition=with_condition), version='1.35')
Get a list of available functions in a given template. :param ctxt: RPC context :param template_name : name of the template which function list you want to get :param with_condition: return includes condition functions.
625941e8851cf427c661a990
def save_raster(self, filename): <NEW_LINE> <INDENT> from chaco.api import PlotGraphicsContext <NEW_LINE> gc = PlotGraphicsContext(self.outer_bounds, dpi=72) <NEW_LINE> self.draw(gc, mode="normal") <NEW_LINE> gc.save(filename) <NEW_LINE> return
Saves an image of a chaco component (e.g. 'Plot' or 'Container') to a raster file, such as .jpg or .png. The file type is terermined by the extension.
625941e8e8904600ed9f23b9
def GetChromosomeLength(GFF, ChromoGeneCoord, AssemblyRef): <NEW_LINE> <INDENT> Chromos = list(ChromoGeneCoord.keys()) <NEW_LINE> ChromoLength = {} <NEW_LINE> infile = open(GFF) <NEW_LINE> for line in infile: <NEW_LINE> <INDENT> if AssemblyRef in line and not line.startswith('#'): <NEW_LINE> <INDENT> line = line.rstrip...
(file, dict. str) -> dict Take the GFF file, and a dictionary with gene coordinates on each chromosome, a string with the assembly name and and return a dictionary with pairs of chromosome and their length
625941e8a05bb46b383ecca2
@pytest.fixture(name="bypass_platform_setup") <NEW_LINE> def bypass_platform_setup_fixture(): <NEW_LINE> <INDENT> with patch( "homeassistant.components.waze_travel_time.sensor.async_setup_entry", return_value=True, ): <NEW_LINE> <INDENT> yield
Bypass platform setup.
625941e84f6381625f114ec0
def movels(self, pose_list, acc=0.01, vel=0.01, radius=0.01, wait=True, threshold=None): <NEW_LINE> <INDENT> return self.movexs("movel", pose_list, acc, vel, radius, wait, threshold=threshold)
Concatenate several movel commands and applies a blending radius pose_list is a list of pose. This method is useful since any new command from python to robot make the robot stop
625941e860cbc95b062c69c8
def rpn_cross_entropy(input, target): <NEW_LINE> <INDENT> mask_ignore = target == -1 <NEW_LINE> mask_calcu = 1 - mask_ignore <NEW_LINE> loss = F.cross_entropy(input=input[mask_calcu], target=target[mask_calcu], size_average=False) <NEW_LINE> return loss
:param input: (15x15x5,2) :param target: (15x15x5,) :return:
625941e855399d3f05588b3c
def update(self): <NEW_LINE> <INDENT> if self.moving_right and self.rect.right < self.screen_rect.right: <NEW_LINE> <INDENT> self.center += self.ai_settings.ship_speed_factor <NEW_LINE> <DEDENT> if self.moving_left and self.rect.left > 0: <NEW_LINE> <INDENT> self.center -= self.ai_settings.ship_speed_factor <NEW_LINE> ...
change ship location by moving flag
625941e860cbc95b062c69c9
def extract_dataFeatureSelection_ranking(self, data_model_I=None, raise_I=False): <NEW_LINE> <INDENT> if data_model_I: data_model=data_model_I; <NEW_LINE> else: data_model = self.data_featureSelection; <NEW_LINE> data_model = self.get_finalEstimator(data_model); <NEW_LINE> impfeat_values_O,impfeat_scores_O = None,None ...
extract out the ranking from a feature selection data model INPUT: data_model_I = feature selection model
625941e8b545ff76a891429a
def reverse(self, x): <NEW_LINE> <INDENT> x_1 = x <NEW_LINE> if x < 0: <NEW_LINE> <INDENT> x = abs(x) <NEW_LINE> <DEDENT> digits = len(str(x)) <NEW_LINE> ans = 0 <NEW_LINE> curr = digits <NEW_LINE> while curr != 0: <NEW_LINE> <INDENT> new = x // (10 ** (curr - 1)) <NEW_LINE> ans += new * (10 ** (digits - curr)) <NEW_LI...
:type x: int :rtype: int
625941e816aa5153ce3628fd
def CreateMatchup(floridaLineupNumber, opponentLineupNumber, time, floridaScore, opponentScore): <NEW_LINE> <INDENT> global matchupsList <NEW_LINE> floridaBigs = CheckFloridaBigs(floridaLineups[floridaLineupNumber]) <NEW_LINE> opponentBigs = CheckOpponentBigs(opponentLineups[opponentLineupNumber]) <NEW_LINE> matchup = ...
Create matchup between lineups, check num of bigs.
625941e8b57a9660fec33d0f
@contextlib.contextmanager <NEW_LINE> def temporary_historian(db_name: str = ''): <NEW_LINE> <INDENT> archive_uri = mince_testing.create_archive_uri(get_base_uri(), db_name) <NEW_LINE> with mince_testing.temporary_historian(archive_uri) as historian: <NEW_LINE> <INDENT> pyos.db.init(historian, use_globally=False) <NEW_...
Create a temporary database using the base archive URI and the given db name or a random one. Yields a tuple consisting of the archive uri and the historian
625941e8d486a94d0b98e5cc
def get_data( self, rng: FullRange | str | None = None, value_type: GoogleValueType = EffectiveVal, ) -> Tab: <NEW_LINE> <INDENT> rng = self.ensure_full_range(self.full_range(), rng) <NEW_LINE> if not rng.tab_title: <NEW_LINE> <INDENT> rng.tab_title = self._title <NEW_LINE> <DEDENT> self._values, self._formats = self._...
Gets the data from the cells of this Tab. .. note:: This method will cause a request to be posted to the relevant Google API immediately. Args: rng (FullRange | HalfRange, optional): An optional range value, to specify a subset of the Tab's values to get, defaults to None, which fetches a...
625941e84e4d5625662d4856
def assert_summaries(self, test_case, expected_logdir=None, expected_graph=None, expected_summaries=None, expected_added_graphs=None, expected_added_meta_graphs=None, expected_session_logs=None): <NEW_LINE> <INDENT> if expected_logdir is not None: <NEW_LINE> <INDENT> test_case.assertEqual(expected_logdir, self._logdir)...
Assert expected items have been added to summary writer.
625941e832920d7e50b28659
def _get_pos_indexers(self, indices, indexers): <NEW_LINE> <INDENT> pos_indexers = {} <NEW_LINE> indexer_dims = [idx.dims for idx in indexers.values()] <NEW_LINE> indexer_shapes = [idx.shape for idx in indexers.values()] <NEW_LINE> if len(set(indexer_dims)) > 1: <NEW_LINE> <INDENT> raise ValueError('All indexers must h...
Returns positional indexers based on the query results and the original (label-based) indexers. 1. Unravel the (flattened) indices returned from the query 2. Reshape the unraveled indices according to indexers shapes 3. Wrap the indices in xarray.Variable objects.
625941e8bd1bec0571d90ab4
def getCommand(protocol, params): <NEW_LINE> <INDENT> pass
Get the C{ICommand} provider with the given parameters. The first parameter is used to determine the plugin to locate the command in. @raise eridanus.errors.PluginNotInstalled: If the plugin parameter specifies a plugin that is not installed @raise eridanus.errors.UsageError: If there is any problem locating ...
625941e8d164cc61757831d4
def print_separator(*args, **kwargs): <NEW_LINE> <INDENT> separator = "-" * 80 <NEW_LINE> print(separator) <NEW_LINE> the_function(*args, **kwargs) <NEW_LINE> print(separator, "\n")
Surrounds `the_function` with a separator and add a new line.
625941e84c3428357757c7aa
def get_department_level_grade_data_with_given_term(self, term_id, **kwargs): <NEW_LINE> <INDENT> response = self._requester.request( "GET", "accounts/{}/analytics/terms/{}/grades".format(self.id, term_id), _kwargs=combine_kwargs(**kwargs), ) <NEW_LINE> return response.json()
Return the distribution of all available or concluded grades with the given term :calls: `GET /api/v1/accounts/:account_id/analytics/terms/:term_id/grades <https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.department_grades>`_ :param term_id: The ID of the term, or the strings "curren...
625941e830c21e258bdfa927
def get_service_type(service, services_glob): <NEW_LINE> <INDENT> services, types = get_services_and_types(services_glob) <NEW_LINE> try: <NEW_LINE> <INDENT> return types[services.index(service)] <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> return ""
Returns the type of the specified ROS service,
625941e829b78933be1e5b2b
def code_to_coef(self): <NEW_LINE> <INDENT> self.dimension = int(self.code[0]) <NEW_LINE> self.order = int(self.code[1]) <NEW_LINE> self.set_polynom_length() <NEW_LINE> self.coef = [ [ (CODEDICT[ord(_)] + CODERANGE[0]) * self.code_step for _ in self.code[ 3 + __ * self.poly_length : 3 + (__ + 1) * self.poly_length ] ] ...
Convert a Sprott (=ASCII) code to a set of real coefficients for the attractor
625941e8fff4ab517eb2f8c4
def on_intent(intent_request, session): <NEW_LINE> <INDENT> print("on_intent requestId=" + intent_request['requestId'] + ", sessionId=" + session['sessionId']) <NEW_LINE> intent = intent_request['intent'] <NEW_LINE> intent_name = intent_request['intent']['name'] <NEW_LINE> if intent_name == "ConnectivityIntent": <NEW_L...
Called when the user specifies an intent for this skill
625941e863f4b57ef0001591
def _get_var_memory(self, address): <NEW_LINE> <INDENT> if address < self.var_current(): <NEW_LINE> <INDENT> return self.scalars.get_memory(address) <NEW_LINE> <DEDENT> elif address < self.var_current() + self.arrays.current: <NEW_LINE> <INDENT> return self.arrays.get_memory(address) <NEW_LINE> <DEDENT> elif address > ...
Retrieve data from data memory.
625941e8e76e3b2f99f3ac89
def __init__(self, red, green, blue): <NEW_LINE> <INDENT> self.red = red <NEW_LINE> self.green = green <NEW_LINE> self.blue = blue
This function ... :param red: :param green: :param blue:
625941e8cb5e8a47e48b7f29
def _prep_scores(self, scorer, subset='train'): <NEW_LINE> <INDENT> columns = ["metric", "value"] <NEW_LINE> scores = {"Precision": scorer.scores["ents_p"], "Recall": scorer.scores["ents_r"], "F-score": scorer.scores["ents_f"]} <NEW_LINE> metrics_df = pd.DataFrame([(k, v) for k, v in scores.items()], columns=columns) <...
Prepare score metrics using a spaCy scrorer Returns a dataframe formatted for output
625941e8a17c0f6771cbe4d5
@app.route("/decrypt", methods=["GET", "POST"]) <NEW_LINE> def decrypt(): <NEW_LINE> <INDENT> global KEY <NEW_LINE> if request.method == "POST": <NEW_LINE> <INDENT> data = base64.b64decode(request.form["token"].encode()) <NEW_LINE> IV = base64.b64decode(request.form["IV"].encode()) <NEW_LINE> cipher = AES.new(KEY, AES....
Decrypt phrase client has and report if padding is correct or not
625941e8f9cc0f698b140a7d
def handle_param_desc(column, data): <NEW_LINE> <INDENT> params = [] <NEW_LINE> if isinstance(data, list): <NEW_LINE> <INDENT> if len(data) > 0: <NEW_LINE> <INDENT> for row in data: <NEW_LINE> <INDENT> param = handle_param(column, row) <NEW_LINE> if param is not None: <NEW_LINE> <INDENT> params.append(param) <NEW_LINE>...
处理参数类型
625941e8460517430c3945fe
def subgradient_method(oracle, x_0, tolerance=1e-2, max_iter=1000, alpha_0=1, display=False, trace=False): <NEW_LINE> <INDENT> history = defaultdict(list) if trace else None <NEW_LINE> x_k = np.copy(x_0) * 1.0 <NEW_LINE> f_k = oracle.func(x_k) <NEW_LINE> minF_x = np.copy(f_k) <NEW_LINE> minX_k = np.copy(x_k) <NEW_LINE>...
Subgradient descent method for nonsmooth convex optimization. Parameters ---------- oracle : BaseNonsmoothConvexOracle-descendant object Oracle with .func() and .subgrad() methods implemented for computing function value and its one (arbitrary) subgradient respectively. If avaliable, .duality_gap() method ...
625941e81d351010ab855fa0
def __path_adapter(self, fn, path, **kwargs): <NEW_LINE> <INDENT> log = logging.getLogger('udiskie.mount.%s' % fn.__name__) <NEW_LINE> device = self.udisks.find(path) <NEW_LINE> if device: <NEW_LINE> <INDENT> log.debug('found device owning "%s": "%s"' % (path, device)) <NEW_LINE> return fn(device, **kwargs) <NEW_LINE> ...
Internal method.
625941e857b8e32f52483923
def main(): <NEW_LINE> <INDENT> G = setup_recipe() <NEW_LINE> print_strongly_connected_components(G)
The main function.
625941e873bcbd0ca4b2c4fb
def create_model(self, model_input, vocab_size, num_mixtures=None, hidden_size=None, l2_penalty=1e-5, is_training=True, **unused_params): <NEW_LINE> <INDENT> num_mixtures = num_mixtures or FLAGS.moe_num_mixtures <NEW_LINE> hidden_size = hidden_size or FLAGS.moe_hidden_size <NEW_LINE> print('model_input:',model_input) <...
Creates a Mixture of (Logistic) Experts model. The model consists of a per-class softmax distribution over a configurable number of logistic classifiers. One of the classifiers in the mixture is not trained, and always predicts 0. Args: model_input: 'batch_size' x 'num_features' matrix of input features. vocab...
625941e8ad47b63b2c50a404
def grab_cache(self, grab): <NEW_LINE> <INDENT> if grab in self.cache.keys(): return self.cache[grab] <NEW_LINE> else: <NEW_LINE> <INDENT> function = getattr(self.game, "fetch_{}".format(grab)) <NEW_LINE> if grab == "technologies": <NEW_LINE> <INDENT> fetched = function() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> f...
Return cached version of requested if it exists. If not make cached entry.
625941e8fb3f5b602dac3b1d
def main(): <NEW_LINE> <INDENT> retvals = [] <NEW_LINE> if len(sys.argv) < 2: <NEW_LINE> <INDENT> pages = [ ('http://www.binpress.com/', False), ('http://david.li/flow/', False), ('https://imzdl.com/', False), ('http://www.20min.ch/', True), ('http://www.the-compiler.org/', True), ('http://phoronix.com', True), ('http:...
Main entry point.
625941e8b57a9660fec33d10
def _checked_filter(self, field): <NEW_LINE> <INDENT> return (field in self._active_fields)
Checked filter method for the EntityFieldMenu. Determines whether the given field should be checked in the field menu. :param field: The field name being processed.
625941e8a8370b7717052d23
def EpilogRead(self, eof, progupdate): <NEW_LINE> <INDENT> if self.options.demo_verbose: <NEW_LINE> <INDENT> print("DEMO: %s:EpilogRead(eof)" % self.__class__.__name__)
Callback message: file epilog section has been read. Progress 0-100.
625941e894891a1f4081bf31
def validate_subscription_with_http_info(self, sub_id, validation_callback_request, **kwargs): <NEW_LINE> <INDENT> all_params = ['sub_id', 'validation_callback_request'] <NEW_LINE> all_params.append('callback') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_...
Validate Subscription Validate Subscription This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.validate_subscripti...
625941e8b830903b967e9d8b
def write_raw_block(self, block, height): <NEW_LINE> <INDENT> with util.open_truncate(self.raw_block_path(height)) as f: <NEW_LINE> <INDENT> f.write(block) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> del_height = self.min_undo_height(height) - 1 <NEW_LINE> os.remove(self.raw_block_path(del_height)) <NEW_LINE> <DEDENT>...
Write a raw block to disk.
625941e85fcc89381b1e1b48
def maxNumberOfBalloons(self, text: str) -> int: <NEW_LINE> <INDENT> balloon_counter = Counter("balloon") <NEW_LINE> text_counter = Counter(text) <NEW_LINE> numbers = [] <NEW_LINE> for c, count in balloon_counter.items(): <NEW_LINE> <INDENT> numbers.append(text_counter.get(c, 0) // count) <NEW_LINE> <DEDENT> return min...
>>> s = Solution() >>> s.maxNumberOfBalloons("nlaebolko") 1 >>> s.maxNumberOfBalloons("loonbalxballpoon") 2 >>> s.maxNumberOfBalloons("leetcode") 0
625941e8004d5f362079a7b6
def P(word): <NEW_LINE> <INDENT> N=sum(WORDS.values()) <NEW_LINE> return WORDS[word] / N
args: `word`: word for which we need to find probability (string) `N`: the sum of all the word counts (integer) returns: Probability of the given `word` from the WORDS.
625941e823849d37ff7b3511
def __init__(self, root_dir='../images/train', train=True, use_depth=False, data_transform=None, depth_transform=None, H=160, W=608, num_test=None): <NEW_LINE> <INDENT> self.root_dir = root_dir <NEW_LINE> self.train = train <NEW_LINE> self.use_depth = use_depth <NEW_LINE> self.data_transform = data_transform <NEW_LINE>...
Args: root_dir (string): Directory with all the images. transform (callable, optional): Optional transform to be applied on a sample.
625941e8be7bc26dc91cda7d
def send_transaction(addr_from, private_key, addr_to, amount): <NEW_LINE> <INDENT> print(len(private_key), private_key) <NEW_LINE> if len(private_key) == 64: <NEW_LINE> <INDENT> signature, message = sign_ECDSA_msg(private_key) <NEW_LINE> url = base_url + '/txion' <NEW_LINE> payload = {"from": addr_from, "to": addr_to, ...
Sends your transaction to different nodes. Once any of the nodes manage to mine a block, your transaction will be added to the blockchain. Despite that, there is a low chance your transaction gets canceled due to other nodes having a longer chain. So make sure your transaction is deep into the chain before claiming it ...
625941e89f2886367277ad0f
def loadtrain(FN, delim='|'): <NEW_LINE> <INDENT> return load(FN, delim, hasY=True)
alias for load() for training data
625941e8796e427e537b0a50
def get_country_id(self, cr, uid, code, context=None): <NEW_LINE> <INDENT> country_obj = self.pool.get('res.country') <NEW_LINE> return country_obj.search(cr, uid, [('code', '=', code)], context=context)[0]
Returns the id of the country from the code.
625941e85166f23b2e1a55df
def getContigSizes(self, with_synonyms=True): <NEW_LINE> <INDENT> if not self.mIsLoaded: <NEW_LINE> <INDENT> self._loadIndex() <NEW_LINE> <DEDENT> contig_sizes = {} <NEW_LINE> for key, val in list(self.mIndex.items()): <NEW_LINE> <INDENT> contig_sizes[key] = self.getLength(key) <NEW_LINE> <DEDENT> if with_synonyms: <NE...
return hash with contig sizes including synonyms.
625941e8ec188e330fd5ac1b
def normalise_dict(d): <NEW_LINE> <INDENT> out = {} <NEW_LINE> for k, v in d.items(): <NEW_LINE> <INDENT> if hasattr(v, 'items'): <NEW_LINE> <INDENT> out[k] = normalise_dict(v) <NEW_LINE> <DEDENT> elif isinstance(v, list): <NEW_LINE> <INDENT> out[k] = [] <NEW_LINE> for item in sorted(v): <NEW_LINE> <INDENT> if hasattr(...
Recursively convert dict-like object (eg OrderedDict) into plain dict. And sorts list values. :param d: dict input
625941e8e1aae11d1e74a142
def do_load(file_specifier, output_ws_name, ipf_filename, load_logs, load_opts): <NEW_LINE> <INDENT> from mantid.simpleapi import LoadVesuvio, LoadParameterFile <NEW_LINE> if 'VESUVIO' in ipf_filename: <NEW_LINE> <INDENT> LoadVesuvio(Filename=str(file_specifier), OutputWorkspace=output_ws_name, SpectrumList='1-198', **...
Loads the files, passing the given file specifier in the load command. :param file_specifier: The file specifier (single file, range or sum) :param output_ws_name: The name of the output workspace to create :param ipf_filename: The instrument parameter file to load with :param load_opts: Additional loading ...
625941e885dfad0860c3b2e2