code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def assert_word_shuffle_with_distance_3(self, x, x_noised, x_len, l_noised): <NEW_LINE> <INDENT> for i in range(x_len[0]): <NEW_LINE> <INDENT> self.assertEqual(x[i][0], x_noised[i][0]) <NEW_LINE> <DEDENT> shuffle_map = {0: 0, 1: 3, 2: 1, 3: 2} <NEW_LINE> for k, v in shuffle_map.items(): <NEW_LINE> <INDENT> self.assertE... | Applies word shuffle with max_shuffle_distance = 3 and asserts that the
shuffling result is as expected. If test data changes, update this func | 625941cb3346ee7daa2b2e30 |
def kfold_run(self, clusters): <NEW_LINE> <INDENT> kmeans_model = kmeans.model_build(clusters) <NEW_LINE> super().kfold_run(kmeans_model) | Runs kfold cross-validation using the generated KMeans model. | 625941cbd486a94d0b98e20a |
@patch('curdling.services.curdler.guess_file_type') <NEW_LINE> def test_unpack_error(guess_file_type): <NEW_LINE> <INDENT> guess_file_type.return_value = None <NEW_LINE> curdler.unpack.when.called_with('pkg.abc').should.throw( curdler.UnpackingError, 'Unknown compress format for file pkg.abc' ) | unpack() Should raise `UnpackingError` on unknown files | 625941cb377c676e9127226d |
def update(self,current_value): <NEW_LINE> <INDENT> self.error = self.set_point - current_value <NEW_LINE> self.P_value = self.Kp * self.error <NEW_LINE> if (self.last_value >= current_value): <NEW_LINE> <INDENT> change = self.error - self.last_error <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> change = 0.0 <NEW_LINE>... | Calculate PID output value for given reference input and feedback | 625941cb66656f66f7cbc270 |
def fetch_all_mrs_data(conn): <NEW_LINE> <INDENT> return _fetch_all_from_table(conn, TABLE_NAME_BRAINSCANS) | Fetches all MRS data from the database.
Args:
conn: A database Connection object.
Returns:
List of all MRS data entries in the database. Each item in the list is
a 4-tuple of the form (ID, filename, MRS file contents, group label). | 625941cb2c8b7c6e89b35886 |
def _MergeRow(self, other_row, id_columns, merge_rules=None): <NEW_LINE> <INDENT> id_values = self._GetIdValuesForRow(other_row, id_columns) <NEW_LINE> row_indices = self.GetRowIndicesByValue(id_values) <NEW_LINE> if row_indices: <NEW_LINE> <INDENT> row_index = row_indices[0] <NEW_LINE> row = self.GetRowByIndex(row_ind... | Merge |other_row| into this table.
See MergeTables for description of |id_columns| and |merge_rules|. | 625941cbeab8aa0e5d26dc1d |
def setListAllMachine(self, *args, **kwargs): <NEW_LINE> <INDENT> return _VISHNU.ListMachineOptions_setListAllMachine(self, *args, **kwargs) | setListAllMachine(self, EBoolean _listAllMachine) | 625941cb60cbc95b062c6608 |
def __call__(self, endian = None, record = None): <NEW_LINE> <INDENT> if endian != None: <NEW_LINE> <INDENT> if ((endian == '<') or (endian == '>')): <NEW_LINE> <INDENT> self.endian = endian <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise STDFError("%s object creation error : unsupported endian '%s'" % (self.id, en... | Method to change contents of an already created object. (eg : Change endian) | 625941cb32920d7e50b28294 |
def eit_solve(self, detect_potential, lmbda=295): <NEW_LINE> <INDENT> J = self.eliminate_non_detect_JAC() - 1 <NEW_LINE> Q = np.eye(J.shape[1]) <NEW_LINE> delta_V = detect_potential - np.copy(self.electrode_original_potential) <NEW_LINE> capacitance_predict = np.dot(np.dot(np.linalg.inv(np.dot(J.T, J) + lmbda ** 2 * Q)... | detect_potential: electrode_num * (electrode_num - 1) elements NDArray vector
lmbda: FLOAT regularization parameter | 625941cb442bda511e8be4de |
def generate(self, include_draft=False): <NEW_LINE> <INDENT> self.include_draft = include_draft <NEW_LINE> logger.debug("Empty the destination directory") <NEW_LINE> dest_dir = os.path.join(self.target_path, self.config["destination"]) <NEW_LINE> if os.path.exists(dest_dir): <NEW_LINE> <INDENT> exclude_list = ['.git', ... | :include_draft: True/False, include draft pages or not to generate. | 625941cbbe7bc26dc91cd6c6 |
def get_page_articles(self, page_uri): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> r = requests.get(page_uri, headers=self.headers, cookies=self.cookies, timeout=10) <NEW_LINE> end_time = time.time() <NEW_LINE> <DEDENT> except requests.exceptions.RequestException as e: <NEW_LINE> <I... | 获取页面文章列表
Args:
page_uri: 文章列表页地址(直接带参数即可)
Returns:
解析成功返回文章列表, 类型: list 如下:
[
{'title': '标题名',
'summary': '摘要',
'article_uri': '文章链接',
'account_name': '公众号账户名'
},
{},
...
]
解析失败返回: None | 625941cb3317a56b86939d1e |
def __init__(self, peer: 'TypeInputPeer', q: str, filter: 'TypeMessagesFilter', min_date: Optional[datetime], max_date: Optional[datetime], offset_id: int, add_offset: int, limit: int, max_id: int, min_id: int, hash: int, from_id: Optional['TypeInputPeer']=None, top_msg_id: Optional[int]=None): <NEW_LINE> <INDENT> self... | :returns messages.Messages: Instance of either Messages, MessagesSlice, ChannelMessages, MessagesNotModified. | 625941cbbe8e80087fb20d08 |
def check(filenames, select=None, ignore=None, ignore_decorators=None): <NEW_LINE> <INDENT> if select is not None and ignore is not None: <NEW_LINE> <INDENT> raise IllegalConfiguration('Cannot pass both select and ignore. ' 'They are mutually exclusive.') <NEW_LINE> <DEDENT> elif select is not None: <NEW_LINE> <INDENT>... | Generate docstring errors that exist in `filenames` iterable.
By default, the PEP-257 convention is checked. To specifically define the
set of error codes to check for, supply either `select` or `ignore` (but
not both). In either case, the parameter should be a collection of error
code strings, e.g., {'D100', 'D404'}.... | 625941cb4e4d5625662d449d |
def get_release_revision(self, project, release_id, definition_snapshot_revision, **kwargs): <NEW_LINE> <INDENT> route_values = {} <NEW_LINE> if project is not None: <NEW_LINE> <INDENT> route_values['project'] = self._serialize.url('project', project, 'str') <NEW_LINE> <DEDENT> if release_id is not None: <NEW_LINE> <IN... | GetReleaseRevision.
[Preview API] Get release for a given revision number.
:param str project: Project ID or project name
:param int release_id: Id of the release.
:param int definition_snapshot_revision: Definition snapshot revision number.
:rtype: object | 625941cbbde94217f3682eb6 |
def __init__(self, name, courses): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.courses = {"courses": courses} <NEW_LINE> self.students = {"students": []} <NEW_LINE> self.teachers = {"teachers": []} <NEW_LINE> self.begin_date = datetime.datetime.now() <NEW_LINE> self.status = 0 | 定义班级属性
:param name: 班级名称,字符属性
:param courses: 学习课程名称,字典类型
:param students: 学员,字典类型
:param teachers: 讲师,字典类型
:param begin_date: 开课时间,默认为班级创建时间
:param status: 是否已开课,默认开课后不允许添加新成员 0 为开课, 1 为已开课 | 625941cb9f2886367277a953 |
def coeff_friction(n,fc): <NEW_LINE> <INDENT> return (1.-fc)*(1.-(1.-fc)**n)/fc | Renvoie le coefficient d'une grandeur physique
dont le taux de changement sur le temps varie
de forme proportionnelle a <fc> | 625941cb627d3e7fe0d68f15 |
def sink(self, name, filter_, destination): <NEW_LINE> <INDENT> return Sink(name, filter_, destination, client=self) | Creates a sink bound to the current client.
:type name: str
:param name: the name of the sink to be constructed.
:type filter_: str
:param filter_: the advanced logs filter expression defining the
entries exported by the sink.
:type destination: str
:param destination: destination URI for the entries... | 625941cb21a7993f00bc7db4 |
def __init__(self): <NEW_LINE> <INDENT> self.EvidenceInfo = None <NEW_LINE> self.EvidenceName = None <NEW_LINE> self.BusinessId = None <NEW_LINE> self.HashType = None <NEW_LINE> self.EvidenceDescription = None | :param EvidenceInfo: 业务数据明文(json格式字符串),最大256kb
:type EvidenceInfo: str
:param EvidenceName: 存证名称(长度最大30)
:type EvidenceName: str
:param BusinessId: 业务ID 透传 长度最大不超过64
:type BusinessId: str
:param HashType: 算法类型 0 SM3, 1 SHA256, 2 SHA384 默认0
:type HashType: int
:param EvidenceDescription: 存证描述
:type EvidenceDescription: ... | 625941cb71ff763f4b549750 |
def add_dependency(self, preceding_message): <NEW_LINE> <INDENT> dependency = QueuedMessageDependency( preceding_message=preceding_message, dependent_message=self ) <NEW_LINE> dependency.put() | Create a dependency between this Message and a preceding Message required to be
finished before this one. | 625941cb460517430c39424b |
def test16_process_inventory_adjustments_returns_None_when_no_drift(self): <NEW_LINE> <INDENT> inv = self.test_location_01._process_inventory_adjustments([]) <NEW_LINE> self.assertIsNone(inv, "Returned a new inventory for empty request") | Returns None when no request item is specified | 625941cbd58c6744b4257d25 |
def purge_all(self, *files): <NEW_LINE> <INDENT> self._request('purge.purge.all', 'GET') | Purge all resources from the CDN.
| 625941cb8a43f66fc4b5412b |
def set_year(self, album_id, year, sql=None): <NEW_LINE> <INDENT> if not sql: <NEW_LINE> <INDENT> sql = Lp.sql <NEW_LINE> <DEDENT> sql.execute("UPDATE albums SET year=? WHERE rowid=?", (year, album_id)) | Set year
@param album id as int
@param year as int
@warning: commit needed | 625941cb63f4b57ef00011e0 |
def __init__(self, data_dir, batch_size, num_steps, epochs): <NEW_LINE> <INDENT> self.data_dir = data_dir <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.num_steps = num_steps <NEW_LINE> self.epochs = epochs <NEW_LINE> self.mean = 44 <NEW_LINE> self.stddev2 = 1.0 / 15.5 <NEW_LINE> with open(data_dir, 'r') as f:... | data_dir: dir to store the .pkl
num_steps: time steps used for unfolding
RNN | 625941cbbde94217f3682eb7 |
def load_compute_driver(virtapi, compute_driver=None): <NEW_LINE> <INDENT> if not compute_driver: <NEW_LINE> <INDENT> compute_driver = CONF.compute_driver <NEW_LINE> <DEDENT> if not compute_driver: <NEW_LINE> <INDENT> LOG.error(_("Compute driver option required, but not specified")) <NEW_LINE> sys.exit(1) <NEW_LINE> <D... | Load a compute driver module.
Load the compute driver module specified by the compute_driver
configuration option or, if supplied, the driver name supplied as an
argument.
Compute drivers constructors take a VirtAPI object as their first object
and this must be supplied.
:param virtapi: a VirtAPI instance
:param com... | 625941cb76e4537e8c351738 |
def test_permissions(self): <NEW_LINE> <INDENT> self.assertForbidden(self.client.get(self.url)) <NEW_LINE> self.assertForbidden(self.client.post(self.url, data={'ok': True})) <NEW_LINE> self.add_permission('delete_registrationcenter') <NEW_LINE> self.add_permission('browse_registrationcenter') <NEW_LINE> self.assertOK(... | ensure permission required to access delete page | 625941cb01c39578d7e74f01 |
def update_view(self): <NEW_LINE> <INDENT> self.draw() | place holder; should update only the limits without recalculating
the impulse respons | 625941cb63d6d428bbe445b5 |
def binary_search_2(items: list, target)->bool: <NEW_LINE> <INDENT> start_i = 0 <NEW_LINE> end_i = len(items) - 1 <NEW_LINE> while True: <NEW_LINE> <INDENT> mid_i = (start_i + end_i) // 2 <NEW_LINE> if items[mid_i] == target: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif items[mid_i] < target: <NEW_LINE> <IN... | Implement the binary search using while loop | 625941cb167d2b6e31218c5b |
def __script_two(self, account_id, client_id, ids, start_campaigns_unix_time, stop_campaigns_unix_time, money_limit, impressions_count, token): <NEW_LINE> <INDENT> pass | :param account_id:
:param client_id:
:param ids:
:param start_campaigns_unix_time:
:param stop_campaigns_unix_time:
:param money_limit:
:param impressions_count:
:param token:
:return: | 625941cb8c0ade5d55d3ea80 |
def prev(*args, **kwargs): <NEW_LINE> <INDENT> note = utils.get_from_name(current, args) <NEW_LINE> if note is None: <NEW_LINE> <INDENT> note = current <NEW_LINE> <DEDENT> print(note.text[:30]) | Preview the contents of a file, displaying the first 30 characters of the note. | 625941cb004d5f362079a3f9 |
def aggregate(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.query.distinct_fields: <NEW_LINE> <INDENT> raise NotImplementedError("aggregate() + distinct(fields) not implemented.") <NEW_LINE> <DEDENT> for arg in args: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> arg.default_alias <NEW_LINE> <DEDENT> except (Attrib... | Returns a dictionary containing the calculations (aggregation)
over the current queryset
If args is present the expression is passed as a kwarg using
the Aggregate object's default alias. | 625941cb4c3428357757c3ed |
def set_freewheel_callback(self, callback): <NEW_LINE> <INDENT> @self._callback("JackFreewheelCallback") <NEW_LINE> def callback_wrapper(starting, _): <NEW_LINE> <INDENT> callback(bool(starting)) <NEW_LINE> <DEDENT> _check(_lib.jack_set_freewheel_callback( self._ptr, callback_wrapper, _ffi.NULL), "Error setting freewhe... | Register freewheel callback.
Tell the JACK server to call `callback` whenever we enter or
leave "freewheel" mode.
The argument to the callback will be ``True`` if JACK is
entering freewheel mode, and ``False`` otherwise.
All "notification events" are received in a separated non RT
thread, the code in the supplied fun... | 625941cba934411ee3751759 |
@pytest.fixture <NEW_LINE> def clear_vasp_envvar(monkeypatch): <NEW_LINE> <INDENT> for envvar in Vasp.env_commands: <NEW_LINE> <INDENT> monkeypatch.delenv(envvar, raising=False) <NEW_LINE> assert envvar not in os.environ <NEW_LINE> <DEDENT> yield | Clear the environment variables which can be used to launch
a VASP calculation. | 625941cbf548e778e58cd643 |
def hide(self) -> None: <NEW_LINE> <INDENT> self.surface = None <NEW_LINE> pygame.display.quit() | Hide the window | 625941cb91f36d47f21ac5b8 |
def __eq__(self, other: 'ConfigCASigningProfilesCaCaconstraint') -> bool: <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Return `true` when self and other are equal, false otherwise. | 625941cb0a366e3fb873e8e0 |
def __init__(self,x=0., y=0., dist_mu=0.2, dist_sigma=0.1): <NEW_LINE> <INDENT> self.origin = array([x,y]) <NEW_LINE> self.dist_mu = dist_mu <NEW_LINE> self.dist_sigma = dist_sigma <NEW_LINE> self.current_pos = array([0., 0.]) <NEW_LINE> self.previous_angle = 0.0 | Initialize Explorer class
:param float dist_mu, dist_sigma: mean and standard deviation for sampling the distance of the next target | 625941cb44b2445a3393215c |
def BreadthFirstSearch(graph, start, end): <NEW_LINE> <INDENT> pathQueue = [start] <NEW_LINE> label = [-1 for i in range(len(graph.nodes))] <NEW_LINE> path = [Node('({}, {})'.format(-1, -1)) for i in range(len(graph.nodes))] <NEW_LINE> NumOfVertex = int(sqrt(len(graph.nodes))) <NEW_LINE> while len(pathQueue) != 0: <NEW... | Assumes graph is a Digraph; start and end are nodes
Returns a shortest path from start to end in graph | 625941cbb5575c28eb68e0c6 |
def __iadd__(self, other): <NEW_LINE> <INDENT> if hasattr(other, 'getAllParams'): <NEW_LINE> <INDENT> self.setAllParams([x + y for x, y in zip(self.getAllParams(), other.getAllParams())]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.setAllParams([x + other for x in self.getAllParams()]) <NEW_LINE> <DEDENT> return... | += | 625941cb82261d6c526ab564 |
def finalizar_matriz(lista): <NEW_LINE> <INDENT> for n in range(len(lista)): <NEW_LINE> <INDENT> for m in range(len(lista[n])): <NEW_LINE> <INDENT> lista[n][m]="0" | limpia la lista que tiene la matriz del juego | 625941cba4f1c619b28b0100 |
def test_post_callbacks(self): <NEW_LINE> <INDENT> post = [] <NEW_LINE> def post1(obj): <NEW_LINE> <INDENT> post.append('post1') <NEW_LINE> <DEDENT> def post2(obj): <NEW_LINE> <INDENT> post.append('post2') <NEW_LINE> <DEDENT> response = SimpleTemplateResponse('first/test.html', {}) <NEW_LINE> response.add_post_render_c... | Rendering a template response triggers the post-render callbacks | 625941cb82261d6c526ab565 |
def getHubServerConfig(self): <NEW_LINE> <INDENT> return self._iohub_server_config | Returns a dict containing the ioHub Server configuration that is being
used for the current ioHub experiment.
Args:
None
Returns:
dict: ioHub Server configuration. | 625941cb9c8ee82313fbb83b |
def sendValues(eletuple, arg): <NEW_LINE> <INDENT> time.sleep(2) <NEW_LINE> listkey = ['username', 'password'] <NEW_LINE> i = 0 <NEW_LINE> for key in listkey: <NEW_LINE> <INDENT> eletuple[i].send_keys('') <NEW_LINE> eletuple[i].clear() <NEW_LINE> eletuple[i].send_keys(arg[key]) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> tim... | :param eletuple:
:param arg: username,password
:return: | 625941cb7047854f462a14d0 |
def calculate_celsius(fahrenheit): <NEW_LINE> <INDENT> celsius = 5 / 9 * (fahrenheit - 32) <NEW_LINE> return celsius | calculate celsius using fahrenheit | 625941cb30c21e258bdfa563 |
def build_status_response(self, data, status=400): <NEW_LINE> <INDENT> raise StatusException(data, status) | An event occurred preventing the request from being completed | 625941cb009cb60464c63478 |
def ReadZeroQueryRuleData(input_stream): <NEW_LINE> <INDENT> zero_query_dict = collections.defaultdict(list) <NEW_LINE> for line in input_stream: <NEW_LINE> <INDENT> if line.startswith('#'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> line = line.rstrip('\r\n') <NEW_LINE> if not line: <NEW_LINE> <INDENT> continue ... | Reads zero query rule data from stream and returns zero query data. | 625941cb16aa5153ce36253e |
def __init__(self, nb_model: CTParsePipeline) -> None: <NEW_LINE> <INDENT> self._model = nb_model | Scorer based on a naive bayes estimator.
This scorer models the probability of having a correct parse, conditioned
on the sequence of rules (expressed as a categorical feature) that led to
that parse.
The score is also modified by a "length" factor that penalizes parses that
cover a smaller part of the text string.
... | 625941cb5fcc89381b1e1785 |
def p_boolex_select(p): <NEW_LINE> <INDENT> p[0] = 'check_selected(' + p[3] + ', ' + p[5] + ')' | boolex : SELECTED LPAREN term ',' term RPAREN | 625941cbff9c53063f47c2ba |
def get_language_from_request(request): <NEW_LINE> <INDENT> if hasattr(request, 'session'): <NEW_LINE> <INDENT> language_code = request.session.get(translation.LANGUAGE_SESSION_KEY) <NEW_LINE> if language_code: <NEW_LINE> <INDENT> return language_code <NEW_LINE> <DEDENT> <DEDENT> return request.COOKIES.get(settings.LAN... | Get the language in the session or as separate cookie.
Django methods should be used for regular cases. This is only useful for
very narrow cases. | 625941cb26068e7796caeda4 |
def coding_problem_05(): <NEW_LINE> <INDENT> pass | cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair.
Given this implementation of cons below, implement car and cdr.
>>> def cons(a, b):
... def pair(f):
... return f(a, b)
... return pair
>>> car, cdr = coding_problem_05()
>>> car(cons('first', 'l... | 625941cb435de62698dfdd13 |
def _noisy_samples(self, x: np.ndarray, n: Optional[int] = None) -> np.ndarray: <NEW_LINE> <INDENT> if n is None: <NEW_LINE> <INDENT> n = self.sample_size <NEW_LINE> <DEDENT> x = np.expand_dims(x, axis=0) <NEW_LINE> x = np.repeat(x, n, axis=0) <NEW_LINE> x = x + np.random.normal(scale=self.scale, size=x.shape).astype(A... | Adds Gaussian noise to `x` to generate samples. Optionally augments `y` similarly.
:param x: Sample input with shape as expected by the model.
:param n: Number of noisy samples to create.
:return: Array of samples of the same shape as `x`. | 625941cb63b5f9789fde71ac |
def split_all(self, iters = 10): <NEW_LINE> <INDENT> for _ in range(iters): <NEW_LINE> <INDENT> for i in range(self.n_clusts): <NEW_LINE> <INDENT> self.split_cluster(i) | Compare all possible cluster splits | 625941cb66673b3332b92157 |
def __call__(self, image): <NEW_LINE> <INDENT> return self.fgbg.apply(image) | Returns a foreground mask of the image. | 625941cbd18da76e2353259c |
def test_initialization(self, logger): <NEW_LINE> <INDENT> task = type('task', (object,), {'session_id': '123'}) <NEW_LINE> handler = OutputHandler(task) <NEW_LINE> logger.addHandler(handler) <NEW_LINE> assert handler.task == task <NEW_LINE> assert len(handler.contents) == 0 <NEW_LINE> assert handler.messages() == '' | Make sure that all necessary properties are set. | 625941cb851cf427c661a5d5 |
def make_salt(): <NEW_LINE> <INDENT> string = '' <NEW_LINE> for x in range(0,5): <NEW_LINE> <INDENT> string += random.choice(letters) <NEW_LINE> <DEDENT> return string | make_salt: Method for creating salt string for use of hashing user
passwords.
Returns:
Random string of length five. | 625941cb046cf37aa974ce0e |
def _type_pprint(obj, p, cycle): <NEW_LINE> <INDENT> mod = getattr(obj, '__module__', None) <NEW_LINE> if mod is None: <NEW_LINE> <INDENT> return p.text(obj.__name__) <NEW_LINE> <DEDENT> if mod in ('__builtin__', 'builtins', 'exceptions'): <NEW_LINE> <INDENT> name = obj.__name__ <NEW_LINE> <DEDENT> else: <NEW_LINE> <IN... | The pprint for classes and types. | 625941cb1f5feb6acb0c4c17 |
def _fit_chromosomes(self): <NEW_LINE> <INDENT> target_total = self.get_sum() <NEW_LINE> for chromosome in self.chromosomes: <NEW_LINE> <INDENT> chromosome.fit(target_total) | For each chromosome in the population, calculate its fitness | 625941cb5f7d997b87174b5e |
def startLogger(app): <NEW_LINE> <INDENT> handler = RotatingFileHandler('app.log', maxBytes=10000, backupCount=1) <NEW_LINE> handler.setLevel(logging.INFO) <NEW_LINE> app.logger.addHandler(handler) | Starts the logger | 625941cb091ae35668667025 |
def cycle_fix(x, z): <NEW_LINE> <INDENT> flat = [item for sublist in find_chain(x, z) for item in sublist] <NEW_LINE> flat = set(flat) <NEW_LINE> contender = x <NEW_LINE> flat.remove(contender) <NEW_LINE> new_isa = set(get_isa_list(x)) <NEW_LINE> new_includes = set(get_includes_list(x)) <NEW_LINE> for e in flat: <NEW_L... | fixes cycles that are identified and spelled out in path | 625941cb4d74a7450ccd428a |
def update(self,abs_tol=1e-5, rel_tol=1e-3): <NEW_LINE> <INDENT> self.beta_m_ac*=self.beta_m_ac <NEW_LINE> self.beta_v_ac*=self.beta_v_ac <NEW_LINE> _w2=0 <NEW_LINE> _check=0 <NEW_LINE> self.Q.averageGrad() <NEW_LINE> for i in range(self.dim): <NEW_LINE> <INDENT> self.mE[i]=self.beta_m*self.mE[i] + (1-self.beta_m)*self... | update should return a number that when it is smaller than 1
the main loop stops. Here I choose this number to be:
sqrt(1/dim*sum_{i=0}^{dim}(grad/(abs_tol+x*rel_tol))_i^2) | 625941cb2ae34c7f2600d1f8 |
def setup_test_loop( loop_factory: _LOOP_FACTORY = asyncio.new_event_loop, ) -> asyncio.AbstractEventLoop: <NEW_LINE> <INDENT> loop = loop_factory() <NEW_LINE> try: <NEW_LINE> <INDENT> module = loop.__class__.__module__ <NEW_LINE> skip_watcher = "uvloop" in module <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <... | Create and return an asyncio.BaseEventLoop
instance.
The caller should also call teardown_test_loop,
once they are done with the loop. | 625941cba8ecb033257d3194 |
def FY1_hydration(time): <NEW_LINE> <INDENT> amount = 750 * time <NEW_LINE> amountStr = '{}L'.format(str(ceil(float(amount) / 1000))) if amount > 1000 else '{}ml'.format(str(amount)) <NEW_LINE> plural = 's' if time > 1 else '' <NEW_LINE> print('You need to drink {} in the next {} hour{}'.format(amountStr, time, plural)... | Print the amount to drink. | 625941cb1b99ca400220ab78 |
def check_output(truth, estimation): <NEW_LINE> <INDENT> tol_xy = 15 <NEW_LINE> tol_ori = 0.25 <NEW_LINE> delta_xy = abs(truth[0:2] - estimation[0:2]) <NEW_LINE> delta_ori = abs((truth[-1] - estimation[-1] + np.pi) % (2 * np.pi) - np.pi) <NEW_LINE> if all(delta_xy < tol_xy) and delta_ori < tol_ori: <NEW_LINE> <INDENT> ... | :param truth: np array
:param estimation: np array
:return: | 625941cbb830903b967e99d2 |
def test_wait_for_db_ready(self): <NEW_LINE> <INDENT> with patch('django.db.utils.ConnectonHandler.__getitem__') as gi: <NEW_LINE> <INDENT> gi.return_value = True <NEW_LINE> call_command('wait_for_db') <NEW_LINE> self.assertEqual(gi.call_count, 1) | Test waiting for db when db is available | 625941cb7047854f462a14d1 |
def __init__(self, content_id, clicks, site=None, **kwargs): <NEW_LINE> <INDENT> self.clicks = clicks <NEW_LINE> super(PopularContent, self).__init__(content_id=content_id, site=site, **kwargs) | creates a new instance
:param content_id: the content's unique id
:type content_id: str or int
:param clicks: the number of clicks recorded for a piece of content
:type clicks: int
:param site: the site's name
:type site: str or None
:default site: None
:param kwargs: additional keyword arguments | 625941cba934411ee375175a |
@login_required <NEW_LINE> def index(request): <NEW_LINE> <INDENT> return HttpResponseRedirect('/targets/targetList/') | index page, just view a list
of targets in the database | 625941cbd10714528d5ffda9 |
def preprocess(img): <NEW_LINE> <INDENT> while int(np.mean(img[0])) == 255: <NEW_LINE> <INDENT> img = img[1:] <NEW_LINE> <DEDENT> while np.mean(img[:, 0]) == 255: <NEW_LINE> <INDENT> img = np.delete(img, 0, 1) <NEW_LINE> <DEDENT> while np.mean(img[-1]) == 255: <NEW_LINE> <INDENT> img = img[:-1] <NEW_LINE> <DEDENT> whil... | Preprocess incoming images in the same way that
images in the MNIST dataset were processed.
This code was adapted from
http://opensourc.es/blog/tensorflow-mnist
: param img : input black-and-white image
: returns : processed image | 625941cb76d4e153a657ebf7 |
def infer_gt_z(self, gammas): <NEW_LINE> <INDENT> return self.gt_enc(gammas) | :param gammas: mb,dim
:return: mb,z_dim | 625941cb4e696a04525c9512 |
def _update_status_db(self, status, msg): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data_source = DataSource(self._config['database']) <NEW_LINE> <DEDENT> except DataSourceException as err: <NEW_LINE> <INDENT> msg = 'data source initialization error [{}]'.format(str(err)) <NEW_LINE> Log.an().error(msg) <NEW_LINE> re... | Update the status of the step, and the status record in the database.
Args:
status: new step status.
msg: message associated with step status.
Returns:
On success: True.
On failure: False. | 625941cb8a43f66fc4b5412c |
def dump(self): <NEW_LINE> <INDENT> details = super().dump() <NEW_LINE> attrs = list(self.needs) <NEW_LINE> attrs += ["target", "satisfying", "job", "occupied"] <NEW_LINE> inv = [x.name for x in self.inventory] <NEW_LINE> broken = [x.name for x in self.memories.broken_items] <NEW_LINE> tasks = [f"{x.name}: {x.target.na... | Dumps pertinent object attributes for user to view | 625941cb4f6381625f114b02 |
def get_success_url(self): <NEW_LINE> <INDENT> return reverse('certifyingorganisation-detail', kwargs={ 'project_slug': self.object.certifying_organisation.project.slug, 'slug': self.object.certifying_organisation.slug }) | Define the redirect URL.
After successful creation of the object, the User will be redirected
to the Certifying Organisation detail page.
:returns: URL
:rtype: HttpResponse | 625941cb76d4e153a657ebf8 |
def __set__(self, obj, value): <NEW_LINE> <INDENT> driver = obj.driver <NEW_LINE> WebDriverWait(driver, 100).until( lambda driver: driver.find_element_by_name(self.locator)) <NEW_LINE> if (value == True): <NEW_LINE> <INDENT> driver.find_element_by_name(self.locator).click() | Sets the text to the value supplied | 625941cb498bea3a759b9b76 |
def _unregister_channel(self, channel, name): <NEW_LINE> <INDENT> self._lock.acquire() <NEW_LINE> if self._rchannels.get(name, None) is channel: <NEW_LINE> <INDENT> self._rchannels.pop(name, None) <NEW_LINE> ret = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret = -1 <NEW_LINE> <DEDENT> self._lock.release() <NEW_LIN... | Internal use only.
| 625941cb23849d37ff7b3156 |
def main(): <NEW_LINE> <INDENT> keys = list(data.keys()) <NEW_LINE> keys.sort() <NEW_LINE> import sys <NEW_LINE> user_input = input('What category would you like to explore? ({data}): '.format( data=', '.join(keys) )) <NEW_LINE> if user_input in keys: <NEW_LINE> <INDENT> first_prompt(user_input) <NEW_LINE> <DEDENT> eli... | main gets the initial category imported from data:
| 625941cb57b8e32f52483561 |
def get_transform(self): <NEW_LINE> <INDENT> return self.skin_transform.get_transform() | Return scale, rotation, and translation into a single 4x4 matrix. | 625941cb67a9b606de4a7f81 |
def checkio(alloys): <NEW_LINE> <INDENT> return 1 - sum([1 - v if 'gold' in k else v for (k, v) in alloys.iteritems()]) / 2 | Find proportion of gold, assume exist unique solution. | 625941cb656771135c3eb935 |
def __div__(self, rhs): <NEW_LINE> <INDENT> x, y, z = self._v <NEW_LINE> if hasattr(rhs, "__getitem__"): <NEW_LINE> <INDENT> ox, oy, oz = rhs <NEW_LINE> return self.from_floats(x/ox, y/oy, z/oz) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.from_floats(x/rhs, y/rhs, z/rhs) | Return the result of dividing this vector by another vector, or a scalar (single number). | 625941cb377c676e91272270 |
def show_tables(): <NEW_LINE> <INDENT> for i in T_LIST: <NEW_LINE> <INDENT> print_log(i) | 查看所有的表
:return: | 625941cb32920d7e50b28297 |
def AddPrjCompGrpCnlLink(self, comp, grp, cnl, link): <NEW_LINE> <INDENT> key_list = ["Components", comp, "Groups", grp, "Channels", cnl] <NEW_LINE> result = self.SetValueByKeyList(self.JSON_project, key_list, link) <NEW_LINE> return result | Add component object. | 625941cb7d847024c06be382 |
def collect_bands(band, nw_coords, se_coords, year_list, directory): <NEW_LINE> <INDENT> year_list = [str(x) for x in year_list] <NEW_LINE> archive_list = listdir(directory) <NEW_LINE> archive_list = [file for file in archive_list if file[9:13] in year_list] <NEW_LINE> subimage_list = [] <NEW_LINE> for archive in archi... | Collects sub-images of each band for each year and puts them
into a 3-dimensional array with the 3rd dimension being time
:param band: band of interest
:param nw_coords: UTM coordinates (meters) of the north west corner of interest
:param se_coords; UTM coordinates (meters) of the south east corner of interest
:param ... | 625941cb5e10d32532c5efee |
def _request_url_get(self, url): <NEW_LINE> <INDENT> self.request["url"] = url <NEW_LINE> self.request["response"] = self.request["session"].get( url, headers=self.request["headers"], verify=self.request["verify"], timeout=60, **self.request["parameters"], ) | Execute GET request and assign appropriate request dictionary
values | 625941cb7d43ff24873a2d67 |
def __init__(self, id_: int, centroid: np.ndarray, radius: float, weight: float, case_ids: list): <NEW_LINE> <INDENT> self.id = id_ <NEW_LINE> self.centroid = centroid <NEW_LINE> self.radius = radius <NEW_LINE> self.weight = weight <NEW_LINE> self.case_ids = case_ids | Receives an identifier, the position of the centroid,
the radius and a set of case identifier and initializes a cluster.
Parameters
--------------------------------------
id_: int
Cluster identifier
centroid: np.ndarray
Cluster centroid position
radius: float
Cluster radius,
measure of how far is the c... | 625941cb8da39b475bd6503b |
def test_examples(self): <NEW_LINE> <INDENT> tests = [ [1, [1, 1, 2, 3]], [2, [1, 2, 2, 3]], [2, [1, 2, 2, 3]], [2, [1, 2, 2, 3]], [2, [1, 2, 2, 3]], [3, [3, 1, 2, 3]], ] <NEW_LINE> for soln, ints in tests: <NEW_LINE> <INDENT> print("") <NEW_LINE> print("%s <- %s" % (soln, ints)) <NEW_LINE> ans = which_twice(ints) <NEW... | test some examples | 625941cb3317a56b86939d20 |
def getPageType(self): <NEW_LINE> <INDENT> return WebNotePage | Return type of the page. | 625941cbcdde0d52a9e530fa |
def cancel_order(self, id, symbol=None, params={}): <NEW_LINE> <INDENT> return self.exchange.cancel_order(id, symbol, params) | cancel order with id
:param id:
:param symbol:
:param params:
:return: | 625941cb3c8af77a43ae3867 |
def direction(dir): <NEW_LINE> <INDENT> if dir == UP: <NEW_LINE> <INDENT> return '>' <NEW_LINE> <DEDENT> elif dir == DOWN: <NEW_LINE> <INDENT> return '<' | Print the direction of the edge
:param dir: the direction
:return: a string representation of the direction | 625941cb6e29344779a626d9 |
def out(text): <NEW_LINE> <INDENT> if conf_out: <NEW_LINE> <INDENT> now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) <NEW_LINE> print("[%s] %s" % (now, text)) | Prints text to the terminal. | 625941cbde87d2750b85fe5a |
def predict(self, X): <NEW_LINE> <INDENT> X = np.insert(X, 0, 1, axis=1) <NEW_LINE> return X.dot(self.w) | Predict given test data using the linear model
Args:
X (numpy array of shape [n_samples, n_features]):
Test data
Returns:
C (numpy array of shape [n_samples]):
Predicted values from test data | 625941cb711fe17d82542433 |
def get_comparison_dict(session: Any) -> Dict[Tuple, Any]: <NEW_LINE> <INDENT> return { ( _.query_id, _.subject_id, _.program, _.version, _.fragsize, _.maxmatch, _.kmersize, _.minmatch, ): _ for _ in session.query(Comparison).all() } | Return a dictionary of comparisons in the session database.
:param session: live SQLAlchemy session of pyani database
Returns Comparison objects, keyed by (_.query_id, _.subject_id,
_.program, _.version, _.fragsize, _.maxmatch) tuple | 625941cbd4950a0f3b08c416 |
def plot(self,ax=None,show=True): <NEW_LINE> <INDENT> data = self.getData() <NEW_LINE> if len(np.shape(data))==1: <NEW_LINE> <INDENT> if ax is None: <NEW_LINE> <INDENT> plt.plot(data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ax.plot(data) <NEW_LINE> <DEDENT> if show: <NEW_LINE> <INDENT> plt.show() <NEW_LINE> <DEDE... | Basic plotter of data | 625941cba05bb46b383ec8e9 |
def has_direct_child(self, name): <NEW_LINE> <INDENT> return name in self._children | Determine if the :py:class:`Directory` contains the provided child.
Args:
name (str): The name of the child :py:class:`Node`
Returns:
bool: True if the child exist. | 625941cb99cbb53fe6792cae |
def do_stop(self, gently=True): <NEW_LINE> <INDENT> if gently: <NEW_LINE> <INDENT> self.service_stop('scylla-jmx') <NEW_LINE> self.service_stop('scylla-server') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res = run(['bash', '-c', f"docker exec {self.pid} bash -c 'kill -9 `supervisorctl pid scylla`'"], stdout=PIPE, st... | Stop the node.
- gently: Let Scylla and Scylla JMX clean up and shut down properly.
Otherwise do a 'kill -9' which shuts down faster. | 625941cba79ad161976cc20d |
def fast_missing_impute(df, method, cols): <NEW_LINE> <INDENT> assert isinstance(df, pd.DataFrame), "Data must be a data frame!" <NEW_LINE> assert isinstance(method, str), "Method must be a string!" <NEW_LINE> assert type(cols) == list, "Cols must be a list!" <NEW_LINE> assert method in ["remove", "mean", "median", "mo... | The function takes in a dataframe, a method of imputation, and a list of
column names to modify. The choices of imputation are either remove
(removes all rows with missing data), mean, median, or mode imputation.
The function includes error handling to stop plots from being created for
inappropriate column types, such ... | 625941cb4f88993c3716c12e |
def validate_dict(data, key_specs=None): <NEW_LINE> <INDENT> if not isinstance(data, dict): <NEW_LINE> <INDENT> msg = _("'%s' is not a dictionary") % data <NEW_LINE> LOG.debug(msg) <NEW_LINE> return msg <NEW_LINE> <DEDENT> if not key_specs: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> required_keys = [key for key, sp... | Validate data is a dict optionally containing a specific set of keys.
:param data: The data to validate.
:param key_specs: The optional list of keys that must be contained in
data.
:returns: None if data is a dict and (optionally) contains only key_specs.
Otherwise a human readable message is returned indicati... | 625941cbd10714528d5ffdaa |
def trial_count(inlier_ratio, n_sample, confidence=0.9999999980268246): <NEW_LINE> <INDENT> no_good_sample_prob = 1 - inlier_ratio ** n_sample <NEW_LINE> assert 0.5 <= confidence < 1 <NEW_LINE> assert 0 <= no_good_sample_prob < 1 <NEW_LINE> val = np.log(1 - confidence) / np.log(no_good_sample_prob) <NEW_LINE> if val ==... | default value of confidence is 6 sigma | 625941cb507cdc57c6306da1 |
def _UploadInstanceToHealthcareAPI(sop_instance_uid, inst): <NEW_LINE> <INDENT> http = httplib2.Http(timeout=60) <NEW_LINE> http = _CREDENTIALS.authorize(http) <NEW_LINE> related = MIMEMultipart("related", boundary="boundary") <NEW_LINE> setattr(related, "_write_headers", lambda self: None) <NEW_LINE> mime_attach = MIM... | Uploads instances in Healthcare API. | 625941cb3d592f4c4ed1d136 |
def check_system_consistency(self, system): <NEW_LINE> <INDENT> super().check_system_consistency(system) | Check if the system is in this alchemical state.
It raises a AlchemicalStateError if the system is not consistent
with the alchemical state.
Parameters
----------
system : openmm.System
The system to test.
Raises
------
AlchemicalStateError
If the system is not consistent with this state. | 625941cb91af0d3eaac9bae0 |
def compile(self): <NEW_LINE> <INDENT> with self: <NEW_LINE> <INDENT> work_dir = self.output_directory <NEW_LINE> sys.path.insert(0, os.path.abspath(os.path.dirname(work_dir))) <NEW_LINE> sys.path.insert(0, os.path.abspath(os.path.dirname(self.path))) <NEW_LINE> if self.import_builtins: <NEW_LINE> <INDENT> self._import... | Compile script in the specified working directory. | 625941cb283ffb24f3c559c9 |
def attach(self, tail, head): <NEW_LINE> <INDENT> from abjad.tools import documentationtools <NEW_LINE> prototype = ( documentationtools.GraphvizSubgraph, documentationtools.GraphvizNode, documentationtools.GraphvizField, ) <NEW_LINE> assert isinstance(tail, prototype) <NEW_LINE> assert isinstance(head, prototype) <NEW... | Attaches edge from `tail` to `head`.
| 625941cbd99f1b3c44c67656 |
def trim(self,start,end): <NEW_LINE> <INDENT> self.dna_str = trim(self.dna_str,start,end) | Given a start and an end index trim the quality score string attribute and keep the middle.
start and end are integers.
Input:
start : Integer
end : Integer
Output:
modify self.dna_str | 625941cb76e4537e8c35173a |
def test_future_question_and_past_question(self): <NEW_LINE> <INDENT> pass | Even if both past and future questions exist, only past questions
are displayed.
:return: | 625941cbbde94217f3682eb9 |
def follow(self, avatar, follow): <NEW_LINE> <INDENT> return self.write(dict(command='follow', avatar=avatar, follow=follow)) | subscribe to messages from other avatar
>>> conn = M2Kwetter(SERVER)
>>> r = conn.unreg('follower')
>>> r = conn.unreg('followee')
>>> conn.reg('follower','Joe')
'OK'
>>> conn.reg('followee','Jane')
'OK'
>>> conn.follow('follower','followee')
'OK'
>>> conn.info('follower')
'{ "avatar": "follower", "fullname": "Joe", "f... | 625941cb8c0ade5d55d3ea82 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.