code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def QR_algorithm(A,niter,tol): <NEW_LINE> <INDENT> pass | Return the eigenvalues of A using the QR algorithm. | 625941ea5f7d997b87174f6b |
def show_report(self): <NEW_LINE> <INDENT> self.report.page.add_css("table { width: 95%; }") <NEW_LINE> self.report.send() | Override to apply some custom styling. | 625941ead7e4931a7ee9e3ed |
def from_structures(self, structures, cutoff=4.0, step_freq=10, qhull_options="Qbb Qc Qz"): <NEW_LINE> <INDENT> print("This might take a while...") <NEW_LINE> voro_dict = {} <NEW_LINE> step = 0 <NEW_LINE> for structure in structures: <NEW_LINE> <INDENT> step += 1 <NEW_LINE> if step % step_freq != 0: <NEW_LINE> <INDENT>... | A constructor to perform Voronoi analysis on a list of pymatgen structrue objects
Args:
structures (list): list of Structures
cutoff (float: cutoff distance around an atom to search for neighbors
step_freq (int): perform analysis every step_freq steps
qhull_options (str): options to pass to qhull
Retur... | 625941ea30c21e258bdfa971 |
def _stream_queried_data(self, mapping, local_ids, query): <NEW_LINE> <INDENT> statics = self._get_statics(mapping) <NEW_LINE> total_rows = 0 <NEW_LINE> if mapping.anchor_date: <NEW_LINE> <INDENT> date_context = mapping.get_relative_date_context( mapping.get_load_field_list(), self.sf ) <NEW_LINE> <DEDENT> batch_size =... | Get data from the local db | 625941ea50485f2cf553d26a |
def test_get_disease_list_CHD_Male(self): <NEW_LINE> <INDENT> Disease = "Coronary heart disease (CHD)" <NEW_LINE> get_disease = get_disease_list(45, "Male", 4) <NEW_LINE> self.assertTrue(Disease in get_disease) | Test when user input age, gender, sleep hour, and application can suggest disease correctly. | 625941eafb3f5b602dac3b67 |
def _rms(self, x: np.ndarray) -> np.ndarray: <NEW_LINE> <INDENT> return np.sqrt(np.nanmean(np.square(x))) | Determine root mean square (RMS)
Args:
x: Array with data
Returns:
RMS for given data | 625941ea1f037a2d8b9466cb |
def authorize(key, secret): <NEW_LINE> <INDENT> req = build_request(build_credentials(key, secret)) <NEW_LINE> try: <NEW_LINE> <INDENT> resp = urllib2.build_opener(VerifiedHTTPSHandler()).open(req) <NEW_LINE> out = json.load(resp) <NEW_LINE> resp.close() <NEW_LINE> return {'Authorization': 'Bearer ' + out[u'access_toke... | Given a consumer key and consumer secret, return a dict representing the
HTTP Authorization header containing valid Bearer credentials for use in
subsequent API requests. | 625941ea66656f66f7cbc67b |
def loadJSON(self,jsondata): <NEW_LINE> <INDENT> self.jsondata = jsondata | loads the dictionary object as this class' JSON data
to process..
Inputs:
jsondata [dict]
JSON object to load. | 625941ea71ff763f4b549b63 |
def __init__(self): <NEW_LINE> <INDENT> coil.Configurable.__init__(self) <NEW_LINE> widgets.Gadget.__init__(self) <NEW_LINE> widgets.Presentation.__init__(self) | Initialize.
| 625941eacc0a2c11143dd361 |
def inversion_number(self): <NEW_LINE> <INDENT> inversion_num = 0 <NEW_LINE> asm_matrix = self.to_matrix() <NEW_LINE> nonzero_cells = asm_matrix.nonzero_positions() <NEW_LINE> for (i, j) in nonzero_cells: <NEW_LINE> <INDENT> for (k, l) in nonzero_cells: <NEW_LINE> <INDENT> if i > k and j < l: <NEW_LINE> <INDENT> invers... | Return the inversion number of ``self``.
If we denote the entries of the alternating sign matrix as `a_{i,j}`,
the inversion number is defined as `\sum_{i>k}\sum_{j<l}a_{i,j}a_{k,l}`.
When restricted to permutation matrices, this gives the usual inversion
number of the permutation.
This definition is equivalent to th... | 625941ea57b8e32f5248396d |
def test_multi_scope_fail(self): <NEW_LINE> <INDENT> self.client.login(username="test_user", password="123456") <NEW_LINE> authcode_data = { "client_id": self.application.client_id, "state": "random_state_string", "scope": "scope1 scope3", "redirect_uri": "http://example.org", "response_type": "code", "allow": True, } ... | Test access to a multi-scope protected resource with wrong scopes provided | 625941ea6fb2d068a760f574 |
def switch_platform(self, index): <NEW_LINE> <INDENT> config.set("platform", config.platforms[index]) <NEW_LINE> self.setup() | This has no effect on the display!
It is assumed that the display is already updated, or will be
updated later.
Invalidates the installation for another platform. | 625941ea30dc7b7665901e30 |
def test_derived_order(): <NEW_LINE> <INDENT> o3 = Test3(None) <NEW_LINE> o3['a'] = (None,930016275284.81763) <NEW_LINE> o3['b'] = (None,3000000000.0) <NEW_LINE> tools.assert_equal(o3.d(),o3.a()-o3.b()/2.0) | Test that drived value arguments appeare in proper order. | 625941ea851cf427c661a9d9 |
def get_xy(self, q=None): <NEW_LINE> <INDENT> if q is None: <NEW_LINE> <INDENT> q = self.q <NEW_LINE> <DEDENT> x = self.L[0]*np.cos(q[0]) + self.L[1]*np.cos(q[0]+q[1]) + self.L[2]*np.cos(np.sum(q)) <NEW_LINE> y = self.L[0]*np.sin(q[0]) + self.L[1]*np.sin(q[0]+q[1]) + self.L[2... | Returns the corresponding hand xy coordinates for
a given set of joint angle values [shoulder, elbow, wrist],
and the above defined arm segment lengths, L
q : np.array
the list of current joint angles
returns : list
the [x,y] position of the arm | 625941eaa05bb46b383eccec |
def name(self): <NEW_LINE> <INDENT> return _analog_swig.feedforward_agc_cc_sptr_name(self) | name(feedforward_agc_cc_sptr self) -> std::string | 625941eabf627c535bc1369e |
def close_r(self): <NEW_LINE> <INDENT> if self.r: <NEW_LINE> <INDENT> os.close(self.r) <NEW_LINE> self.r = None | close reading side of the pipe | 625941ea009cb60464c6387c |
def download(ftp, filename): <NEW_LINE> <INDENT> f = open(filename,"wb").write <NEW_LINE> try: <NEW_LINE> <INDENT> ftp.retrbinary("RETR %s"%filename, f, buffer_size) <NEW_LINE> print('成功下载文件: "%s"' % filename) <NEW_LINE> <DEDENT> except ftplib.error_perm: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | 下载文件
:param ftp: 实例化的FTP对象
:param filename: 需要从FTP下载的文件名
:return: | 625941ea3346ee7daa2b323f |
@app.route('/initdb') <NEW_LINE> def initdb_command(): <NEW_LINE> <INDENT> init_db() <NEW_LINE> return redirect('/') | Creates the database tables. | 625941ea4f88993c3716c531 |
def make_private(modeladmin, request, queryset): <NEW_LINE> <INDENT> with transaction.atomic(): <NEW_LINE> <INDENT> for o in queryset.all(): <NEW_LINE> <INDENT> o.status = 'private' <NEW_LINE> o.save() | Action for administrative interface to hide things.
See note in :py:func:`make_published` about efficiency. | 625941eafbf16365ca6f669d |
def __init__(self, redis: StrictRedis=None, host: str='127.0.0.1', port: int=6379, db: int=0, password: str=None): <NEW_LINE> <INDENT> self._log: Logger = logger(self.__class__.__name__) <NEW_LINE> log = self._log <NEW_LINE> if redis: <NEW_LINE> <INDENT> self._r = redis <NEW_LINE> log.info("Initialized a new Bus Writer... | Instantiates a new Bus Writer.
You can either pass an existing Redis instance or
initialize a new Redis instance by providing host, port,
db and password
:param redis: An already initialized Redis instance
:param host: Redis host
:param port: Redis host port
:param db: Redis database
:param password: Redis password | 625941ead10714528d6001b8 |
def route_fitness(self, distance:float): <NEW_LINE> <INDENT> return 1 / float(distance) | Calculates the fitness as the inverse of the total distance
:param distance: Total distance for route
:return fitness: Fitness given the distance | 625941ea73bcbd0ca4b2c544 |
def factI(n): <NEW_LINE> <INDENT> res = 1 <NEW_LINE> while n > 1: <NEW_LINE> <INDENT> res = res * n <NEW_LINE> n -= 1 <NEW_LINE> <DEDENT> return res | assumes that n is an int > 0
returns n! | 625941eadc8b845886cb5a06 |
def _try_update(self, node_pos, parent_pos, diagonal, record): <NEW_LINE> <INDENT> x, y = node_pos <NEW_LINE> px, py = parent_pos <NEW_LINE> dd = DDIST if diagonal else DIST <NEW_LINE> ng = self.nodes[py][px].g + dd <NEW_LINE> node = self.nodes[y][x] <NEW_LINE> if node.g is None or ng < node.g: <NEW_LINE> <INDENT> node... | Try to update the node's info with the given parent.
If this node can be accessed with the given parent with lower
G cost, this node's parent, G and F values will be updated.
:Return:
updated : bool
whether this node's info has been updated. | 625941ea2c8b7c6e89b35c8c |
def init(self, ): <NEW_LINE> <INDENT> self.gw = None <NEW_LINE> pm = MayaPluginManager.get() <NEW_LINE> genesis = pm.get_plugin("Genesis") <NEW_LINE> self.GenesisWin = self.subclass_genesis(genesis.GenesisWin) | Initialize the plugin. Do nothing.
This function gets called when the plugin is loaded by the plugin manager.
:returns:
:rtype:
:raises: | 625941ea4a966d76dd5514e3 |
def get_chap_secret_for_host(self, host_name): <NEW_LINE> <INDENT> resp = self.ssh.lsiscsiauth() <NEW_LINE> host_found = False <NEW_LINE> for host_data in resp: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if host_data['name'] == host_name: <NEW_LINE> <INDENT> host_found = True <NEW_LINE> if host_data['iscsi_auth_metho... | Generate and store a randomly-generated CHAP secret for the host. | 625941ea0a366e3fb873ecee |
def h_levelsum(self) -> int: <NEW_LINE> <INDENT> level_sum = 0 <NEW_LINE> for g in self.problem.goal: <NEW_LINE> <INDENT> g_node = PgNode_s(g, True) <NEW_LINE> for level in range(len(self.s_levels)): <NEW_LINE> <INDENT> if g_node in self.s_levels[level]: <NEW_LINE> <INDENT> level_sum += level <NEW_LINE> break <NEW_LINE... | The sum of the level costs of the individual goals (admissible if goals independent)
:return: int | 625941ea4e696a04525c991d |
def ndarr2tfrecords(data_set, name): <NEW_LINE> <INDENT> images = data_set[0] <NEW_LINE> labels = data_set[1] <NEW_LINE> filename = os.path.join("../data/tfrecords", name + '.tfrecords') <NEW_LINE> print('Writing', filename) <NEW_LINE> writer = tf.python_io.TFRecordWriter(filename) <NEW_LINE> for idx in xrange(images.s... | Converts a dataset to tfrecords. | 625941ea5510c4643540f8a7 |
def evenements_joystick(self, joystick = None): <NEW_LINE> <INDENT> if joystick: <NEW_LINE> <INDENT> if joystick.type == pygame.JOYBUTTONDOWN: <NEW_LINE> <INDENT> bouton = joystick.button <NEW_LINE> if bouton == 9 or bouton == 1 or bouton == 2: <NEW_LINE> <INDENT> self.changer_scene(SceneInitiale()) | Lire les evenements souris pour déterminer les action ou la scene correspondante. | 625941ea4e4d5625662d48a0 |
def check_exit_button(exit_button, mousex, mousey, statistics, sb): <NEW_LINE> <INDENT> if exit_button.rect.collidepoint(mousex, mousey): <NEW_LINE> <INDENT> check_high_score_bf_exit(statistics, sb) | Выходит из игры при нажатии | 625941ea090684286d50f1bc |
def SetModifiersForPlatform(self): <NEW_LINE> <INDENT> if sys.platform == "darwin": <NEW_LINE> <INDENT> self.modifiers = ['Shift', 'Control', 'Option', 'Command'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.modifiers = ['Control', 'Alt', 'Shift'] <NEW_LINE> <DEDENT> self.modifier_label = {'Control': 'Ctrl'} | Determine list of names of key modifiers for this platform.
The names are used to build Tk bindings -- it doesn't matter if the
keyboard has these keys, it matters if Tk understands them. The
order is also important: key binding equality depends on it, so
config-keys.def must use the same ordering. | 625941ea925a0f43d254a34b |
def test_parser_desc(self): <NEW_LINE> <INDENT> assert self.parser.description == "Formats C:" | Test if parser has the desc set. | 625941eaeab8aa0e5d26e029 |
def _get_logs(self): <NEW_LINE> <INDENT> self.rlog, self.tlog, self.dbal = self.portfolio.get_logs() | Get the logs. | 625941eaa4f1c619b28b04fd |
def __load_cells(self, cells): <NEW_LINE> <INDENT> [self.map.update({cell.position: cell}) for cell in self.cells] | Update map | 625941ea56ac1b37e6264695 |
def initialize_docs(self, docs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.repo = git.Repo(self.datadir) <NEW_LINE> <DEDENT> except git.exc.NoSuchPathError: <NEW_LINE> <INDENT> print("Error: Specified datadir %s does not exist" % self.datadir) <NEW_LINE> exit(1) <NEW_LINE> <DEDENT> except git.exc.InvalidGitRepo... | Read or initialize git repository | 625941ea67a9b606de4a8386 |
def split_data_random(dataset: dict) -> (DataPartition, DataPartition): <NEW_LINE> <INDENT> assert len(dataset) >= 4 <NEW_LINE> keys = list(dataset.keys()) <NEW_LINE> random.shuffle(keys) <NEW_LINE> mid_idx = len(dataset) // 2 <NEW_LINE> entries = (dict(list(dataset.items())[:mid_idx]), dict(list(dataset.items())[mid_i... | Randomly splits data stored in dictionary into two parts
:param dataset: dictionary of routing objects to be split
:return: two new partitions | 625941eaa8370b7717052d6d |
def toggleMenu(self, state): <NEW_LINE> <INDENT> if state: <NEW_LINE> <INDENT> self.statusbar.show() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.statusbar.hide() | 根据状态判断是否展示状态条 | 625941eacc40096d61595e1e |
def is_for_infer(self) -> bool: <NEW_LINE> <INDENT> return False | The samples are dropped according to label. So it is not usable for inference | 625941ea5e10d32532c5f3f5 |
def get_GHA(dt1): <NEW_LINE> <INDENT> times = [dt1.strftime('%Y-%m-%dT%H:%M:%S.%f')] <NEW_LINE> t1 = Time(times, format='isot', scale='utc') <NEW_LINE> d_a = t1.jd[0] - 2451545.0 <NEW_LINE> t = np.double(d_a) / 36525.0 <NEW_LINE> GMST = 280.46061837 + 360.98564736629 * d_a <NEW_LINE> Om = (125.04452 - 1934.136261 * t) ... | Longitude geolocation must be corrected for Greenwich Hour
Angle. This is determined from the datetime associated
with the image to be geolocated.
Parameters
----------
dt1 : datetime.datetime
Input datetime object for image to be geolocated
Returns
-------
GHA : float
Greenwich Hour Angle, use this to correc... | 625941ea9f2886367277ad59 |
def etag_cache(key=None): <NEW_LINE> <INDENT> if_none_match = pylons.request.environ.get('HTTP_IF_NONE_MATCH', None) <NEW_LINE> pylons.response.headers['ETag'] = key <NEW_LINE> if str(key) == if_none_match: <NEW_LINE> <INDENT> log.debug("ETag match, returning 304 HTTP Not Modified Response") <NEW_LINE> raise httpexcept... | Use the HTTP Entity Tag cache for Browser side caching
If a "If-None-Match" header is found, and equivilant to ``key``, then
a ``304`` HTTP message will be returned with the ETag to tell the browser
that it should use its current cache of the page.
Otherwise, the ETag header will be added to the response headers.
Su... | 625941ea15baa723493c4449 |
def sleep_db(self, last_action_time: datetime.datetime, action: str): <NEW_LINE> <INDENT> capacity = self.get_capacity()[action] <NEW_LINE> time_between_actions = 1 / capacity <NEW_LINE> time_elapsed = datetime.datetime.now().timestamp() - last_action_time.timestamp() <NEW_LINE> time_to_sleep = time_between_actions - t... | Sleeps between calls to dynamodb (if it needs to).
Uses the table's capacity to decide how long it needs to sleep.
:param last_action_time: Last time when we did this action (read/write) to this dynamo table
:param action: "read" or "write" | 625941ea377c676e91272676 |
def check_balance(self): <NEW_LINE> <INDENT> return f'balance({self.__ac_no}): {self.__balance}/-' | :return: returns the balance | 625941ea76d4e153a657f002 |
def test_enqueue_adds_to_front_and_back_on_empty(queue_no_nodes): <NEW_LINE> <INDENT> queue_no_nodes.enqueue('a') <NEW_LINE> assert queue_no_nodes.front.value == 'a' <NEW_LINE> assert queue_no_nodes.back.value == 'a' | Back and front of queue should equal only node in queue. | 625941ea92d797404e30465c |
def searchOutputs(self): <NEW_LINE> <INDENT> request = self.request <NEW_LINE> research_database_catalog = getToolByName(self, 'research_database_catalog') <NEW_LINE> if hasattr(self.request, 'research_theme'): <NEW_LINE> <INDENT> research_theme = getattr(self.request, 'research_theme') <NEW_LINE> <DEDENT> else: <NEW_L... | Return the research outputs results as objects
| 625941ea9c8ee82313fbbc47 |
def check_play_button(ai_settings, screen, stats, play_button, ship, aliens, bullets, mouse_x, mouse_y): <NEW_LINE> <INDENT> button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y) <NEW_LINE> if button_clicked and not stats.game_active: <NEW_LINE> <INDENT> start_game(ai_settings, screen, stats, ship, aliens, b... | start a new game when the player clicks play. | 625941ea6aa9bd52df037277 |
def test_ini_file_creates_config_objects_non_strict(IniFileNonStrict): <NEW_LINE> <INDENT> config.Configuration( test_ini_loader_non_strict=namespace.Namespace( test=boolopt.BoolOption(), many=numopt.IntegerOption() ) ) <NEW_LINE> generated_conf = IniFileNonStrict(path="test", strict=False).config <NEW_LINE> assert gen... | Test that parsing INI files loads options. | 625941ea44b2445a33932562 |
def main(): <NEW_LINE> <INDENT> global opts <NEW_LINE> opts = parse_opts() <NEW_LINE> if opts.version: <NEW_LINE> <INDENT> print(__version__) <NEW_LINE> sys.exit(0) <NEW_LINE> <DEDENT> if not opts.image: <NEW_LINE> <INDENT> print(f"Usage: {sys.argv[0]} [OPTIONS] REGISTRY[/REPOSITORY[:TAG|@DIGEST]]") <NEW_LINE> sys.exit... | Main function | 625941ea656771135c3ebd44 |
def uniqueness_3(cuts, obj, firstIndex, **kwargs): <NEW_LINE> <INDENT> idx = [firstIndex + x for x in range(3)] <NEW_LINE> hzz = kwargs.get("hzz", False) <NEW_LINE> if hzz: <NEW_LINE> <INDENT> cutstr = 'zCompatibilityWithUserCands(%d, %d, "dretFSRCand") < zCompatibilityWithUserCands(%d, %d, "dretFSRCand")' <NEW_LINE> <... | Put the best Z candidate first, and order the first two objects by pt. | 625941ea3539df3088e2e81b |
def show_count(): <NEW_LINE> <INDENT> print('count = ', count) | Shows current count. | 625941eae76e3b2f99f3acd3 |
def reply(self, signature=None, args=None): <NEW_LINE> <INDENT> if self.type != dbusx.MESSAGE_TYPE_METHOD_CALL: <NEW_LINE> <INDENT> raise TypeError('Cannot create reply to message of type %s' % self.type) <NEW_LINE> <DEDENT> message = type(self)(dbusx.MESSAGE_TYPE_METHOD_RETURN, reply_serial=self.serial, destination=se... | Create a METHOD_RETURN message.
The message represents a reply to the current message, which must be a
METHOD_CALL message. | 625941eae76e3b2f99f3acd4 |
def squareHeight(self): <NEW_LINE> <INDENT> return self.contentsRect().height() // Board.BoardHeight | returns the height of one square
| 625941ea21bff66bcd684e1e |
def resultsIter(self): <NEW_LINE> <INDENT> resolveColumns = hasattr(self, 'resolveColumns') <NEW_LINE> fields = None <NEW_LINE> hasAggregateSelect = bool(self.query.aggregateSelect) <NEW_LINE> for rows in self.executeSql(MULTI): <NEW_LINE> <INDENT> for row in rows: <NEW_LINE> <INDENT> if hasAggregateSelect: <NEW_LINE> ... | Returns an iterator over the results from executing this query. | 625941eaeab8aa0e5d26e02a |
def test_uke(): <NEW_LINE> <INDENT> print('{}{}Unknown Error {} '.format( colorama.Back.WHITE, colorama.Fore.BLACK, colorama.Style.RESET_ALL), end=' ') | UKE 信息 | 625941eae64d504609d74d10 |
def __changePage(self, change): <NEW_LINE> <INDENT> if change == QuizletWindow.PAGE_FIRST: <NEW_LINE> <INDENT> self.fetchResults(1) <NEW_LINE> <DEDENT> elif change == QuizletWindow.PAGE_PREVIOUS: <NEW_LINE> <INDENT> if self.result_page - 1 >= 1: <NEW_LINE> <INDENT> self.fetchResults(self.result_page-1) <NEW_LINE> <DEDE... | determine what page to fetch | 625941eade87d2750b860268 |
@register.simple_tag <NEW_LINE> def og_prop(name, value): <NEW_LINE> <INDENT> if not isinstance(value, dict) and name in settings.OG_SECURE_URL_ITEMS and value.startswith("https"): <NEW_LINE> <INDENT> data = {name: value, "%s:secure_url" % name: value} <NEW_LINE> <DEDENT> elif not isinstance(value, dict): <NEW_LINE> <I... | Generic OpenGraph property
:param name: property name (without 'og:' namespace)
:param value: property value | 625941ea6fece00bbac2dc15 |
def __repr__(self): <NEW_LINE> <INDENT> return '<Case(module={})>'.format(self.func_name) | 调用类返回的结构 | 625941ea99fddb7c1c9de85e |
def countUnivalSubtrees(self, root): <NEW_LINE> <INDENT> return self.dfs(root)[1] | :type root: TreeNode
:rtype: int | 625941ea0a50d4780f667366 |
def variantFile(path, variant_dirs): <NEW_LINE> <INDENT> path = str(path) <NEW_LINE> for dest, source in variant_dirs.iteritems(): <NEW_LINE> <INDENT> common = os.path.commonprefix([path, source]) <NEW_LINE> if common == source: <NEW_LINE> <INDENT> return os.path.join(dest, path[len(common)+1:]) <NEW_LINE> <DEDENT> <DE... | Returns the path to the corresponding dict entry in variant_dirs | 625941ea498bea3a759b9f7e |
def find_names(self, kind, content_id, timestamp): <NEW_LINE> <INDENT> assert isinstance(timestamp, datetime) <NEW_LINE> try: <NEW_LINE> <INDENT> filenames = os.listdir(self.directory) <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> filenames = [] <NEW_LINE> <DEDENT> paths = (self.directory / fname fo... | -> (exact_match, best_guess, best_guess_freeze_time, names)
where
exact_match = name (kind & content_id matched)
best_guess = name (kind matched, timestamp is closest to input's)
best_guess_freeze_time = timestamp ()
names = sequence of names (kind matched) | 625941ea8c3a873295158891 |
def __newItem(self, parent, data): <NEW_LINE> <INDENT> item = BaseTreeViewItem(parent) <NEW_LINE> item.data = data <NEW_LINE> self.__indextable.append(item) <NEW_LINE> return item | Return a new item to insert in the tree.
Each derived class should override this method to return the proper
TreeViewItem. | 625941eae1aae11d1e74a18c |
def min(self): <NEW_LINE> <INDENT> return self.agg('min') | Finds the min element.
Examples
--------
>>> s = GrizzlySeries([1,2,3,4])
>>> s.min()
1 | 625941eaadb09d7d5db6cc5d |
def __set_vice1_data(self): <NEW_LINE> <INDENT> if self.is_vice1: <NEW_LINE> <INDENT> self.post_data['request_type'] = self.api <NEW_LINE> self.post_data['cert_jurisdiction_hash'] = self.env.get('cert_jurisdiction_hash', None) <NEW_LINE> if 'signatureAlgorithm' in self.post_data: <NEW_LINE> <INDENT> self.post_data.pop(... | sets the request_type and cert_jurisdiction_hash values
removes signatureAlgorithm and specificEndDate | 625941ea38b623060ff0b2bd |
def process_gpspoints_path_v1( csv_path, gps_point_filename, protocol, database_path, track_log_oids=None ): <NEW_LINE> <INDENT> path = os.path.join(csv_path, gps_point_filename + ".csv") <NEW_LINE> gps_points_header = ",".join(protocol["csv"]["gps_points"]["field_names"]) <NEW_LINE> with open(path, "r", encoding="utf-... | Add a CSV file of GPS points to the database. | 625941ea1f5feb6acb0c501a |
def get_file_revision(self, rev_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.get_file_revision_with_http_info(rev_id, **kwargs) | get_file_revision # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_file_revision(rev_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str rev_id: UUID (... | 625941ead99f1b3c44c67a56 |
def deleteOperations(self): <NEW_LINE> <INDENT> log = gLogger.getSubLogger("deleteOperations", child=True) <NEW_LINE> res = self.fts3db.deleteFinalOperations(limit=self.maxDelete, deleteDelay=self.deleteDelay) <NEW_LINE> if not res['OK']: <NEW_LINE> <INDENT> return res <NEW_LINE> <DEDENT> deletedOperations = res['Value... | Delete final operations
:return: S_OK()/S_ERROR() | 625941ea435de62698dfe11d |
def test_patch_service_keep_environments_when_not_in_request(self): <NEW_LINE> <INDENT> service = self.services[0] <NEW_LINE> environments_ids = [env.id for env in service.environments.all()] <NEW_LINE> service_env_ids = [ se.id for se in service.serviceenvironment_set.all() ] <NEW_LINE> url = reverse('service-detail',... | Check if ServiceEnvironment for service are not cleaned after PATCH
without environments fields. | 625941eaec188e330fd5ac65 |
def test(self): <NEW_LINE> <INDENT> cmd = os.path.join(self.srcdir, 'datadir') <NEW_LINE> cmd_result = process.run(cmd) <NEW_LINE> self.log.info(cmd_result) | Execute 'datadir'. | 625941ea656771135c3ebd45 |
def degree(graph: Graph, vertex: int) -> int: <NEW_LINE> <INDENT> _degree = 0 <NEW_LINE> for w in graph.adj(vertex): <NEW_LINE> <INDENT> _degree += 1 <NEW_LINE> <DEDENT> return _degree | 计算V的度数
:param graph:
:param vertex:
:return: | 625941eaa8ecb033257d359c |
def assert_array_compare(self, comparison, x, y, err_msg='', header='', fill_value=True): <NEW_LINE> <INDENT> xf = self.filled(x) <NEW_LINE> yf = self.filled(y) <NEW_LINE> m = self.mask_or(self.getmask(x), self.getmask(y)) <NEW_LINE> x = self.filled(self.masked_array(xf, mask=m), fill_value) <NEW_LINE> y = self.filled(... | Asserts that a comparison relation between two masked arrays is satisfied
elementwise. | 625941ea3346ee7daa2b3240 |
def render_markup(self): <NEW_LINE> <INDENT> if settings.BLOCKS_MARKUP == 'markdown': <NEW_LINE> <INDENT> import markdown <NEW_LINE> self.body_html = markdown.markdown(self.body) <NEW_LINE> self.excerpt_html = markdown.markdown(self.excerpt) <NEW_LINE> <DEDENT> elif settings.BLOCKS_MARKUP == 'textile': <NEW_LINE> <INDE... | Turns any markup into HTML | 625941ea32920d7e50b286a5 |
def totalintensity(filename=None, stream=None): <NEW_LINE> <INDENT> neutrons = read(filename=filename, stream=stream) <NEW_LINE> if neutrons is None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return neutrons[:, -1].sum() | return sum of intensities of all neutrons | 625941ea4527f215b584c922 |
def testAddDepend(self): <NEW_LINE> <INDENT> self.assertEquals(0, len(self.layer.getDepends())) <NEW_LINE> other = blueprint.Layer("test2") <NEW_LINE> self.layer.dependOn(other, blueprint.DependType.All) <NEW_LINE> self.assertEquals(1, len(self.layer.getDepends())) | Testing adding a dependency. | 625941ea56ac1b37e6264696 |
def test_traindata(): <NEW_LINE> <INDENT> traindata_iterator = corpustools.make_tier_tuple_list(tdata) <NEW_LINE> for fname, token, pos in traindata_iterator: <NEW_LINE> <INDENT> assert fname != None <NEW_LINE> assert token != None <NEW_LINE> assert pos != None | this test runs to find non-parsed element-tiers in the exmaralda sources
:return: | 625941ea63d6d428bbe449c1 |
def log_default(self, string: str): <NEW_LINE> <INDENT> self.__log_general('', string) | This function prints a given message in the default warning style
:param string: message that needs to be printed | 625941ea85dfad0860c3b32c |
def p_maybe_eof_or_blankline(p): <NEW_LINE> <INDENT> p[0] = '' | maybe_eof_or_blankline : empty
| EOF
| BLANKLINE
| BLANKLINE EOF | 625941ea97e22403b379d46c |
def write_text_files(self, dictionary: dict) -> None: <NEW_LINE> <INDENT> extralife_io.write_text_files(dictionary, self.text_folder) | Write OBS/XSplit display info to text files.
It uses the helper function extralife_IO.write_text_files to handle the task.
:param dictionary: Dictionary containing values to write to text files . The key will become the filename. The value will be written to the file.
:type dictionary: dict | 625941ea5fdd1c0f98dc0706 |
def test_paths_relative_to_base(self): <NEW_LINE> <INDENT> owner1 = MyPathable(path="owner") <NEW_LINE> owned1 = MyPathable(path_from=owner1, path="owned") <NEW_LINE> self.assertEqual("owned", owned1.path_relative_to(owner1)) <NEW_LINE> owner2 = MyPathable(path="owner") <NEW_LINE> owned2 = MyPathable(path_from=owner2, ... | Ensures that pathable resources have a relative path that is relative to base_path if given | 625941ea07f4c71912b11955 |
def get_cfg_mtime(self): <NEW_LINE> <INDENT> return os.path.getmtime(self.cfg_loc) if self.cfg_loc else None | Return modification time of cfg file | 625941ea3c8af77a43ae3c77 |
def fibonacci(n): <NEW_LINE> <INDENT> cache = {} <NEW_LINE> def fibonacci_helper(n): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return fibonacci_helper(n) | Computes the fibonacci of n. | 625941ea8e05c05ec3eea849 |
def is_winner(self, board_status): <NEW_LINE> <INDENT> result = board_status.check_winner() <NEW_LINE> if result == 'X': <NEW_LINE> <INDENT> self.player_one.wins += 1 <NEW_LINE> print(self.player_one.name + ' WINS!!!!') <NEW_LINE> self.play_again() <NEW_LINE> <DEDENT> elif result == 'O': <NEW_LINE> <INDENT> self.player... | Verify if there is a winner. | 625941ea30bbd722463cc299 |
def subscribe(self): <NEW_LINE> <INDENT> pubsub = self.red.pubsub() <NEW_LINE> pubsub.subscribe(self.rkey) <NEW_LINE> self.subs.append(pubsub) <NEW_LINE> try: <NEW_LINE> <INDENT> for message in pubsub.listen(): <NEW_LINE> <INDENT> if message['type'] == 'message': <NEW_LINE> <INDENT> yield self.encode(message['data']) <... | Yields messages whenever pubsub receives them | 625941eae1aae11d1e74a18d |
@task <NEW_LINE> @roles('web') <NEW_LINE> def restart(hard=False): <NEW_LINE> <INDENT> with hide('running', 'stdout'): <NEW_LINE> <INDENT> result = supervisorctl('status') <NEW_LINE> <DEDENT> if 'no such file' in result: <NEW_LINE> <INDENT> cmd('supervisord -c {supervisord}'.format(**env)) <NEW_LINE> <DEDENT> else: <NE... | Restart the web service. | 625941ea6fb2d068a760f576 |
def __init__(self, title, storyline, image): <NEW_LINE> <INDENT> self.title = title <NEW_LINE> self.storyline = storyline <NEW_LINE> self.poster_image_url = image | Inits Video with title, storyline and image | 625941ea96565a6dacc8fb9a |
def AssignedUsers(role): <NEW_LINE> <INDENT> return get_user_model().objects.filter(rbacuserassignment__roles=role) | Returns the users which are assigned to the specified role.
@type role: RbacRole
@rtype: QuerySet | 625941eacc0a2c11143dd363 |
def remove_peer_node(self, node): <NEW_LINE> <INDENT> self.__peer_nodes.discard(node) <NEW_LINE> self.save_data() | Removed node from the peer node network
Arguments :
:node: the node url that should be removed | 625941ea4428ac0f6e5bacc7 |
def IsolatedYcmd( custom_options = {} ): <NEW_LINE> <INDENT> def Decorator( test ): <NEW_LINE> <INDENT> @functools.wraps( test ) <NEW_LINE> def Wrapper( *args, **kwargs ): <NEW_LINE> <INDENT> with IsolatedApp( custom_options ) as app: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> test( app, *args, **kwargs ) <NEW_LINE> ... | Defines a decorator to be attached to tests of this package. This decorator
passes a unique ycmd application as a parameter. It should be used on tests
that change the server state in a irreversible way (ex: a semantic subserver
is stopped or restarted) or expect a clean state (ex: no semantic subserver
started, no .yc... | 625941eaa4f1c619b28b04fe |
@scheduler.command() <NEW_LINE> @click.argument('agent_ids', nargs=-1) <NEW_LINE> def include_agents(agent_ids): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with Session() as session: <NEW_LINE> <INDENT> session.Manager.scheduler_op('include-agents', agent_ids) <NEW_LINE> <DEDENT> print_done('The given agents now acce... | Include agents in scheduling, meaning that the given agents
will be considered to be ready for creating new session containers. | 625941ea16aa5153ce362949 |
def merge_sort2(nums, p, r): <NEW_LINE> <INDENT> if p == r: <NEW_LINE> <INDENT> return nums[p] <NEW_LINE> <DEDENT> q = (p + r) // 2 <NEW_LINE> l = merge_sort2(nums, p, q) <NEW_LINE> r = merge_sort2(nums, q, r) <NEW_LINE> merge2(nums, l, r) <NEW_LINE> return nums | >>> nums = random.sample(range(10), 10)
>>> ret = sorted(nums)
>>> merge_sort2(nums, 0, len(nums))
>>> operator.eq(ret, nums)
True | 625941eaa219f33f34628e33 |
def main(): <NEW_LINE> <INDENT> cf_client = boto3.client('cloudformation') <NEW_LINE> s3_client = boto3.resource('s3').meta.client <NEW_LINE> __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) <NEW_LINE> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument('-y', '--yaml'... | Accepts arguments
Reads data
Creates template
Uploads template to S3
Creates and delets stack | 625941eaa05bb46b383eccee |
def str_equals(a, b): <NEW_LINE> <INDENT> al = len(a) <NEW_LINE> bl = len(b) <NEW_LINE> match = True <NEW_LINE> for i in xrange(0, min(al, bl)): <NEW_LINE> <INDENT> match &= a[i] == b[i] <NEW_LINE> <DEDENT> return match | Constant time string equals method - no time leakage
:param a:
:param b:
:return: | 625941ea50812a4eaa59c7ed |
def get_attr_u32(self, a): <NEW_LINE> <INDENT> return _conntrack.conntrack_get_attr_u32(self._ct, a) | get attribute of unsigned 32-bits long
Returns the value of the requested attribute, if the attribute is not
set, OSError is raised. In order to check if the attribute is set or not,
use attr_is_set.
@type a: number (ATTR_)
@param a: attribute type
@rtype: number
@return: the value of the requested attribute | 625941ea4f88993c3716c533 |
def __init__(self, dataset, features_field_name, labels_field_name, batch_size=None, batch_tokens_size=None, maximum_features_length=None, maximum_labels_length=None, shuffle_every_epoch=None, bucketing=True): <NEW_LINE> <INDENT> super(ParallelTextInputter, self).__init__( dataset, batch_size) <NEW_LINE> self._batch_to... | Initializes the parameters for this inputter.
Args:
dataset: A `Dataset` object.
features_field_name: The attribute name of dataset that has
access to a features file.
labels_field_name: The attribute name of dataset that has
access to a labels file.
batch_size: An integer value indicating ... | 625941eab830903b967e9dd7 |
def _make_table(self, p_list, table_size=20000000): <NEW_LINE> <INDENT> phrase_count = len(p_list) <NEW_LINE> phrase_lens = np.asarray([p.size for p in p_list]).astype(np.float64) <NEW_LINE> len_sum = np.sum(phrase_lens) <NEW_LINE> table = np.zeros((table_size,), dtype=np.uint32) <NEW_LINE> widx = 0 <NEW_LINE> d1 = phr... | Create a table for quickly drawing phrase indices in proportion to
the length of each phrase. | 625941ea8da39b475bd6544b |
def list_stages(self): <NEW_LINE> <INDENT> return self.client._perform_json("GET", "/api-deployer/stages") | Lists infrastructure stages of the API Deployer
:rtype: list of dict. Each dict contains a field "id" for the stage identifier and "desc" for its description.
:rtype: list | 625941eadc8b845886cb5a08 |
def double_sin(x, α=4, β=13, μ=0, σ=0.03, noisy=True): <NEW_LINE> <INDENT> w = 0 <NEW_LINE> if noisy: <NEW_LINE> <INDENT> w = Normal(μ, σ).sample((x.shape[0],)) <NEW_LINE> <DEDENT> return x + torch.sin(α * (x + w)) + torch.sin(β * (x + w)) + w | Toy function in: https://arxiv.org/pdf/1602.04621.pdf, Fig. 10
| 625941ea63f4b57ef00015dc |
def test_vectors(self): <NEW_LINE> <INDENT> def md5test(key, data, digest): <NEW_LINE> <INDENT> h = hmac.HMAC(key, data) <NEW_LINE> self.failUnless(h.hexdigest().upper() == digest.upper()) <NEW_LINE> <DEDENT> md5test(chr(0x0b) * 16, "Hi There", "9294727A3638BB1C13F48EF8158BFC9D") <NEW_LINE> md5test("Jefe", "what do ya ... | Test the HMAC module against test vectors from the RFC. | 625941ea4a966d76dd5514e5 |
def count_roots(self, verbose=False, max_iter=100, tol=0.1, max_step=0.1): <NEW_LINE> <INDENT> self.success = False <NEW_LINE> for i in range(0, max_iter): <NEW_LINE> <INDENT> n_add = self.refine_select(tol=tol, max_step=max_step) <NEW_LINE> if verbose == True: <NEW_LINE> <INDENT> print(i, self.sum_angles(), n_add) <NE... | Count number of roots in domain
Args:
verbose (bool, optional): Flag whether to print progress. Defaults to False
max_iter (optional): Maximum number of refinement iterations. Defaults to 100. RuntimeError if not converged before.
tol (optional): Tolerance in jump in argument. Defaults to 0.1.
max_step... | 625941ea2c8b7c6e89b35c8e |
def compare_error(ref, syn): <NEW_LINE> <INDENT> corr_min = 1. <NEW_LINE> err_max = 0. <NEW_LINE> corr_mat = np.corrcoef(ref, syn) <NEW_LINE> corr = np.min(corr_mat) <NEW_LINE> corr_min = min(corr, corr_min) <NEW_LINE> norm = np.linalg.norm <NEW_LINE> sqrt = np.sqrt <NEW_LINE> err = norm(ref-syn)/sqrt(norm(ref)*norm(sy... | calculate difference between two seismogram/adjoint source | 625941ea8a43f66fc4b54531 |
def calculate_rate_skipping_prediction(self, user_id, h, k): <NEW_LINE> <INDENT> if not hasattr(self, 'user_rating_df'): <NEW_LINE> <INDENT> self.prediction_setup() <NEW_LINE> <DEDENT> user_unranked_items = self.get_unrank_itmes(user_id) <NEW_LINE> h_user_items_max_rank = list(self.get_user_max_rank_items(h, user_id)) ... | Question 6 - the function calculate the rate for each item of user_id
that does not appear in the base file using the method described in the article
params :
h - h number of items which the user rated highest
k - k number of items that have the highest similarity with unrated item | 625941ea7047854f462a18d5 |
def deadlock(self): <NEW_LINE> <INDENT> if len(self.ghost_droppers) == len(self.ships): <NEW_LINE> <INDENT> for ship in self.ships: <NEW_LINE> <INDENT> if ship.position == self.ghost.position: <NEW_LINE> <INDENT> if self.me.halite_amount < self.dropoff_cost(ship): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DE... | Check for deadlock situation.
Note:
Can occur when every ship is returning to the ghost dropoff, but
the ghost dropoff cannot be constructed. Probably lost the game
already, so it does not really matter what we do. | 625941ea21a7993f00bc81ca |
def rmse (estimation, target): <NEW_LINE> <INDENT> return numpy.sqrt(mse(estimation, target)) | Calculates the root mean square error between a set of outputs and target
values using the following formula:
.. math::
RMSE(\hat{\Theta}) = \sqrt(E[(\hat{\Theta} - \Theta)^2])
Estimation (:math:`\hat{\Theta}`) and target (:math:`\Theta`) are supposed to
have 2 dimensions. Different examples are organized as rows ... | 625941ea099cdd3c635f112a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.