code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def main(self): <NEW_LINE> <INDENT> if self.options.timerange: <NEW_LINE> <INDENT> timefilter = TimeFilter.parse_range(self.options.timerange) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> timefilter = TimeFilter(self.options.time0, self.options.time1) <NEW_LINE> <DEDENT> trafficexpr = TrafficFilter(self.options.traffi... | Setup query and run report with default column set
| 625941f6f548e778e58cdbd0 |
def utf82unicode(value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return value.decode("utf8") <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> if not _Log: <NEW_LINE> <INDENT> _late_import() <NEW_LINE> <DEDENT> if not isinstance(value, binary_type): <NEW_LINE> <INDENT> _Log.error("Can not convert {{ty... | WITH EXPLANATION FOR FAILURE | 625941f6097d151d1a2234a5 |
def get_feature(ftr_id: int): <NEW_LINE> <INDENT> return json.loads(open(BASEPATH_FEATURES + '%s.json' % ftr_id).read()) | Each feature is stored in a file with the name of the file as feature_number.json: 1.json, 2.json. This
function loads the file from the file system using the base path from the configuration file.
:param ftr_id: identifier of the feature being a sequential number
:return: the contents of the file representing the feat... | 625941f6796e427e537b0c1b |
def test_distance_to_point(): <NEW_LINE> <INDENT> pt = Point3D(2, 2, 2) <NEW_LINE> vec = Vector3D(0, 2, 0) <NEW_LINE> ray = Ray3D(pt, vec) <NEW_LINE> near_pt = Point3D(3, 3, 2) <NEW_LINE> assert ray.distance_to_point(near_pt) == 1 <NEW_LINE> near_pt = Point3D(2, 0, 2) <NEW_LINE> assert ray.distance_to_point(near_pt) ==... | Test the Ray3D distance_to_point method. | 625941f607f4c71912b11ad5 |
def candies(): <NEW_LINE> <INDENT> return _inventory.candy | :return:
:rtype: Candies | 625941f6090684286d50f341 |
def _default_date(self, end=False): <NEW_LINE> <INDENT> today = datetime.today() <NEW_LINE> if end: <NEW_LINE> <INDENT> result = today.strftime(u'%Y-07-31') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = (today - relativedelta(years=1)).strftime(u'%Y-08-01') <NEW_LINE> <DEDENT> return result | Returns the default date for each of the season bounds
:param end (boolean): True if end date is required False otherwise
:return (unicode): date as unicode string | 625941f630bbd722463cc41a |
def write_airflow_string(tasks, filename): <NEW_LINE> <INDENT> with open(filename, "w") as f: <NEW_LINE> <INDENT> f.write(create_airflow_string(tasks)) | Writes the Airflow DAG file for the given tasks. I/O wrapper for `create_airflow_string`.
Parameters
----------
tasks: list of {Transform, Depositor} objects, required
The tasks constituting the task graph to be written as a DAG.
filename: str, required
The filename the DAG will be written to. | 625941f667a9b606de4a8505 |
def set_conclusion(self, text): <NEW_LINE> <INDENT> if isinstance(text, str): <NEW_LINE> <INDENT> text = Statement(text) <NEW_LINE> <DEDENT> if not isinstance(text, Statement): <NEW_LINE> <INDENT> raise UnrecognizedConclusionFormat("conclusions must be " "Statements") <NEW_LINE> <DEDENT> self.conclusion_statement = tex... | set argument conclusion from string or Statement | 625941f64d74a7450ccd4815 |
def save(self, file=None, filename=None, adjoin=True): <NEW_LINE> <INDENT> if file is None and filename is None: <NEW_LINE> <INDENT> raise TypeError('expected an argument') <NEW_LINE> <DEDENT> elif file is not None and filename is not None: <NEW_LINE> <INDENT> raise TypeError('expected only one argument; but two passed... | Saves the image into the ``file`` or ``filename``. It takes
only one argument at a time.
:param file: a file object to write to
:type file: file object
:param filename: a filename string to write to
:type filename: :class:`basestring`
:param adjoin: write all images to a single multi-image file. Only
av... | 625941f65fdd1c0f98dc0885 |
def updateTxnCount(self, count): <NEW_LINE> <INDENT> self._db.put(b'lastTxnDownloaded', int.to_bytes( count, 10, byteorder='big')) | Updates the transaction count (stored as a key-value pair in db) | 625941f6f9cc0f698b140c45 |
def predict(self, MSA): <NEW_LINE> <INDENT> fileh = tempfile.NamedTemporaryFile() <NEW_LINE> AlignIO.write(MSA,fileh,'clustal') <NEW_LINE> fileh.flush() <NEW_LINE> alifold = RNAalifoldCMD(filename=fileh.name,noPostScript=True) <NEW_LINE> stdout, stderr=alifold() <NEW_LINE> lines=stdout.split('\n') <NEW_LINE> import sys... | Predict the consensus structure of a MSA.
Arguments:
- `MSA`: A MultipleSequenceAlignment object | 625941f64e696a04525c9a9e |
def calculateV(self,phiS): <NEW_LINE> <INDENT> d1, d2 = phiS.shape <NEW_LINE> v = np.zeros((d1*self.M, d2)) <NEW_LINE> n = 0 <NEW_LINE> for i in range(0, d1): <NEW_LINE> <INDENT> v[n] = 0 <NEW_LINE> for x in range(0,d1): <NEW_LINE> <INDENT> for y in range(x+1, d1): <NEW_LINE> <INDENT> if i == x or i==y: <NEW_LINE> <IND... | Calculate derivatives of P vector in respect
to each variable.
Returns V vector of shape (d1*M , d2).
d1 - number of oscillators
d2 - number of data points
M - number of parameters | 625941f615baa723493c45ca |
def get_longest_row_w(self): <NEW_LINE> <INDENT> table_cells_pos_x = [cell_pos[0] for cell_pos in self.table_cells_dict_keys] <NEW_LINE> table_cells_pos_w = [cell_pos[2] for cell_pos in self.table_cells_dict_keys] <NEW_LINE> columns = set(table_cells_pos_x) <NEW_LINE> col_len = len(columns) <NEW_LINE> test_cell_items =... | 根据表格中最长的行对应的x索引,获取w索引
:param table: cells list
:return: 表格各列对应的x坐标[w1,w2,w3] | 625941f6b545ff76a8914465 |
def get_playlist_id_by_title(youtube, title, create_missing_playlist=False): <NEW_LINE> <INDENT> playlists = get_playlists(youtube) <NEW_LINE> named_playlists = filter(lambda playlist: playlist['title'] == title, playlists) <NEW_LINE> if (not named_playlists and create_missing_playlist): <NEW_LINE> <INDENT> request_res... | Retrieve a list of playlists (ids and titles) that match the given title. | 625941f66fece00bbac2dd96 |
def getOperator(): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> operator = input("\nChoose one operator: {} ".format(validOperators)) <NEW_LINE> if operator in validOperators: <NEW_LINE> <INDENT> return operator <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("\nInvalid operator!") | returns the operator chosen by the user | 625941f67cff6e4e81117fd5 |
def plot_single_graph(scales, real_times, m_title, m_xlabel="n", m_ylabel="time(s)", line_color='dodgerblue'): <NEW_LINE> <INDENT> plt.plot(scales, real_times, color=line_color) <NEW_LINE> plt.title(m_title) <NEW_LINE> plt.xlabel(m_xlabel) <NEW_LINE> plt.ylabel(m_ylabel) <NEW_LINE> plt.show() | 绘制时间比较图像 | 625941f69c8ee82313fbbdc7 |
def status(self, cache, jobs=None, remote=None, show_checksums=False): <NEW_LINE> <INDENT> remote = self.get_remote(remote, "status") <NEW_LINE> return self.repo.cache.local.status( cache, jobs=jobs, remote=remote, show_checksums=show_checksums ) | Check status of data items in a cloud-agnostic way.
Args:
cache (NamedCache): named checksums to check status for.
jobs (int): number of jobs that can be running simultaneously.
remote (dvc.remote.base.RemoteBASE): optional remote to compare
cache to. By default remote from core.remote config optio... | 625941f6956e5f7376d714bb |
def get_valids(self): <NEW_LINE> <INDENT> valids = {} <NEW_LINE> valids['feats'] = [] <NEW_LINE> valids['descriptions'] = [] <NEW_LINE> for valid in self.split['val']: <NEW_LINE> <INDENT> valids['feats'].append(self.images[valid['imgid']]) <NEW_LINE> valids['descriptions'].append(valid) <NEW_LINE> <DEDENT> return valid... | get validation examples from the whole dataset
:return: | 625941f6377c676e912727f6 |
@pytest.mark.django_db <NEW_LINE> def test_associate_user_in_company(logged_client, user): <NEW_LINE> <INDENT> company = CompanyFactory.create() <NEW_LINE> ASSOCIATE_URL = reverse_lazy('companies:associate', kwargs={'company': company.id}) <NEW_LINE> response = logged_client.post(ASSOCIATE_URL, data={'username': user.u... | Should redirect and send a success message after associating the user | 625941f631939e2706e4d4b0 |
def HasSubtree(root1, root2): <NEW_LINE> <INDENT> result = False <NEW_LINE> if root1 != None and root2 != None: <NEW_LINE> <INDENT> if Equal(root1.val, root2.val): <NEW_LINE> <INDENT> result = DoesTree1HaveTree2(root1, root2) <NEW_LINE> <DEDENT> if not result: <NEW_LINE> <INDENT> result = HasSubtree(root1.left, root2) ... | 查找根值相同的节点
:param root1:
:param root2:
:return: | 625941f6be7bc26dc91cdc44 |
def check_bullet_alien_collisions(setting, screen, ship,aliens,bullets): <NEW_LINE> <INDENT> collisions = pygame.sprite.groupcollide(bullets, aliens, True, True) <NEW_LINE> if len(aliens) == 0: <NEW_LINE> <INDENT> bullets.empty() <NEW_LINE> setting.increase_speed() <NEW_LINE> create_fleet(setting, screen, ship, aliens) | 响应子弹和外星人的碰撞 | 625941f644b2445a339326e1 |
def task_view_link(self, ): <NEW_LINE> <INDENT> if not self.cur_task: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> e = self.cur_task.element <NEW_LINE> if isinstance(e, djadapter.models.Asset): <NEW_LINE> <INDENT> self.view_asset(e) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.view_shot(e) | View the link of the current task
:returns: None
:rtype: None
:raises: None | 625941f68a349b6b435e87c2 |
def prep_high_score(self): <NEW_LINE> <INDENT> high_score = self.stats.high_score <NEW_LINE> high_score_str = f"Record:{high_score}" <NEW_LINE> self.high_score_img = self.font.render( high_score_str, True, self.text_color, self.settings.bg_color) <NEW_LINE> self.high_score_rect = self.high_score_img.get_rect() <NEW_LIN... | Преобразует рекордный счёт в изображение | 625941f6a8370b7717052eed |
def make_image_blur(original_img): <NEW_LINE> <INDENT> base_filename, file_extension = os.path.splitext(original_img) <NEW_LINE> print("Dirname: '{}'\n" "filename: '{}'\n".format(os.path.dirname(original_img), os.path.basename(original_img))) <NEW_LINE> blur_filename = f"{new_imgs_path}{os.path.basename(original_img)}_... | Creates a blurred of the image
Args:
original_img (str): complete file path and name of original image
Returns:
The name (str) of the new (blurred) version
The final image will be named "<original_filename>_thumbnail.jpg | 625941f656ac1b37e6264812 |
def draw(self): <NEW_LINE> <INDENT> glRotatef(self.__pitch, 1.0, 0.0, 0.0) <NEW_LINE> glRotatef(self.__yaw, 0.0, 1.0, 0.0) <NEW_LINE> glTranslatef(*self.__position) | Apply transform | 625941f6009cb60464c639fc |
def swapPairs(self, head): <NEW_LINE> <INDENT> if not head or not head.next: <NEW_LINE> <INDENT> return head <NEW_LINE> <DEDENT> nextNode = head.next <NEW_LINE> head.next = self.swapPairs(nextNode.next) <NEW_LINE> nextNode.next = head <NEW_LINE> return nextNode | 方法一使用递归来解决该题,主要就是递归的三部曲:
1. 找终止条件:本题终止条件很明显,当递归到链表为空或者链表只剩一个元素的时候,没得交换了,自然就终止了。
2. 找返回值:返回给上一层递归的值应该是已经交换完成后的子链表。
3. 单次的过程:因为递归是重复做一样的事情,所以从宏观上考虑,只用考虑某一步是怎么完成的。我们假设待交换的俩节点分别为head和next,next的应该接受上一级返回的子链表(参考第2步)。就相当于是一个含三个节点的链表交换前两个节点,就很简单了,想不明白的画画图就ok。 | 625941f621bff66bcd684f9d |
def __export(self): <NEW_LINE> <INDENT> if self.__groups_info: <NEW_LINE> <INDENT> user_data = { 'Имя пользователя': self.__first_name, 'Фамилия пользователя': self.__last_name, 'ID ВКонтакте': self.__id, 'Список уникальных групп': self.__groups_info, } <NEW_LINE> with open(self.__file, 'w', encoding='utf-8') as f: <NE... | Сохранение данных о пользователе и его уникальных группах в файл | 625941f6e5267d203edce2e5 |
def register_plugin(self): <NEW_LINE> <INDENT> self.pylint.treewidget.sig_edit_goto.connect(self.main.editor.load) <NEW_LINE> self.pylint.redirect_stdio.connect( self.main.redirect_internalshell_stdio) <NEW_LINE> self.main.add_dockwidget(self) <NEW_LINE> pylint_act = create_action(self, _("Run static code analysis"), t... | Register plugin in Spyder's main window | 625941f671ff763f4b549ce8 |
def Insert(self, itemText, previous=None, parent=None, clientData=None): <NEW_LINE> <INDENT> data = wx.TreeItemData(clientData) <NEW_LINE> if parent is None: <NEW_LINE> <INDENT> parent = self._tree.GetRootItem() <NEW_LINE> <DEDENT> if previous is None: <NEW_LINE> <INDENT> item = self._tree.InsertItemBefore(parent, 0, i... | Insert(self, String itemText, TreeItemId previous=None, TreeItemId
parent=None, PyObject clientData=None) -> TreeItemId
Insert an item into the control before the ``previous`` item
and/or as child of the ``parent`` item. The itemText is associated
with clientData when not None. | 625941f63eb6a72ae02ecb40 |
def set_AccessToken(self, value): <NEW_LINE> <INDENT> super(RetrieveActivityInputSet, self)._set_input('AccessToken', value) | Set the value of the AccessToken input for this Choreo. ((required, string) The Access Token retrieved after the final step in the OAuth2 process.) | 625941f60fa83653e4657607 |
def modify(self, start, end): <NEW_LINE> <INDENT> if self.contains(end): <NEW_LINE> <INDENT> self.render_from(start) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.update() | Update focus window after insert lines to start..end
OR after delete lines above start.
For delete, pass same iline for start and end. | 625941f6d18da76e23532b2f |
def gender(): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> z = input('Are you a boy(1) or a girl(2)?') <NEW_LINE> if z[0] == '1' or z[0] == 'b' or z[0] == 'B': <NEW_LINE> <INDENT> a = 'boy' <NEW_LINE> b = 'he' <NEW_LINE> c = 1 <NEW_LINE> break <NEW_LINE> <DEDENT> if z[0] == '2' or z[0] == 'g' or z[0] == 'G': <NE... | (NoneType) -> list of str and int | 625941f621a7993f00bc834d |
def uniquePathsIII(self, grid): <NEW_LINE> <INDENT> self.grid = grid <NEW_LINE> self.nx = len(grid) <NEW_LINE> self.ny = len(grid[0]) <NEW_LINE> self.count = 0 <NEW_LINE> self.p = 0 <NEW_LINE> root = Node([], self.findRoot()) <NEW_LINE> self.search(root) <NEW_LINE> print(self.p) <NEW_LINE> print(self.count) <NEW_LINE> ... | :type grid: List[List[int]]
:rtype: int | 625941f6cdde0d52a9e53689 |
@util.positional(2) <NEW_LINE> def api(name, version, description=None, hostname=None, audiences=None, scopes=None, allowed_client_ids=None, canonical_name=None, auth=None, owner_domain=None, owner_name=None, package_path=None, frontend_limits=None, title=None, documentation=None, auth_level=None, issuers=None, api_key... | Decorate a ProtoRPC Service class for use by the framework above.
This decorator can be used to specify an API name, version, description, and
hostname for your API.
Sample usage (python 2.7):
@endpoints.api(name='guestbook', version='v0.2',
description='Guestbook API')
class PostService(remote.S... | 625941f6aad79263cf39109b |
def __getitem__(self, key): <NEW_LINE> <INDENT> record = self.client.get(key) <NEW_LINE> if record: <NEW_LINE> <INDENT> if self.compress: <NEW_LINE> <INDENT> record = zlib.decompress(record) <NEW_LINE> <DEDENT> return record.decode(self.encoding) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError(key + ' does... | Load data from Redis for given URL | 625941f6bde94217f368343b |
def heuristic(capacity, items): <NEW_LINE> <INDENT> items.sort(key=lambda el: el.desire, reverse=False) <NEW_LINE> solution = [] <NEW_LINE> _size = 0 <NEW_LINE> while _size < capacity and items: <NEW_LINE> <INDENT> taken = items.pop() <NEW_LINE> _size += taken.size <NEW_LINE> solution.append(taken) <NEW_LINE> <DEDENT> ... | This function performs heuristic, greedy solution to the knapsack problem
based on the value-to-size ratio. | 625941f6711fe17d825429ad |
def get_nodes(self, stage=None): <NEW_LINE> <INDENT> if stage is None: <NEW_LINE> <INDENT> return [name for name in self._all_nodes] <NEW_LINE> <DEDENT> return [name for name, n_stage in self._all_nodes.items() if n_stage == stage] | Get a list of nodes that have the specified status | 625941f68da39b475bd655cd |
def creat_data(n): <NEW_LINE> <INDENT> np.random.seed(0) <NEW_LINE> X = 5 * np.random.rand(n, 1) <NEW_LINE> y = np.sin(X).ravel() <NEW_LINE> noise_num = (int)(n / 5) <NEW_LINE> y[::5] += 3 * (0.5 - np.random.rand(noise_num)) <NEW_LINE> return model_selection.train_test_split(X, y, test_size=0.25, random_state=1) | 产生用于回归问题的数据集
:param n: 数据集容量
:return: 返回一个元组,元素依次为:训练样本集、测试样本集、训练样本集对应的值、测试样本集对应的值 | 625941f6baa26c4b54cb1768 |
def sample(self, get_n=0): <NEW_LINE> <INDENT> if get_n: <NEW_LINE> <INDENT> idx = np.arange(len(self.memory)-get_n, len(self.memory)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.priority: <NEW_LINE> <INDENT> p = np.array(self.error_buffer) <NEW_LINE> p = p/p.sum() <NEW_LINE> idx = np.random.choice(len(p), se... | Randomly sample a batch of experiences from memory. | 625941f6a79ad161976cc796 |
def getBarycenter(self, atomlist): <NEW_LINE> <INDENT> coords = self.getcoords(atomlist) <NEW_LINE> nat = len(atomlist) <NEW_LINE> barycenter = np.asarray([0,0,0]) <NEW_LINE> for at in coords: <NEW_LINE> <INDENT> barycenter = barycenter + at/nat <NEW_LINE> <DEDENT> return barycenter | Return the mass free barycenter of the atoms in the list | 625941f696565a6dacc8fd19 |
def roll(self): <NEW_LINE> <INDENT> scale = (16384, 8192, 4096, 2048) <NEW_LINE> raw = self.get_accel_raw() <NEW_LINE> y = unp('>h', raw[2:4])[0]/scale[self._ar] <NEW_LINE> z = unp('>h', raw[4:6])[0]/scale[self._ar] <NEW_LINE> roll = degress(pi+atan2(-y,-z)) <NEW_LINE> if (roll>=180) and (roll<=360): <NEW_LINE> <INDENT... | Returns roll angle in degrees based on y and z accelerations. | 625941f626068e7796caf33a |
def compute_xi(self,data): <NEW_LINE> <INDENT> log_alpha = self.compute_log_alpha(data) <NEW_LINE> log_gamma = np.log(self.q_e_step) <NEW_LINE> T = data.shape[0] <NEW_LINE> log_xi = np.zeros((T-1,4,4)) <NEW_LINE> for t in range(T-1): <NEW_LINE> <INDENT> for i in range(4): <NEW_LINE> <INDENT> for j in range(4) : <NEW_LI... | Compute p(q_t,q_{t+1}|y)
parameters: np.array data: observations | 625941f6a8ecb033257d371b |
@fail_on <NEW_LINE> def block_dirty_bitmap_remove(vm, device, name): <NEW_LINE> <INDENT> qemu_monitor.get_monitor_function( vm, "block-dirty-bitmap-remove")(device, name) <NEW_LINE> time.sleep(0.3) <NEW_LINE> msg = "Bitmap '%s' in device '%s' still exists!" % (name, device) <NEW_LINE> assert get_bitmap_by_name(vm, devi... | Remove bitmaps on the device one by one | 625941f656b00c62f0f14cae |
def LaunchPlugin(self, plugin_name, *pos, **kwargs): <NEW_LINE> <INDENT> subprocess.check_call( [sys.executable, plugin_name] + pos + ["--%s='%s'" % (k, v) for k, v in kwargs.items()]) | Runs a plugin in another process. | 625941f623849d37ff7b36da |
def clean(self): <NEW_LINE> <INDENT> super(BaseResource, self).clean() <NEW_LINE> try: <NEW_LINE> <INDENT> instance = self.instance <NEW_LINE> <DEDENT> except KeyError as e: <NEW_LINE> <INDENT> raise ValidationError(str(e)) | Make sure self.name is a valid resource | 625941f6596a89723608a108 |
def __init__(self, input_shape, output_shape): <NEW_LINE> <INDENT> self.input_shape = input_shape <NEW_LINE> self.output_shape = output_shape | In case of Q learning, the input_shape is size of state space and the
output_shape denotes the size of the action space. | 625941f68c0ade5d55d3f011 |
def is_Enabled(self): <NEW_LINE> <INDENT> return self.isEnabled() | get Enable state of webElement
:param: None
:return: Boolean | 625941f62eb69b55b151cf0a |
def MultiRandom(N,PA): <NEW_LINE> <INDENT> Points = len(PA) <NEW_LINE> MR = np.zeros((N,Points)) <NEW_LINE> for i in range(0,Points): <NEW_LINE> <INDENT> A = Random(N,PA[i]) <NEW_LINE> MR[:,i] = Degree(A) <NEW_LINE> <DEDENT> return MR | MultiRandom creates multiple random graph networks and calculates the
degree of each vertex in each network. Note the length of the PA array
determines the number of networks created.
Input:
N = number of vertices per network
PA = 1D array of probability of connection values
Output:
MR = 2D array of degree... | 625941f63346ee7daa2b33c3 |
def print_all_names(): <NEW_LINE> <INDENT> print("List of Donors:") <NEW_LINE> print("---------------") <NEW_LINE> for n in donor_data.get_all_names(): <NEW_LINE> <INDENT> print(n) <NEW_LINE> <DEDENT> print("_______________") | Print all donor names | 625941f676e4537e8c351cc9 |
def climbStairs(self, n): <NEW_LINE> <INDENT> if (n == 0 or n == 1): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> aks1 = 1 <NEW_LINE> aks2 = 1 <NEW_LINE> ak = 2 <NEW_LINE> k = 2 <NEW_LINE> while k != n: <NEW_LINE> <INDENT> aks2 = aks1 <NEW_LINE> aks1 = ak <NEW_LINE> k += 1 <NEW_LINE> ak = aks1 + aks2 <NEW_LINE> <DE... | :type n: int
:rtype: int | 625941f69f2886367277aed8 |
def get_previous_imports(): <NEW_LINE> <INDENT> return reporter.get_previous_imports() | Return a new sorted name list of previously imported modules | 625941f6f548e778e58cdbd1 |
def centered(self): <NEW_LINE> <INDENT> r_all = self.r_all <NEW_LINE> v_all = self.v_all <NEW_LINE> r_cent = np.empty_like(r_all) <NEW_LINE> """ Centering """ <NEW_LINE> for b in range(10): <NEW_LINE> <INDENT> r_cent[:,:,b,:] = r_all[:,:,b,:] - r_all[:,:,0,:] <NEW_LINE> <DEDENT> r_aux = vec_ub(r_cent[:,:,:,0], self.Lx)... | Returns: r_cent, v_all
r_cent is the particle positions, after being centered around the root of
their respective chains and reversed the boundary conditions in x dir.
v_all is just piped through | 625941f6dd821e528d63b7f4 |
def test_insert(self): <NEW_LINE> <INDENT> ret = {'name': 'salt', 'changes': {}, 'result': None, 'comment': ''} <NEW_LINE> self.assertDictEqual(iptables.insert('salt', rules=[]), ret) <NEW_LINE> mock = MagicMock(return_value=[]) <NEW_LINE> with patch.object(iptables, '_STATE_INTERNAL_KEYWORDS', mock): <NEW_LINE> <INDEN... | Test to insert a rule into a chain | 625941f657b8e32f52483af0 |
def pc_work_time(self): <NEW_LINE> <INDENT> return _blocks_swig4.packed_to_unpacked_ss_sptr_pc_work_time(self) | pc_work_time(packed_to_unpacked_ss_sptr self) -> float | 625941f6cad5886f8bd27629 |
def test_build_issue_96_fail_read_malformed_index_duplicate_key(self): <NEW_LINE> <INDENT> tmp_dir = mkdtemp() <NEW_LINE> try: <NEW_LINE> <INDENT> fasta_path = os.path.join(tmp_dir, 'issue_96.fasta') <NEW_LINE> faidx_path = os.path.join(tmp_dir, 'issue_96.fasta.fai') <NEW_LINE> with open(fasta_path, 'w') as fasta_out: ... | Ensure that the fasta file is closed if construction of the 'Faidx' file
fails when attempting to read a pre-existing index. The index is malformed because
it contains mulitple occurrences of the same index.
See mdshw5/pyfaidx#96 | 625941f626238365f5f0f4c7 |
def clear_auxmatrix(self): <NEW_LINE> <INDENT> self._cache.clear(tags='m', dealloc=True) | Clear auxiliary matrices | 625941f6d4950a0f3b08c996 |
def test_adding_event_in_various_manners(tmpdir): <NEW_LINE> <INDENT> asdf_filename = os.path.join(tmpdir.strpath, "test.h5") <NEW_LINE> data_path = os.path.join(data_dir, "small_sample_data_set") <NEW_LINE> event_filename = os.path.join(data_path, "quake.xml") <NEW_LINE> ref_cat = obspy.read_events(event_filename) <NE... | Events can be added either as filenames, open files, BytesIOs, or ObsPy
objects. In any case, the result should be the same. | 625941f61f037a2d8b94684d |
def init_reddit(): <NEW_LINE> <INDENT> client_id = '' <NEW_LINE> client_secret = '' <NEW_LINE> user_agent = '' <NEW_LINE> reddit = praw.Reddit(client_id=client_id, client_secret=client_secret, user_agent=user_agent) <NEW_LINE> return reddit | Initializes a connection w/ Reddit | 625941f6e8904600ed9f2589 |
def getFamsNonEmptyLevels(self, *args): <NEW_LINE> <INDENT> return _MEDCalculator.MEDFileUMesh_getFamsNonEmptyLevels(self, *args) | getFamsNonEmptyLevels(self, svec fams) -> ivec
1 | 625941f6236d856c2ad44e35 |
def test_preferences(self): <NEW_LINE> <INDENT> self.user_login('test') <NEW_LINE> response = self.client.get(reverse('core:user:preferences')) <NEW_LINE> profile = User.objects.get(username='test').userprofile <NEW_LINE> self.assertFalse(profile.show_comments) <NEW_LINE> self.assertEqual(response.status_code, 200) <NE... | Helper function to test the preferences page | 625941f650812a4eaa59c96b |
def test_provider_matches(): <NEW_LINE> <INDENT> p = gce.get_configured_provider() <NEW_LINE> assert p is not None | Test that the first configured instance of a gce driver is matched | 625941f63c8af77a43ae3df9 |
def getAllMacroNodes(self): <NEW_LINE> <INDENT> macros = {} <NEW_LINE> mnodes = [] <NEW_LINE> for node in self.getAllNodes(): <NEW_LINE> <INDENT> if isMacroChildNode(node): <NEW_LINE> <INDENT> macros[str(node.macroParent().getID())] = node.getSiblingNodes() <NEW_LINE> mnodes.append(node.macroParent()) <NEW_LINE> <DEDEN... | Find all nodes that belong to macro-framework, then store them in a
dictionary based on macro-object-id. | 625941f65e10d32532c5f575 |
def download_projects_images(self, path): <NEW_LINE> <INDENT> images = self.getImages() <NEW_LINE> if not images: <NEW_LINE> <INDENT> print (f"No files found in {self.PF_FOLDER_NAME}", flush=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for img in images: <NEW_LINE> <INDENT> req = self.api.files().get_media(fileI... | Downloads the images stored on the google drive folder,
to a given path
:param str path: the path where the files will be downloaded to | 625941f63617ad0b5ed68547 |
def session_closed(self): <NEW_LINE> <INDENT> self._detach() <NEW_LINE> self.safe_finish() | Called by the session when it was closed | 625941f673bcbd0ca4b2c6c6 |
def InitFromGpPoint(self, GpPoint, resolution): <NEW_LINE> <INDENT> self.InitFromCoordinates(GpPoint.lat, GpPoint.lon ,resolution) | Initialize from a GpPoint at specified resolution. | 625941f63d592f4c4ed1d6ac |
def to_json(self): <NEW_LINE> <INDENT> result = { "ip_address": self.ip_address, "locale_code": self.locale_code, "continent": { "name": self.continent_name, "code": self.continent_code }, "country": { "name": self.country_name, "code": self.country_iso_code }, "subdivision1": { "name": self.subdiv1_name, "code": self.... | Returns all geolocation data as a JSON string. | 625941f68c3a873295158a14 |
def test_threshold_viz_quick_method_read_data(self): <NEW_LINE> <INDENT> model = BernoulliNB(3) <NEW_LINE> visualizer = type('Visualizer', (object, ), {'ax': thresholdviz(model, X, y)}) <NEW_LINE> self.assert_images_similar(visualizer) | Test for thresholdviz quick method with visual unit test | 625941f67b25080760e39aa6 |
def deep(self): <NEW_LINE> <INDENT> return self.__deep | Get deep search | 625941f64f88993c3716c6b1 |
def testInvalidLength(self): <NEW_LINE> <INDENT> self.bot.replies = ['i6 i2', 'g6 g3', 'e6 e4', 'c4 c1', 'c4 c2', 'a7 a8'] <NEW_LINE> board = battleships.SeaBoard(self.bot) <NEW_LINE> self.assertEqual(['Cruisers must be 3 squares long.\n'], self.bot.errors) | Test the error from entering a ship of the wrong size. | 625941f6d164cc61757833a0 |
def fix_text(s, tp='answer'): <NEW_LINE> <INDENT> drop = False <NEW_LINE> if 'math::' in s: <NEW_LINE> <INDENT> errwarn('\n*** warning: quiz %s with math block not supported:' % tp) <NEW_LINE> errwarn(s) <NEW_LINE> drop = True <NEW_LINE> <DEDENT> if '.. code-block::' in s: <NEW_LINE> <INDENT> errwarn('\n*** warning: qu... | Answers and feedback in RunestoneInteractive book quizzes
cannot contain math, figure and rst markup. Perform fixes. | 625941f666673b3332b926e2 |
def result_list(cl): <NEW_LINE> <INDENT> return {'cl': cl, 'result_headers': list(result_headers(cl)), 'results': list(results(cl))} | Displays the headers and data list together | 625941f6498bea3a759ba0fe |
def obs_normalizer(observation): <NEW_LINE> <INDENT> if isinstance(observation, tuple): <NEW_LINE> <INDENT> observation = observation[0] <NEW_LINE> <DEDENT> if isinstance(observation, dict): <NEW_LINE> <INDENT> observation = observation['history'] <NEW_LINE> <DEDENT> observation = observation[:, :, 3:4] / observation[:... | Preprocess observation obtained by environment
Args:
observation: (nb_classes, window_length, num_features) or with info
Returns: normalized | 625941f6be8e80087fb21288 |
def init_x_g0(card, eid, x1_default, x2_default, x3_default): <NEW_LINE> <INDENT> field5 = integer_double_or_blank(card, 5, 'g0_x1', x1_default) <NEW_LINE> if isinstance(field5, integer_types): <NEW_LINE> <INDENT> g0 = field5 <NEW_LINE> x = None <NEW_LINE> <DEDENT> elif isinstance(field5, float): <NEW_LINE> <INDENT> g0... | common method to read the x/g0 field for the CBAR, CBEAM, CBEAM3 | 625941f656b00c62f0f14caf |
def quit(self, widget, data=None): <NEW_LINE> <INDENT> self.destroy() | quit - signal handler for closing the XratersWindow | 625941f6e1aae11d1e74a30f |
def authorize(self, username, password, kiln_account_domain, *args, **kwargs): <NEW_LINE> <INDENT> self.account.data['kiln_account_domain'] = kiln_account_domain <NEW_LINE> token = self.client.login(username, password) <NEW_LINE> self.account.data['auth_token'] = token | Authorizes the Kiln repository.
Kiln requires an authentication request against a login URL,
and will return an API token on success. This token is stored
along with the account data. The username and password are not
stored. | 625941f663d6d428bbe44b43 |
def test_cstyle_multi_comment_multi_line_long(self): <NEW_LINE> <INDENT> bug_line = 60 <NEW_LINE> sc_handler = SourceCodeCommentHandler(self.__tmp_srcfile_3) <NEW_LINE> res = sc_handler.has_source_line_comments(bug_line) <NEW_LINE> self.assertTrue(res) <NEW_LINE> source_line_comments = sc_handler.get_source_line_commen... | Multi line C style comment with multiple review status comment.
/* codechecker_false_positive [ my.checker_2, my.checker_1 ] comment
which
is
long
codechecker_intentional [ my.checker_1 ] intentional comment
long
again */ | 625941f655399d3f05588d0a |
def _move_cursor_without_reading (self) : <NEW_LINE> <INDENT> cell = numpy.zeros((3,3)) <NEW_LINE> if self._is_endoffile() : <NEW_LINE> <INDENT> return None, None <NEW_LINE> <DEDENT> self.position += 1 <NEW_LINE> coords = numpy.array([]) <NEW_LINE> return coords, cell | Move the cursor forward and return coords as empty array | 625941f63d592f4c4ed1d6ad |
def createUuidV5(self, QUuid, *__args): <NEW_LINE> <INDENT> return QUuid | createUuidV5(QUuid, Union[QByteArray, bytes, bytearray]) -> QUuid
createUuidV5(QUuid, str) -> QUuid | 625941f6e5267d203edce2e6 |
def DrawSplitter(self, dc): <NEW_LINE> <INDENT> backColour = self.GetBackgroundColour() <NEW_LINE> dc.SetBrush(wx.Brush(backColour, wx.SOLID)) <NEW_LINE> dc.SetPen(wx.Pen(backColour)) <NEW_LINE> dc.Clear() <NEW_LINE> if wx.VERSION >= _RENDER_VER: <NEW_LINE> <INDENT> if self.HasFlag(wx.SP_3DBORDER): <NEW_LINE> <INDENT> ... | Actually draws the sashes.
:param `dc`: an instance of :class:`DC`. | 625941f6bde94217f368343c |
def vgg13_bn(pretrained=False, progress=True, **kwargs): <NEW_LINE> <INDENT> return _vgg('vgg13_bn', 'B', True, pretrained, progress, **kwargs) | VGG 13-layer model (configuration "B") with batch normalization
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr | 625941f6187af65679ca5772 |
def build(self, parent): <NEW_LINE> <INDENT> wx.Dialog.__init__( self, parent, title='DPC230 Options', size=(350, 300)) <NEW_LINE> self.mainsizer = wx.BoxSizer(wx.VERTICAL) <NEW_LINE> self.simple_label('Integration time') <NEW_LINE> default = qy.settings.get('realtime.integration_time') <NEW_LINE> self.integration_time... | Construct the body of the GUI | 625941f699fddb7c1c9de9de |
def consViewerConfigured(self, widget, event): <NEW_LINE> <INDENT> new_width = self.da.get_allocated_width() <NEW_LINE> if self.rescrolldata.fontchanged: <NEW_LINE> <INDENT> if self.rescrolldata.oldwidth != new_width: <NEW_LINE> <INDENT> adj = self.get_hadjustment() <NEW_LINE> page_size = adj.get_page_size() <NEW_LINE>... | Responds to ConsensusSequenceViewer size changes that are caused by
font changes to ensure that the correct part of the viewer remains
centered in the visible part of the window. | 625941f60a50d4780f6674e9 |
def keypresses_to_default_partition(self, keypresses): <NEW_LINE> <INDENT> if self._client: <NEW_LINE> <INDENT> self._client.keypresses_to_default_partition(keypresses) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _LOGGER.error(COMMAND_ERR) | Send a key to the current partition. | 625941f699fddb7c1c9de9df |
def send_command(child, cmd): <NEW_LINE> <INDENT> child.sendline(cmd) <NEW_LINE> child.expect(PROMPT) <NEW_LINE> print(child.before) | A function to send commands during ssh interaction. | 625941f6a05bb46b383ece6c |
def main_menu(self) -> None: <NEW_LINE> <INDENT> main_menu_choices = self.get_root_menu_actions() <NEW_LINE> action: Optional[RootAction] = list_choice_menu( main_menu_choices, 'What do you want to do?', back=self._back, ) <NEW_LINE> if action is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> action_method = self... | Displays the backend main menu
By default, proposes all the `RootAction` and call their handler
Parameters
==========
back: Callable
The function to call when the user choses to go back
If set to `None` (default) the menu will not display a *BACK* option | 625941f61b99ca400220b106 |
def radial_to_vector(magnitude, direction, orientation='to'): <NEW_LINE> <INDENT> assert orientation in ['from', 'to'] <NEW_LINE> v = np.cos(direction) * magnitude <NEW_LINE> u = np.sin(direction) * magnitude <NEW_LINE> if orientation == "from": <NEW_LINE> <INDENT> v = -v <NEW_LINE> u = -u <NEW_LINE> <DEDENT> return u,... | Converts from a radial variable defined by a magnitude and
direction from north to zonal (u) and meridianal (v) components. | 625941f650812a4eaa59c96c |
def transform_letter_to_index(transcript, letter_list): <NEW_LINE> <INDENT> output=[] <NEW_LINE> for item in range(transcript.shape[0]): <NEW_LINE> <INDENT> temp='' <NEW_LINE> for i in transcript[item]: <NEW_LINE> <INDENT> i=i.decode('UTF-8') <NEW_LINE> for j in i: <NEW_LINE> <INDENT> temp+=j <NEW_LINE> <DEDENT> temp+=... | :param transcript :(N, ) Transcripts are the text input
:param letter_list: Letter list defined above
:return letter_to_index_list: Returns a list for all the transcript sentence to index | 625941f6a17c0f6771cbe6a0 |
def chunk(it: Union[Iterable[V], PeekingIterator[V]], n: int, metric: Callable[[V], int] = one ) -> Iterable[Iterable[V]]: <NEW_LINE> <INDENT> if not isinstance(it, PeekingIterator): <NEW_LINE> <INDENT> it = PeekingIterator(it) <NEW_LINE> <DEDENT> assert isinstance(it, PeekingIterator) <NEW_LINE> has_more: bool = True ... | :param it: stream of values as a PeekingIterator (or regular iterable if you are only going to take the first chunk
and don't care about the peeked value being consumed)
:param n: consume stream until n is reached. if n is 0, process whole stream as one chunk.
:param metric: the callable that returns positive metric f... | 625941f638b623060ff0b43e |
def test02_logout_service_description(self): <NEW_LINE> <INDENT> auth = IIIFAuthBasic() <NEW_LINE> auth.logout_uri = 'xyz' <NEW_LINE> lsd = auth.logout_service_description() <NEW_LINE> self.assertEqual(lsd['profile'], 'http://iiif.io/api/auth/1/logout') <NEW_LINE> self.assertEqual(lsd['@id'], 'xyz') <NEW_LINE> self.ass... | Test logout_service_description. | 625941f607f4c71912b11ad7 |
def testStrandsPositiveEnd(self): <NEW_LINE> <INDENT> self._runTest(starts=[10], ends=[20], strands=['+'], expStarts=[10], expEnds=[25], expStrands=['+'], upstream=5, useStrands=True, expTrackFormatType="Segments") | Using strand, positive at the end.
:return: | 625941f67d43ff24873a32f7 |
def map_downwind_node_link_max_to_node(grid, var_name, out=None): <NEW_LINE> <INDENT> if out is None: <NEW_LINE> <INDENT> out = grid.empty(at="node") <NEW_LINE> <DEDENT> if type(var_name) is str: <NEW_LINE> <INDENT> var_name = grid.at_link[var_name] <NEW_LINE> <DEDENT> values_at_links = var_name[grid.links_at_node] * g... | Map the largest magnitude of the links carrying flux from the node to
the node.
map_downwind_node_link_max_to_node iterates across the grid and identifies
the link values at each link connected to a node. It then uses the
link_dirs_at_node data structure to identify links carrying flux out of the
node, then maps the m... | 625941f68c3a873295158a15 |
def load_long_lat_data(): <NEW_LINE> <INDENT> with gzip.open(os.path.join(DATA_FOLDER, 'san_francisco.csv.gz')) as f: <NEW_LINE> <INDENT> pdf = pd.read_csv(f, encoding="utf-8") <NEW_LINE> <DEDENT> pdf['date'] = datetime.datetime.now().date() <NEW_LINE> pdf['occupancy'] = [random.randint(1, 6) for _ in range(len(pdf))] ... | Loading lat/long data from a csv file in the repo | 625941f6097d151d1a2234a8 |
def read_all(self): <NEW_LINE> <INDENT> with self.ser as s: <NEW_LINE> <INDENT> ret = s.read(s.in_waiting()) <NEW_LINE> <DEDENT> logger.debug("Read all waiting bytes from serial device on port %s", self.ser.port) <NEW_LINE> logger.debug("Serial device on port %s returned %s", self.ser.port, ret.decode()) <NEW_LINE> ret... | This wraps the Serial.read() function, and returns all of the
waiting bytes.
:returns: The ascii (decoded) value of the ``Serial.read()``
:rtype: str | 625941f6167d2b6e312191e6 |
def get_investigations_count(self, query: Optional[str] = None) -> int: <NEW_LINE> <INDENT> query_name = "investigationsCount" <NEW_LINE> frame = inspect.currentframe() <NEW_LINE> arguments = get_args_from_frame(frame) <NEW_LINE> result = self._service.execute_gql_query( gql_name=query_name, **arguments ) <NEW_LINE> re... | Get aggregated investigations counts based on CQL query
:param query: cql query | 625941f6d99f1b3c44c67bd4 |
def submit_vserver_limit(vs_host, type_instance, value): <NEW_LINE> <INDENT> submit_generic(vs_host, 'context', 'vs_vlimit', value, type_instance) | Reports vserver vlimit metrics to collectd. | 625941f6627d3e7fe0d694a4 |
def preprocess_args(fun, varnames): <NEW_LINE> <INDENT> def wrapper(f, *a, **kw): <NEW_LINE> <INDENT> func_code = f.__code__ <NEW_LINE> names = func_code.co_varnames <NEW_LINE> new_a = [ fun(arg) if (name in varnames) else arg for (arg, name) in zip(a, names) ] <NEW_LINE> new_kw = {k: fun(v) if k in varnames else v for... | Applies fun to variables in varnames before launching the function | 625941f66fece00bbac2dd98 |
def import_path(name): <NEW_LINE> <INDENT> modname, __, attr = name.rpartition('.') <NEW_LINE> if not modname: <NEW_LINE> <INDENT> return __import__(attr) <NEW_LINE> <DEDENT> m = __import__(modname, fromlist=[attr]) <NEW_LINE> return getattr(m, attr) | import a callable from full module.callable name | 625941f6099cdd3c635f12a9 |
def delMin(self): <NEW_LINE> <INDENT> returnVal = self.heapArray[1] <NEW_LINE> self.heapArray[1] = self.heapArray.pop() <NEW_LINE> self.currentSize -= 1 <NEW_LINE> self.percDown(1) <NEW_LINE> return returnVal | B:删除最小项 | 625941f67047854f462a1a54 |
def psetPhoFull5x5SigmaIEtaIEtaCut(wpEB, wpEE): <NEW_LINE> <INDENT> return cms.PSet( cutName = cms.string('PhoFull5x5SigmaIEtaIEtaCut'), cutValueEB = cms.double( wpEB.full5x5_sigmaIEtaIEtaCut ), cutValueEE = cms.double( wpEE.full5x5_sigmaIEtaIEtaCut ), barrelCutOff = cms.double(ebCutOff), needsAdditionalProducts = cms.... | Arguments: two containers of working point cut values of the type WorkingPoint_* | 625941f6be7bc26dc91cdc45 |
def parse(self): <NEW_LINE> <INDENT> for (genre, link) in self.urls_to_scrap.items(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> soup = self.make_soup(link) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> song_date = soup.find( 'a', {'class': 'select'} ).text.split('-')[0].strip... | Returns list of `Song`s and assign them to `self.Song` | 625941f6236d856c2ad44e36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.