code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def add_policy(patient_id, added_policy, time): <NEW_LINE> <INDENT> if type(added_policy) is str: <NEW_LINE> <INDENT> added_policy = json.loads(added_policy) <NEW_LINE> <DEDENT> elif type(added_policy) not in [list, dict]: <NEW_LINE> <INDENT> return type_error <NEW_LINE> <DEDENT> conn = psycopg2.connect(privacy_server)... | This function add added_policy into a patient existing privacy policy.
If the patient is not in the database, then create a new record with added_policy.
:param patient_id: the patient id
:param added_policy: the additional privacy policy that will be added
:param time: the time that the record is mo... | 625941f407d97122c4178eb0 |
def set_one(self, host_name, ip_address): <NEW_LINE> <INDENT> self.hosts[host_name] = ip_address | Set the given hostname to map to the given IP address | 625941f41b99ca400220b0c9 |
def test_get_account_trunk(self): <NEW_LINE> <INDENT> pass | Test case for get_account_trunk
Show details of an individual trunk. | 625941f438b623060ff0b402 |
def test_objstr_to_whereclause(self): <NEW_LINE> <INDENT> where_clause = objstr_to_whereclause('{"_id": 1234}') <NEW_LINE> self.assertTrue(isinstance(where_clause, dict)) <NEW_LINE> hit_exception = False <NEW_LINE> try: <NEW_LINE> <INDENT> objstr_to_whereclause('[]') <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <I... | Test the string object to ORM where clause parsing. | 625941f43539df3088e2e961 |
def setGroupLabel(self, text): <NEW_LINE> <INDENT> self.groupLabel.setText(text) | Sets the text to be shown above the group selectbox
text - the labels text | 625941f491af0d3eaac9c033 |
def auc(self, train=False, valid=False, xval=False): <NEW_LINE> <INDENT> return {model.model_id:model.auc(train, valid, xval) for model in self.models} | Get the AUC(s).
If all are False (default), then return the training metric value.
If more than one options is set to True, then return a dictionary of metrics where the keys are "train", "valid",
and "xval"
:param train: If train is True, then return the AUC value for the training data.
:param valid: If valid is True... | 625941f4a219f33f34628f76 |
def __init__(self, parent, window_id=-1, imageTransformViewList=None, **kwargs): <NEW_LINE> <INDENT> if imageTransformViewList is None: <NEW_LINE> <INDENT> imageTransformViewList = [] <NEW_LINE> <DEDENT> super(MosaicTransformPanel, self).__init__(parent, window_id, **kwargs) <NEW_LINE> state.currentMosaicConfig.AddOnMo... | Constructor | 625941f40383005118ecfbf5 |
def WriteLoopTest3(workerID): <NEW_LINE> <INDENT> nodes = PyDOOMS.getNumberOfNodes() <NEW_LINE> if (workerID == 0): <NEW_LINE> <INDENT> TestObject(0) <NEW_LINE> TestObject(1) <NEW_LINE> TestObject(2) <NEW_LINE> TestObject(3) <NEW_LINE> <DEDENT> PyDOOMS.barrier() <NEW_LINE> oldObj0Value = PyDOOMS.get(0).value <NEW_LINE>... | Test writing and reading to/from multiple shared object from each node | 625941f4460517430c394789 |
def __init__ (self, parent, message, caption, buttons, default=0, cancel=-1): <NEW_LINE> <INDENT> assert len (buttons) > 0 <NEW_LINE> assert default < len (buttons) <NEW_LINE> assert cancel < len (buttons) <NEW_LINE> wx.Dialog.__init__ (self, parent) <NEW_LINE> self.__default = default <NEW_LINE> self.__cancel = cancel... | parent - родитель диалога
message - сообщение, отображаемое в диалоге
caption - заголовок диалога
buttons - список строк. Каждая строка соответствует кнопке с соответствующей надписью
default - номер кнопки, выбранной по умолчанию
cancel - номер кнопки, срабатывающей при нажатии Esc | 625941f43617ad0b5ed6850c |
def condition_group_options(self): <NEW_LINE> <INDENT> if "no-groups" in self.options and self.options["no-groups"]: <NEW_LINE> <INDENT> self.options["groups"] = [] <NEW_LINE> if "exclude-groups" in self.options: <NEW_LINE> <INDENT> del self.options["exclude-groups"] <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> super... | Additional conditioning of the grouping options. (See options
:rst:dir:`automodapi:groups`, :rst:dir:`automodapi:exclude-groups`, and
:rst:dir:`automodapi:no-groups` for additional details.) | 625941f40a366e3fb873ee36 |
def _ShowATFAStatus(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.atft_manager.CheckDevice(self.atft_manager.atfa_dev) <NEW_LINE> <DEDENT> except DeviceNotFoundException: <NEW_LINE> <INDENT> self._SendAlertEvent(self.ALERT_NO_ATFA) <NEW_LINE> return <NEW_LINE> <DEDENT> if self._UpdateKeysLeftInATFA(): <NEW_L... | Show the attestation key status of the ATFA device.
| 625941f4507cdc57c6307300 |
def multiplication(self, uA, uB, t_nrm): <NEW_LINE> <INDENT> if len(uA[0]) > len(uB[0]): <NEW_LINE> <INDENT> uL = uA <NEW_LINE> uS= uB <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> uL= uB <NEW_LINE> uS= uA <NEW_LINE> <DEDENT> z = [] <NEW_LINE> zd = [] <NEW_LINE> zu = [] <NEW_LINE> for L in range(len(uL[0])): <NEW_LINE>... | Function realises uA * uB
:param uA: first multiplier (fuzzy number, for example: [[0.1, 0.2, 0.8], [2, 3, 4]])
:param uB: second multiplier (fuzzy number, for example: [[0.1, 0.2, 0.8], [2, 3, 4]])
:param t_nrm: T - norm, which we use
:return: result of multiplication (fuzzy number, for example: [[0.1, 0.2, 0.8], [2, ... | 625941f401c39578d7e75451 |
def on_disconnection(self, other): <NEW_LINE> <INDENT> self.attribute.unlock_widget() | Unlock the widget of the attribute
:param other: Other `Plug` disconnected from this one.
:type other: Plug | 625941f482261d6c526ababe |
def parse_all(self): <NEW_LINE> <INDENT> ID_line = "" <NEW_LINE> AC = [] <NEW_LINE> DR_line = "" <NEW_LINE> SY = [] <NEW_LINE> features = [] <NEW_LINE> CC = [] <NEW_LINE> SQ_line = "" <NEW_LINE> seq = [] <NEW_LINE> for i in self.record: <NEW_LINE> <INDENT> head = i[:2] <NEW_LINE> if head == 'ID': <NEW_LINE> <INDENT> ID... | Splits up the record into its parts and sends them to the appropriate method. | 625941f4097d151d1a22346b |
def hasCycle(self, head): <NEW_LINE> <INDENT> h1 = head <NEW_LINE> h2 = head <NEW_LINE> while h1 and h2 and h2.next: <NEW_LINE> <INDENT> h1 = h1.next <NEW_LINE> h2 = h2.next.next <NEW_LINE> if h1 == h2: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | :type head: ListNode
:rtype: bool | 625941f415baa723493c4590 |
def schemaFromString(data): <NEW_LINE> <INDENT> schema = Schema() <NEW_LINE> addSQLToSchema(schema, data) <NEW_LINE> return schema | Get a L{Schema}.
@param data: a C{str} containing SQL.
@return: a L{Schema} object with the contents of the given C{str} parsed
and added to it as L{Table} objects. | 625941f4ad47b63b2c50a595 |
def crtaj_glavni_kanal(self): <NEW_LINE> <INDENT> frejm = self.data[self.gKanal] <NEW_LINE> if type(frejm) == pd.core.frame.DataFrame: <NEW_LINE> <INDENT> x = list(frejm.index) <NEW_LINE> y = list(frejm[self.konfig.MIDLINE]) <NEW_LINE> logging.debug('crtanje glavnog kanala - midline') <NEW_LINE> self.crtaj_line(x, y, s... | crtanje podataka glavnog kanala. | 625941f4ad47b63b2c50a596 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, InlineResponse2011): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941f4bde94217f3683401 |
def demo(sess, net, im): <NEW_LINE> <INDENT> timer = Timer() <NEW_LINE> timer.tic() <NEW_LINE> scores, boxes = im_detect(sess, net, im) <NEW_LINE> timer.toc() <NEW_LINE> print('Detection took {:.3f}s for {:d} object proposals'.format(timer.total_time, boxes.shape[0])) <NEW_LINE> CONF_THRESH = 0.8 <NEW_LINE> NMS_THRESH ... | Detect object classes in an image using pre-computed object proposals. | 625941f430dc7b7665901f75 |
def calc_exp_wins(teams, schedule, week, reg_season): <NEW_LINE> <INDENT> df_remaining = schedule.query(f'matchupPeriodId > {week} & matchupPeriodId <= {reg_season}').reset_index(drop=True) <NEW_LINE> df_remaining['home_score_fit'] = df_remaining.apply( lambda x: teams[teams.get('team_id') == x.get('home_id')].get('sco... | Calculate expected wins for rest of season for each team
Use fitted normal distribution for each team, combine distributions
and calculate cdf(0) for probability to win
:param teams: data frame with teams and score profile
:param schedule: data frame with schedule data
:param week: current week
:param reg_season: week... | 625941f49b70327d1c4e13ee |
def test_empty(self): <NEW_LINE> <INDENT> empty_path = os.path.join(self._TEST_DATA_DIR, 'empty.json') <NEW_LINE> with pytest.raises(UnknownStatementError): <NEW_LINE> <INDENT> with open(empty_path, 'r') as f: <NEW_LINE> <INDENT> json2sql(f) | Raise on empty input - data/empty.json. | 625941f41b99ca400220b0ca |
def PI_grow(parameter, size): <NEW_LINE> <INDENT> depths = range(parameter.params['BNF_GRAMMAR'].min_ramp + 1, parameter.params['MAX_INIT_TREE_DEPTH']+1) <NEW_LINE> population = [] <NEW_LINE> if size < 2: <NEW_LINE> <INDENT> print("Error: population size too small for PI Grow initialisation.") <NEW_LINE> print("Returni... | Create a population of size using Position Independent Grow and return.
:param size: The size of the required population.
:return: A full population of individuals. | 625941f40fa83653e46575cd |
def perturb(self, distance): <NEW_LINE> <INDENT> def get_rand_vec(): <NEW_LINE> <INDENT> vector = np.random.randn(3) <NEW_LINE> vnorm = np.linalg.norm(vector) <NEW_LINE> return vector / vnorm * distance if vnorm != 0 else get_rand_vec() <NEW_LINE> <DEDENT> for i in range(len(self._sites)): <NEW_LINE> <INDENT> self.tran... | Performs a random perturbation of the sites in a structure to break
symmetries.
Args:
distance (float): Distance in angstroms by which to perturb each
site. | 625941f432920d7e50b287eb |
def __init__(self): <NEW_LINE> <INDENT> self.ActivityId = None <NEW_LINE> self.ComputeNodeId = None <NEW_LINE> self.ComputeNodeActivityType = None <NEW_LINE> self.EnvId = None <NEW_LINE> self.Cause = None <NEW_LINE> self.ActivityState = None <NEW_LINE> self.StateReason = None <NEW_LINE> self.StartTime = None <NEW_LINE>... | :param ActivityId: Activity ID
:type ActivityId: str
:param ComputeNodeId: Compute node ID
:type ComputeNodeId: str
:param ComputeNodeActivityType: Compute node activity type: creation or termination
:type ComputeNodeActivityType: str
:param EnvId: Compute environ... | 625941f44c3428357757c939 |
def return_json(self,category_id,key,category,return_request=False): <NEW_LINE> <INDENT> if category: <NEW_LINE> <INDENT> url = 'http://api.eia.gov/category/?api_key=YOUR_API_KEY_HERE&category_id=CATEGORY' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> url = 'http://api.eia.gov/series/?api_key=YOUR_API_KEY_HERE&series_i... | builds a url, sends a request, and builds either a dataframe, or a json respnse from the EIA
Keyword arguments:
category_id -- The appropriate id used to select EIA data. These can be found using the API query browse: https://www.eia.gov/opendata/qb.php?category=371
key -- Your individual api key issued by the... | 625941f471ff763f4b549cad |
def global_permissions(): <NEW_LINE> <INDENT> async def pred(ctx: commands.Context): <NEW_LINE> <INDENT> author = ctx.author <NEW_LINE> if await ctx.bot.is_owner(author): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if not await Shop().shop_is_global(): <NEW_LINE> <INDENT> permissions = ctx.channel.permissions_f... | Returns true if shop is global, otherwise checks if the
command was used by guild owner or guild administrator | 625941f423e79379d52eeb71 |
def totalCategories(): <NEW_LINE> <INDENT> CategoriesTotal = categoryDal.totalCategories() <NEW_LINE> return CategoriesTotal | Gets all details of all the categories in the database
:return CategoriesList: All the categories | 625941f4f548e778e58cdb96 |
@app.route('/', methods=['GET']) <NEW_LINE> def get_node_ui(): <NEW_LINE> <INDENT> return send_from_directory('ui', 'node.html') | Returns the node UI. | 625941f4de87d2750b8603b0 |
def checkForImages(self, startFrame, stopFrame, logger): <NEW_LINE> <INDENT> logger.info("Checking if all jpegs have been converted.") <NEW_LINE> jpegFolder = self.getJpegFolder() <NEW_LINE> imageFolder = self.getImageFolder() <NEW_LINE> orthoFolder = self.getOrthoFolder() <NEW_LINE> if not os.path.exists(jpegFolder): ... | Return true if all the images have been converted from jpeg. | 625941f44f6381625f115051 |
def active(self): <NEW_LINE> <INDENT> qs = self.get_queryset() <NEW_LINE> qs = qs.filter(is_published=True) <NEW_LINE> return qs | Return lives with number. | 625941f4be8e80087fb2124d |
def replace_namespaced_role(self, name, namespace, body, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async'): <NEW_LINE> <INDENT> return self.replace_namespaced_role_with_http_info(name, namespace, body, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) ... | replace_namespaced_role # noqa: E501
replace the specified Role # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_namespaced_role(name, namespace, body, async=True)
>>> result = thread.get()
:param: async bool
... | 625941f4baa26c4b54cb172e |
def result_from_api(endpoint, result_producer, retry = 0): <NEW_LINE> <INDENT> (resp, error) = net('get', endpoint) <NEW_LINE> if not error: <NEW_LINE> <INDENT> if __debug__: log(f'got result from {endpoint}') <NEW_LINE> return result_producer(resp) <NEW_LINE> <DEDENT> elif isinstance(error, NoContent): <NEW_LINE> <IND... | Do HTTP GET on "endpoint" & return results of calling result_producer. | 625941f460cbc95b062c6b5a |
def _repr_generic_point(self, v=None): <NEW_LINE> <INDENT> if v is None: <NEW_LINE> <INDENT> v = list(self.gens()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> v = list(v) <NEW_LINE> <DEDENT> splitv = self._factors(v) <NEW_LINE> return '(%s)' % (" , ".join((" : ".join(str(t) for t in P)) for P in splitv)) | Return a string representation of the generic point
on this product space.
If ``v`` is None, the representation of the generic point of
the product space is returned.
OUTPUT: String.
EXAMPLES::
sage: T = ProductProjectiveSpaces([1, 2, 1], QQ, 'x')
sage: T._repr_generic_point()
'(x0 : x1 , x2 : x3 : x4 ,... | 625941f4090684286d50f307 |
def _load_raw(years): <NEW_LINE> <INDENT> filename = "INN{}.csv".format(years) <NEW_LINE> path = os.path.join(Dirs.RAW_DIR, filename) <NEW_LINE> raw_data = pd.read_csv(path) <NEW_LINE> return raw_data | Loads the dataset in .csv format.
Arguments:
years {str} -- years where the data was collected.
Possible choices are:
2008-2014 are years used for training
2015-2016 are years used for testing
Returns:
raw_data -- The data as a pandas DataFrame | 625941f4b5575c28eb68e61c |
def pc_work_time_avg(self): <NEW_LINE> <INDENT> return _vocoder_swig.g721_decode_bs_sptr_pc_work_time_avg(self) | pc_work_time_avg(g721_decode_bs_sptr self) -> float | 625941f429b78933be1e5cbb |
def detect(env): <NEW_LINE> <INDENT> if 'Mkdocs_Combine_Exe' in env: <NEW_LINE> <INDENT> ret = env.Detect(env['Mkdocs_Combine_Exe']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret = env.Detect('mkdocscombine') <NEW_LINE> <DEDENT> if ret is None: <NEW_LINE> <INDENT> print("mkdocscombine not found") <NEW_LINE> <DEDENT... | Detect if mkdocscombine exe is detected on the system
or use user specified option | 625941f416aa5153ce362a8f |
def warn_deadlink(self, content, context): <NEW_LINE> <INDENT> links = [link.replace(context['mkdocs']['site_url'], "") for _, link in re.findall( r"\[([\w\W]+?)\]\(([\w\W]+?)\)", content, re.MULTILINE) if ((link.startswith( "https://") or link.startswith("http://")) and link.startswith(context['mkdocs']['site_url']) o... | Checks for dead links between pages | 625941f47b180e01f3dc4e06 |
def delete(self, item_id: str, shape_id: str, params: dict = None) -> None: <NEW_LINE> <INDENT> if params is None: <NEW_LINE> <INDENT> params = {} <NEW_LINE> <DEDENT> endpoint = self._build_url(f'{item_id}/shape/{shape_id}') <NEW_LINE> self.client.delete(endpoint, params=params) | Removes the specified shape.
:param item_id: The ID of the item.
:param shape_id: The ID of the shape.
:param params: Optional query parameters. | 625941f421bff66bcd684f63 |
def test_package_is_uploaded_404s(default_repo): <NEW_LINE> <INDENT> default_repo.session = pretend.stub( get=lambda url, headers: response_with(status_code=404) ) <NEW_LINE> package = pretend.stub(safe_name="fake", metadata=pretend.stub(version="2.12.0")) <NEW_LINE> assert default_repo.package_is_uploaded(package) is ... | Return False when the project API response status isn't 200. | 625941f4956e5f7376d71481 |
def _make_default_context(self): <NEW_LINE> <INDENT> return { 'model': model, 'session': model.Session, 'user': c.user, } | Creates a default context
:return: the default context | 625941f4e8904600ed9f254e |
def fourSumCount(self, A, B, C, D): <NEW_LINE> <INDENT> from collections import Counter <NEW_LINE> AB = Counter(a + b for a in A for b in B) <NEW_LINE> return sum(AB[-c - d] for c in C for d in D) | :type A: List[int]
:type B: List[int]
:type C: List[int]
:type D: List[int]
:rtype: int | 625941f4b57a9660fec33ea3 |
def __call__(self, code): <NEW_LINE> <INDENT> index = 0 <NEW_LINE> for token, text in self._lexer.get_tokens(code): <NEW_LINE> <INDENT> length = len(text) <NEW_LINE> char_format = self._get_format(token) <NEW_LINE> pygmentsHighlighter._setFormat(index, length, char_format) <NEW_LINE> index += length | makes this class callable, actually do the highlightning | 625941f4091ae3566866756a |
def make_binary(): <NEW_LINE> <INDENT> first = stellar.Star(-150, 0, 1990000000000000000000000000000, STAR_RADIUS, 0, 15000) <NEW_LINE> second = stellar.Star(150, 0, 1990000000000000000000000000000, STAR_RADIUS, 0, -15000) <NEW_LINE> return first, second | Creates a binary star system. The stars are identical, but with
opposite velocities and different positions.
make_binary() -> (stellar, stellar) | 625941f463f4b57ef000171d |
def test_peek(self): <NEW_LINE> <INDENT> self.assertRaises(IndexError, self.queue.peek) <NEW_LINE> self.queue.enqueue(self.item1) <NEW_LINE> self.assertEqual(self.queue.peek(), self.item1) <NEW_LINE> self.assertEqual(self.queue.peek(), self.item1) | test_peek
1) 'peek' returns first node item.
2) And it always should do same result
3) if empty queue, then error occur | 625941f4656771135c3ebe8d |
def calc_prob(predict_data, time_range): <NEW_LINE> <INDENT> prob = (1-tf.nn.softmax(abs(time_range-predict_data))) / time_range.shape[0] <NEW_LINE> return prob | calculate the probability distribution of the specific time range
:param predict_data: the data predicted by RNN model
:param time_range: the time window range of the probability (numpy array)
:return: independent probability distribution on the time_range, corresponding to the predicted data | 625941f47c178a314d6efa81 |
def predict(self, features): <NEW_LINE> <INDENT> features = np.column_stack((np.ones(features.shape[0]), features)) <NEW_LINE> predictions = np.array([]) <NEW_LINE> multiplied = np.array([]) <NEW_LINE> for i in range(features.shape[0]): <NEW_LINE> <INDENT> multiplied = np.append(multiplied, np.dot(features[i,:], self.w... | Given features, a 2D numpy array, use the trained model to predict target
classes. Call this after calling fit.
Args:
features (np.ndarray): 2D array containing real-valued inputs.
Returns:
predictions (np.ndarray): Output of saved model on features. | 625941f41f5feb6acb0c5160 |
@Pipe <NEW_LINE> def skip(qte: int): <NEW_LINE> <INDENT> def _(iterable): <NEW_LINE> <INDENT> i = qte <NEW_LINE> for item in iterable: <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> yield item <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> i -= 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return _ @ P | Skip qte elements in the given iterable, then yield others. | 625941f44a966d76dd55162d |
def object_by_id(self, id): <NEW_LINE> <INDENT> return self.root.object_by_id(id) | Get an object by ID.
:return: An object with the corresponding ID or none. | 625941f4442bda511e8bea25 |
def test_put_single_item_with_expiry_time(self): <NEW_LINE> <INDENT> expiry_date = timezone.now() + timedelta(minutes=5) <NEW_LINE> mommy.make(Item, id=5, name='Jacket') <NEW_LINE> data = { "id": 5, "name": "T-shirt", "price": 15, "expiry_time": expiry_date } <NEW_LINE> url = '/api/v1/items/5?expire_in=60' <NEW_LINE> s... | Test put a single eligable for expiry item | 625941f4287bf620b61d4076 |
def test_no_fallback(self): <NEW_LINE> <INDENT> storage = self.get_storage() <NEW_LINE> response = self.get_response() <NEW_LINE> self.get_session_storage(storage)._store = None <NEW_LINE> for i in range(5): <NEW_LINE> <INDENT> storage.add(constants.INFO, str(i) * 100) <NEW_LINE> <DEDENT> storage.update(response) <NEW_... | (1) A short number of messages whose data size doesn't exceed what is
allowed in a cookie will all be stored in the CookieBackend.
(2) If the CookieBackend can store all messages, the SessionBackend
won't be written to at all. | 625941f49f2886367277ae9e |
def plusOne(self, head): <NEW_LINE> <INDENT> c = self.dfs(head) <NEW_LINE> if c: <NEW_LINE> <INDENT> newHead = ListNode(c) <NEW_LINE> newHead.next = head <NEW_LINE> head = newHead <NEW_LINE> <DEDENT> return head | :type head: ListNode
:rtype: ListNode | 625941f4d58c6744b4258273 |
def create(self, docs, **kwargs): <NEW_LINE> <INDENT> service = get_resource_service('archive') <NEW_LINE> ids = [] <NEW_LINE> for doc in docs: <NEW_LINE> <INDENT> item = service.find_one(req=None, guid=doc['marked_item']) <NEW_LINE> if not item: <NEW_LINE> <INDENT> ids.append(None) <NEW_LINE> continue <NEW_LINE> <DEDE... | Toggle highlight status for given highlight and item. | 625941f4b5575c28eb68e61d |
def login(self, event=None): <NEW_LINE> <INDENT> start_location = self.location.get() <NEW_LINE> if start_location == "": <NEW_LINE> <INDENT> start_location = None <NEW_LINE> <DEDENT> api.spawn(self.parent.login_agent, self.first_name.get(), self.last_name.get(), self.password.get(), start_location) <NEW_LINE> self.par... | Logs in a pyogp agent | 625941f4d6c5a10208144666 |
def calc_msinlet_cal1phint_timestamp(port_timestamp_calint01, L0_dissgas_calint01, gas_mode_calint01, port_timestamp_calint01_mcu, ph_meter_calint01_mcu, inlet_temp_calint01_mcu, massp_rga_initial_mass, massp_rga_final_mass, massp_rga_steps_per_amu, calibration_table): <NEW_LINE> <INDENT> mass_table = rga_status_proces... | This is a wrapper function to calculate the MASSP timestamp while in Nafion mode. | 625941f4d4950a0f3b08c95d |
def validTicTacToe(self, board): <NEW_LINE> <INDENT> xnum, onum=0,0 <NEW_LINE> for i in range(3): <NEW_LINE> <INDENT> for j in range(3): <NEW_LINE> <INDENT> if board[i][j] == 'X': <NEW_LINE> <INDENT> xnum+=1 <NEW_LINE> <DEDENT> if board[i][j] == 'O': <NEW_LINE> <INDENT> onum+=1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if ... | :type board: List[str]
:rtype: bool | 625941f416aa5153ce362a90 |
def progress(self, current, expected): <NEW_LINE> <INDENT> pass | Called each cycle of the fit, reporting the current and the
expected amount of work. The meaning of these values is
optimizer dependent, but they can be converted into a percent
complete using (100*current)//expected.
Progress is updated each iteration of the fit, whatever that
means for the particular optimization ... | 625941f499fddb7c1c9de9a4 |
def plot_quantile_returns_violin(self, demeaned=False, group_adjust=False, ylim_percentiles=(1, 99)): <NEW_LINE> <INDENT> mean_return_by_date = self.calc_mean_return_by_quantile( by_date=True, by_group=False, demeaned=demeaned, group_adjust=group_adjust )[0].apply(rate_of_return, axis=0) <NEW_LINE> pl.plot_quantile_ret... | 画各分位数收益分布图
参数:
demeaned:
- True: 使用超额收益计算累积收益 (基准收益被认为是每日所有股票收益按照weight列中权重加权的均值)
- False: 不使用超额收益
group_adjust:
- True: 使用行业中性化后的收益计算累积收益
(行业收益被认为是每日各个行业股票收益按照weight列中权重加权的均值)
- False: 不使用行业中性化后的收益
plot_quantile_returns_violin: 有效收益分位数(单位为百分之). 画图时y轴的范围为有效收益的最大/最小值.
例如 (1, 99) 代表... | 625941f456ac1b37e62647d9 |
def get_meta_data(markup): <NEW_LINE> <INDENT> data = str(markup).split('setContactFormData(')[1].split(');')[0] <NEW_LINE> data = json.loads(data) <NEW_LINE> return data | Parse meta data
:param markup: raw html
:return: dictionary with data
:rtype: dict | 625941f44f88993c3716c677 |
def odd(self, printNumber): <NEW_LINE> <INDENT> for i in range((self.n+1)//2): <NEW_LINE> <INDENT> self.locks[1].acquire() <NEW_LINE> printNumber(2*i+1) <NEW_LINE> self.locks[0].release() | :type printNumber: method
:rtype: void | 625941f49f2886367277ae9f |
def wait(self, timeout=15): <NEW_LINE> <INDENT> Probe(timeout=timeout, fnc=self.get_phase, expected_retval=PodPhase.RUNNING).run() | block until pod is not running, raises an exc ProbeTimeout if timeout is reached
:param timeout: int or float (seconds), time to wait for pod to run
:return: None | 625941f47d847024c06be8d8 |
def home_list_page(request): <NEW_LINE> <INDENT> fruits = Goods.objects.get_goods_by_type(goods_type_id=FRUIT, limit=4) <NEW_LINE> fruits_new = Goods.objects.get_goods_by_type(goods_type_id=FRUIT, limit=3, sort='new') <NEW_LINE> seafood = Goods.objects.get_goods_by_type(goods_type_id=SEAFOOD, limit=4) <NEW_LINE> seafoo... | 显示首页 | 625941f4e76e3b2f99f3ae18 |
def read_yaml(self, filepath): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(filepath) as fin: <NEW_LINE> <INDENT> data = yaml.load(fin, Loader=yaml.BaseLoader) <NEW_LINE> <DEDENT> <DEDENT> except yaml.YAMLError as exc: <NEW_LINE> <INDENT> print ("Failed to read {}".format(filepath)) <NEW_LINE> raise(exc) <NEW... | Read the YAML file at specified location
return the yaml data on success
raise an exception upon failure reading/load the file | 625941f426068e7796caf2ff |
def memmap_peripheral_memory(memmap, depth=128): <NEW_LINE> <INDENT> width = 32 <NEW_LINE> mem = [Signal(intbv(0)[width:]) for _ in range(depth)] <NEW_LINE> memspace = MemorySpace() <NEW_LINE> memmap.add(memspace) <NEW_LINE> per_addr = memspace.base_address <NEW_LINE> print("memmap_peripheral_memory base address {:08X}... | Example mapping a memory-mapped (csr) bus to an internal memory
buffer.
Ports:
:param memmap:
:return:
Parameters: | 625941f407d97122c4178eb1 |
def sectorize(position): <NEW_LINE> <INDENT> x, y, z = normalize(position) <NEW_LINE> x, y, z = x // SECTOR_SIZE, y // SECTOR_SIZE, z // SECTOR_SIZE <NEW_LINE> return (x, 0, z) | Returns a tuple representing the sector for the given block position | 625941f4d18da76e23532af5 |
def get_sharding_info(self): <NEW_LINE> <INDENT> return self._from_recon_cache(["sharding_stats", "sharding_time", "sharding_last"], self.container_recon_cache) | get sharding info | 625941f4dc8b845886cb5b4e |
def add_eid_to_group(group): <NEW_LINE> <INDENT> if "eid" not in group.keys(): <NEW_LINE> <INDENT> run = group["run"][:].flatten() <NEW_LINE> subrun = group["subrun"][:].flatten() <NEW_LINE> cycle = group["cycle"][:].flatten() <NEW_LINE> batch = group["batch"][:].flatten() <NEW_LINE> evt = group["evt"][:].flatten() <NE... | Add and 'eid' column to the given group.
:param group: an h5.Group object
:return: None | 625941f4aad79263cf391062 |
def test_collect_enter(self): <NEW_LINE> <INDENT> with self.assertRaises(Exception): <NEW_LINE> <INDENT> for obj in self.missing_default: <NEW_LINE> <INDENT> collect_argument(obj, lambda x: "") | Tests to see if defaualt is taken when enter is used | 625941f4379a373c97cfb15e |
def notify_caps(self, pad, *args): <NEW_LINE> <INDENT> self.source.caps = True <NEW_LINE> info = pad.get_current_caps().get_structure(0) <NEW_LINE> self.source._duration = pad.get_peer().query_duration(Gst.Format.TIME).duration / Gst.SECOND <NEW_LINE> channels = info.get_int('channels')[1] <NEW_LINE> sample_rate = info... | notify::caps callback | 625941f407f4c71912b11a9c |
def get_transaction(self, transaction_id): <NEW_LINE> <INDENT> url = self.base_url + 'transactions/' + str(transaction_id) <NEW_LINE> self.session.headers.update(self.sign(url)) <NEW_LINE> resp = self.session.get(url) <NEW_LINE> return resp.json() | Retrieve a transaction's details
params:
transaction_id: Unique transaction identifier
returns:
json response | 625941f430c21e258bdfaabc |
def write_excel(self, interface, filename): <NEW_LINE> <INDENT> wt = WriteExcel(filename) <NEW_LINE> try: <NEW_LINE> <INDENT> wt.write(interface['row_num'], 1, interface['id']) <NEW_LINE> wt.write(interface['row_num'], 2, interface['tags']) <NEW_LINE> wt.write(interface['row_num'], 3, interface['name']) <NEW_LINE> wt.w... | 把dict中的值写入对应的excel行中 | 625941f4009cb60464c639c4 |
def isOkay(self, center): <NEW_LINE> <INDENT> matrix = [[0, 0], [0, 1], [0, -1], [-1, 0], [-1, 1], [-1, -1], [1, 0], [1, 1], [1, -1]] <NEW_LINE> for pos in matrix: <NEW_LINE> <INDENT> if center[0] + pos[0] < 0 or center[0] + pos[0] >= self.MAX_ROW or center[1] + pos[1] < 0 or center[1] + pos[1] >= self.... | not out of map or is obstacle | 625941f40fa83653e46575ce |
def update_state(self, *args, **kwargs): <NEW_LINE> <INDENT> self(*args, **kwargs) | Update this model's state as if self.__call__ is called.
Unlike __call__, stateless objects may do nothing. | 625941f43539df3088e2e963 |
def updateService(self, tenantId,serviceId,payload): <NEW_LINE> <INDENT> uri = "/v1/tenants/" + str(tenantId) + "/services/"+str(serviceId) <NEW_LINE> response = self.client.put(uri,payload) <NEW_LINE> return response | 625941f456b00c62f0f14c75 | |
def get_exp(self): <NEW_LINE> <INDENT> return self.experimentInfo.value() | Get set experiment info number | 625941f4be383301e01b5a91 |
def mean(self, S): <NEW_LINE> <INDENT> return t_dualFnc.gaussMean(S) | Return the upper-level policy mean given the context features.
The mean of the distribution is N(w | a + As, sigma)
Parameters
----------
S: numpy.ndarray, shape (n_samples, n_context_features)
Context features
Returns
-------
W: numpy.ndarray, shape (n_samples, n_lower_policy_weights)
Distribution mean for... | 625941f4c432627299f05262 |
def transform(self, X, y=None): <NEW_LINE> <INDENT> raise ValueError( "%s.transform not implemented! This imputation algorithm likely " "doesn't support inductive mode. Only %s.fit_transform is " "supported at this time." % ( self.__class__.__name__, self.__class__.__name__)) | Transform input `X`.
Note: all imputations should have a `fit_transform` method,
but only some (like IterativeImputer) also support inductive mode
using `fit` or `fit_transform` on `X_train` and then `transform`
on new `X_test`. | 625941f4a05bb46b383ece33 |
def get_batch_test(self,data_length,start_index,data): <NEW_LINE> <INDENT> train_one_batch = np.zeros((data_length, self.time_sequence,1+self.positive_lab_size+self.negative_lab_size,self.item_size)) <NEW_LINE> train_one_batch_mortality = np.zeros((data_length,2,2)) <NEW_LINE> one_batch_logit = np.zeros((data_length,2)... | get training batch data | 625941f40a366e3fb873ee38 |
def write_fits(ccd, full_path, combined=False, parent_file=None, overwrite=True): <NEW_LINE> <INDENT> assert isinstance(ccd, CCDData) <NEW_LINE> if not os.path.isdir(os.path.dirname(full_path)): <NEW_LINE> <INDENT> log.error("Directory {} does not exist. Creating it right now." "".format(os.path.dirname(full_path))) <N... | Write fits while adding information to the header.
This is a wrapper for allowing to save files while being able to add
information into the header. Mostly for historical reasons.
Args:
ccd (CCDData) A :class:`~astropy.nddata.CCDData` instance to be saved
to fits.
full_path (str): Full path of file.
c... | 625941f4d7e4931a7ee9e537 |
def search(values): <NEW_LINE> <INDENT> values = reduce_puzzle(values) <NEW_LINE> if values == False: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if all(len(values[box])==1 for box in values): <NEW_LINE> <INDENT> return values <NEW_LINE> <DEDENT> n,b = min((len(values[box]),box) for box in values if len(values... | Using depth-first search and propagation, create a search tree and solve the sudoku. | 625941f4046cf37aa974d358 |
def lengthOfLIS(self, nums): <NEW_LINE> <INDENT> if len(nums) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> n = len(nums) <NEW_LINE> f = [nums[0]] <NEW_LINE> for i in range(1, n): <NEW_LINE> <INDENT> if nums[i] > f[-1]: <NEW_LINE> <INDENT> f.append(nums[i]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> index =... | :type nums: List[int]
:rtype: int | 625941f482261d6c526abac0 |
def test_cmp_missing_reference(self): <NEW_LINE> <INDENT> self.assertEqual(Md5Checker.MD5_ERROR, Md5Checker.md5cmp_files(self.example_dir.path('missing.txt'), self.example_dir.path('spider.txt'))) | Md5Checker.md5cmp_files with missing reference file
| 625941f497e22403b379d5b3 |
def test_delete_firewall_with_rule_list_info_true(self): <NEW_LINE> <INDENT> self.ev.id = fw_const.FIREWALL_DELETE_EVENT <NEW_LINE> self._test_handle_event() | Implements test case for delete firewall method
of firewall agent's event handler with firewall rules.
Returns: none | 625941f47d847024c06be8d9 |
def isPalindrome(self, x): <NEW_LINE> <INDENT> if x >= 0 and str(x) == str(x)[::-1]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | :type x: int
:rtype: bool | 625941f4d18da76e23532af6 |
@njit <NEW_LINE> def psi(t): <NEW_LINE> <INDENT> return 2./np.sqrt(3.*np.sqrt(np.pi)) * (1.-t**2) * np.exp(-(t**2)/2) | Mother wavelet function | 625941f4bde94217f3683402 |
def char_read_handle(self, uuid): <NEW_LINE> <INDENT> raise NotImplementedError() | Reads a Characteristic by handle.
handle -- handle of Characteristic to read.
Returns a bytearray containing the characteristic value on success.
Example:
my_ble_device.char_read_handle(5) | 625941f48c3a8732951589da |
def multipart_push(self, upload_id, url, part_number, chunk_size, data, md5=None): <NEW_LINE> <INDENT> path = self.base_path / url <NEW_LINE> assert path.is_file(), f"{self}: multipart upload file {path} does not exist." <NEW_LINE> with path.open("r+b") as stream: <NEW_LINE> <INDENT> stream.seek((part_number - 1) * chu... | Upload a single part of multipart upload. | 625941f426238365f5f0f48e |
def which(cmd): <NEW_LINE> <INDENT> found_path = None <NEW_LINE> paths = os.environ.get("PATH").split(":") <NEW_LINE> for path in paths: <NEW_LINE> <INDENT> if path in EMPTY_VALUES: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if cmd in os.listdir(path): <NEW_LINE> <INDENT> found_path = os.path.join(path, cmd) <NEW... | Similar to the 'which' command in *nix, this function searches the system PATH to see if the provided 'cmd' is
found. If so, it returns the absolute path. | 625941f49b70327d1c4e13f0 |
def stop(self): <NEW_LINE> <INDENT> self._stop_event.set() <NEW_LINE> if self.__writer_thread is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.__writer_thread.join(5) <NEW_LINE> <DEDENT> except (KeyboardInterrupt, SystemExit): <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> except BaseException: <NEW_LINE> ... | Stop the writer thread | 625941f41b99ca400220b0cc |
def test_get_action_text_with_verb_action(self): <NEW_LINE> <INDENT> self.action = Action.objects.create( actor=self.user, verb='made friends with', action=self.user2, timestamp=timezone.now() - timedelta(days=2) ) <NEW_LINE> expected = 'test_bob made friends with test_gary 2 days ago' <NEW_LINE> result = get_action_te... | Tests get_action_text() with a verb and action, that the text output
is correct. | 625941f407f4c71912b11a9d |
def SearchDataAdapter(results, format): <NEW_LINE> <INDENT> if results and results['response'] and results['response']['docs']: <NEW_LINE> <INDENT> search_data = results['response']['docs'] <NEW_LINE> order = search_data[0].keys() <NEW_LINE> rows = [order] <NEW_LINE> for data in search_data: <NEW_LINE> <INDENT> row = [... | SearchDataAdapter(results, format, db) -> 2D array of data.
First line should be the headers. | 625941f4f9cc0f698b140c0d |
def entities(self): <NEW_LINE> <INDENT> code, vals = self._get('/entities') <NEW_LINE> return (Entity(self, v) for v in vals) | Returns a generator of all entities in the dataset | 625941f44428ac0f6e5bae10 |
def move_to_games(self, specific_donor=None): <NEW_LINE> <INDENT> if specific_donor is None: <NEW_LINE> <INDENT> donor_id = self.get_donor_title_id(self.selected_donor) <NEW_LINE> game_using = self.get_donor_used_by(self.selected_donor) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> donor_id = self.get_donor_title_id(sp... | Moves the current game being used by the donor to the games storage location
:param specific_donor:
:return: | 625941f40fa83653e46575cf |
@pytest.mark.skip("Failing") <NEW_LINE> def test_montecarlo1(): <NEW_LINE> <INDENT> my_cards = [['3H', '3S']] <NEW_LINE> cards_on_table = ['8S', '4S', 'QH', '8C', '4H'] <NEW_LINE> expected_results = 40.2 <NEW_LINE> players = 2 <NEW_LINE> _runner(my_cards, cards_on_table, players, expected_results) | Montecarlo test | 625941f4bf627c535bc137e7 |
def tensorbasis(n, d=None, get_locality=False): <NEW_LINE> <INDENT> if d == None: <NEW_LINE> <INDENT> dim = n <NEW_LINE> n = len(dim) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dim = ones(n, int) * d <NEW_LINE> <DEDENT> dim = tuple(dim) <NEW_LINE> if dim in tensorbasis_cache: <NEW_LINE> <INDENT> if get_locality: <NE... | Hermitian tensor-product basis for End(H).
Returns a Hermitian basis for linear operators on the Hilbert space H
which shares H's tensor product structure. The basis elements are tensor products
of Gell-Mann matrices (which in the case of qubits are equal to Pauli matrices).
The basis elements are normalized such that... | 625941f460cbc95b062c6b5b |
def __init__(self, lat=None, lng=None): <NEW_LINE> <INDENT> self._lat = None <NEW_LINE> self._lng = None <NEW_LINE> self.discriminator = None <NEW_LINE> if lat is not None: <NEW_LINE> <INDENT> self.lat = lat <NEW_LINE> <DEDENT> if lng is not None: <NEW_LINE> <INDENT> self.lng = lng | GeocodingPoint - a model defined in Swagger | 625941f44c3428357757c93b |
def delete_snapshot(self, snapshot): <NEW_LINE> <INDENT> raise NotImplementedError() | Deletes a snapshot. | 625941f4e76e3b2f99f3ae19 |
def save_to_file(generator_ad_archives, args, is_verbose=False): <NEW_LINE> <INDENT> if len(args) != 1: <NEW_LINE> <INDENT> raise Exception("save action requires exact 1 param: output file") <NEW_LINE> <DEDENT> with open(args[0], "w+") as file: <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for ad_archives in generator_ad_ar... | Save all retrieved ad_archives to the file; each ad_archive will be
stored in JSON format in a single line; | 625941f4ec188e330fd5ada9 |
def is_photometric_quantity(argument): <NEW_LINE> <INDENT> if isinstance(argument, Quantity): <NEW_LINE> <INDENT> number = argument.value <NEW_LINE> unit = argument.unit <NEW_LINE> return is_photometric_unit(unit) <NEW_LINE> <DEDENT> elif types.is_string_type(argument): <NEW_LINE> <INDENT> number, units = split_value_u... | This function ...
:param argument:
:return: | 625941f44d74a7450ccd47dd |
def pop_result(self, key): <NEW_LINE> <INDENT> self.pending_callbacks.remove(key) <NEW_LINE> return self.results.pop(key) | Returns the result for ``key`` and unregisters it. | 625941f4379a373c97cfb15f |
def get_indices(inventory, item_name, starts_with=False): <NEW_LINE> <INDENT> indices = [] <NEW_LINE> for i, item in enumerate(inventory): <NEW_LINE> <INDENT> if starts_with: <NEW_LINE> <INDENT> if item.name.startswith(item_name): <NEW_LINE> <INDENT> indices.append(i) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDE... | Gets all of the indices of items in inventory
:param inventory: Blender collection property instance
:type inventory: bpy.types.CollectionProperty
:param item_name: name of the item you are searching for
:type item_name: str
:param starts_with: use startswith function for name string comparsion
:type starts_with: boo... | 625941f4099cdd3c635f1270 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.