code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def get_q_value(self, state, action): <NEW_LINE> <INDENT> x = (tuple(state), action) <NEW_LINE> if x in self.q: <NEW_LINE> <INDENT> return self.q[(tuple(state), action)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 | Return the Q-value for the state `state` and the action `action`.
If no Q-value exists yet in `self.q`, return 0. | 625941ce566aa707497f46a0 |
def compare_objects(obj1, obj2, ignore_fields): <NEW_LINE> <INDENT> differences = [] <NEW_LINE> d_obj1 = obj1.__dict__ <NEW_LINE> d_obj2 = obj2.__dict__ <NEW_LINE> for field, new in d_obj1.items(): <NEW_LINE> <INDENT> if field in ignore_fields: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> old = d_obj2[field] <NEW_L... | Compares two objects.
@param ignore_fields Attributes of those objects to not compare
@return Array of tuple (field, new, old) where field is the name
of a field which has changed, new is current value, and
old is previous value. | 625941ce627d3e7fe0d68f88 |
def model_fit(self): <NEW_LINE> <INDENT> algo = SVD(n_factors=self.n_factors, reg_all=self.reg_all) <NEW_LINE> print("best performance of SVD when using parameters n_factors:" + str(self.n_factors) + " and regularizer:" + str(self.reg_all)) <NEW_LINE> print() <NEW_LINE> trainset = self.trainset.build_full_trainset() <N... | train the SVD use the best parameter
:return: | 625941ceac7a0e7691ed4204 |
def __init__(self, csca: CscaCertificate): <NEW_LINE> <INDENT> self.serializeCSCA(csca) <NEW_LINE> self.issuer = csca.issuer.human_friendly <NEW_LINE> self.fingerprint = csca.fingerprint <NEW_LINE> self.subject = csca.subject.human_friendly <NEW_LINE> self.subjectKey = csca.subjectKey <NEW_LINE> self.auth... | Initialization class with serialization of DSC | 625941ce07f4c71912b115ba |
def product(self, x, y): <NEW_LINE> <INDENT> return self((x.value * y.value) % self.n) | Return the product of two elements `x` and `y` of the monoid, as
per :meth:`Semigroups.ParentMethods.product`.
EXAMPLES::
sage: M = FiniteMonoids().example()
sage: M.product(M(3), M(5))
3 | 625941ce0c0af96317bb831f |
def searchAgent(self, AAD): <NEW_LINE> <INDENT> msg = ACLMessage.ACLMessage() <NEW_LINE> template = Behaviour.ACLTemplate() <NEW_LINE> template.setConversationId(msg.getConversationId()) <NEW_LINE> r = str(uuid.uuid4()).replace("-", "") <NEW_LINE> msg.setReplyWith(r) <NEW_LINE> template.setInReplyTo(r) <NEW_LINE> t = B... | searches an agent in the AMS
the search template is an AmsAgentDescription class | 625941ce85dfad0860c3af93 |
def _pair_property_accessors(self, node): <NEW_LINE> <INDENT> for prop in node.properties: <NEW_LINE> <INDENT> if not prop.introspectable: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if prop.setter is None: <NEW_LINE> <INDENT> normalized_name = prop.name.replace('-', '_') <NEW_LINE> if prop.writable and not prop.c... | Look for accessor methods for class properties | 625941ce0fa83653e46570f2 |
@contextmanager <NEW_LINE> def build_resources( resources: Dict[str, Any], instance: Optional[DagsterInstance] = None, resource_config: Optional[Dict[str, Any]] = None, pipeline_run: Optional[PipelineRun] = None, log_manager: Optional[DagsterLogManager] = None, ) -> Generator[Resources, None, None]: <NEW_LINE> <INDENT>... | Context manager that yields resources using provided resource definitions and run config.
This API allows for using resources in an independent context. Resources will be initialized
with the provided run config, and optionally, pipeline_run. The resulting resources will be
yielded on a dictionary keyed identically to... | 625941ce63b5f9789fde721d |
def _new_sample(self, sink): <NEW_LINE> <INDENT> if self.running: <NEW_LINE> <INDENT> buf = sink.emit('pull-sample').get_buffer() <NEW_LINE> self.queue.put(str(buf.extract_dup(0, buf.get_size()))) <NEW_LINE> <DEDENT> return Gst.FlowReturn.OK | The callback for appsink's "new-sample" signal.
| 625941ce3d592f4c4ed1d1a5 |
def get_list(self, mutagen_file): <NEW_LINE> <INDENT> return [self.deserialize(item) for item in self.fetch(mutagen_file)] | Get a list of all values for the field using this style.
| 625941ce099cdd3c635f0d93 |
def process_dag(controller,decider): <NEW_LINE> <INDENT> log.debug("process DAG by submitting nodes") <NEW_LINE> for nodeobj in controller.submittable_nodes(): <NEW_LINE> <INDENT> do_submit = decider.send((nodeobj,controller)) <NEW_LINE> if do_submit: <NEW_LINE> <INDENT> controller.submit_nodes([nodeobj]) | main loop to go through nodes in the DAG and submit the onces that are submittable | 625941cede87d2750b85fecb |
def renderNetwork(self): <NEW_LINE> <INDENT> li = self.scaleCombo.GetSelection() <NEW_LINE> ti = self.thetaCombo.GetSelection() <NEW_LINE> norm = [False, True, True, True] <NEW_LINE> fa = [0, ti, ti, 0] <NEW_LINE> maxGabor = self.network.levels[1].getMaxLayerValue() <NEW_LINE> maxLevel3 = self.network.levels[3].getMaxL... | Render the last processed state of the network using the current
UI visualization settings to choose which scales/angle to view. | 625941ce377c676e912722e0 |
def populate_existing_upgrades(sender, yes_i_know=False, drop=True, **kwargs): <NEW_LINE> <INDENT> from .engine import InvenioUpgrader <NEW_LINE> iu = InvenioUpgrader() <NEW_LINE> map(iu.register_success, iu._load_upgrades().values()) | Populate existing upgrades. | 625941cea05bb46b383ec959 |
def lang(self, widget): <NEW_LINE> <INDENT> if self.fr.get_active(): <NEW_LINE> <INDENT> LangueGui.status = ui_fr <NEW_LINE> self.destroy() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LangueGui.status = ui_an <NEW_LINE> self.destroy() | :param widget: Button clicked
:return: ui_an or ui_fr | 625941ce0fa83653e46570f3 |
def load_data(path="./data/cora/", dataset="cora"): <NEW_LINE> <INDENT> print('Loading {} dataset...'.format(dataset)) <NEW_LINE> idx_features_labels = np.genfromtxt("{}{}.content".format(path, dataset), dtype=np.dtype(str)) <NEW_LINE> features = sp.csr_matrix(idx_features_labels[:, 1:-1], dtype=np.float32) <NEW_LINE> ... | Load citation network dataset (cora only for now) | 625941cef8510a7c17cf9833 |
def nearbyAttractions(properties): <NEW_LINE> <INDENT> print("Preparing Table Containing Nearby Attractions...") <NEW_LINE> url = "https://tripadvisor1.p.rapidapi.com/attractions/list-by-latlng" <NEW_LINE> headers = { 'x-rapidapi-host': "tripadvisor1.p.rapidapi.com", 'x-rapidapi-key': "e3bf3719c0msh2279903cd2d3765p1c3... | Parameters
----------
properties : DataFrame
Returns
-------
Printed output of lat/long
Table of Attraction Results | 625941ce3317a56b86939d8f |
def add(self, piece): <NEW_LINE> <INDENT> self.active_pieces.append(piece) | Add a piece. | 625941cef7d966606f6aa13c |
def reboot(host, username, password, timeout=300, mount_lib=True): <NEW_LINE> <INDENT> if not host: <NEW_LINE> <INDENT> logger.error("Host name is required, provide with 'host' keyword") <NEW_LINE> return None <NEW_LINE> <DEDENT> last_system_boot_time = get_last_system_boot_time(host=host, username=username, password=p... | Reboot a given host
@params:
- host: host to be rebooted
- username: username to connect to host
- password: password to access to remote host
- pkey_filename: a private key filename to authenticate with
If neither password of private key provided,
Attempts to authenticate with all file in <use... | 625941ce2c8b7c6e89b358f8 |
def __init__(self): <NEW_LINE> <INDENT> self.TxnReturnCode = None <NEW_LINE> self.TxnReturnMsg = None <NEW_LINE> self.CnsmrSeqNo = None <NEW_LINE> self.FrontSeqNo = None <NEW_LINE> self.ReservedMsgOne = None <NEW_LINE> self.ReservedMsgTwo = None <NEW_LINE> self.RequestId = None | :param TxnReturnCode: String(20),返回码
:type TxnReturnCode: str
:param TxnReturnMsg: String(100),返回信息
:type TxnReturnMsg: str
:param CnsmrSeqNo: String(22),交易流水号
:type CnsmrSeqNo: str
:param FrontSeqNo: STRING(52),前置流水号
注意:此字段可能返回 null,表示取不到有效值。
:type FrontS... | 625941cecc0a2c11143dcfc8 |
def update_olog_id(logid, text, attachments, verbose=True): <NEW_LINE> <INDENT> olog_client = SimpleOlogClient() <NEW_LINE> client = OlogClient() <NEW_LINE> url = client._url <NEW_LINE> old_text = olog_client.find(id=logid)[0]['text'] <NEW_LINE> upd = LogEntry(text=f'{old_text}\n{text}', attachments=attachments, logboo... | Update olog book logid entry with text and attachments files.
Parameters
----------
logid : integer
the log entry id
text : str
the text to update, will add this text to the old text
attachments : ???
add new attachment files
Example
-------
filename1 = ('/XF11ID/analysis/2016_2/yuzhang/Results/August/af8... | 625941ce57b8e32f524835d3 |
def propagate(self): <NEW_LINE> <INDENT> for p in self.get_descendants(): <NEW_LINE> <INDENT> p.online = self.online <NEW_LINE> p.save() | Will set restricted and groups on all descendant pages like <page>
| 625941cea8370b77170529d7 |
def _initMap(self, Map): <NEW_LINE> <INDENT> if not grass.find_program('g.region', '--help'): <NEW_LINE> <INDENT> sys.exit(_("GRASS module '%s' not found. Unable to start map " "display window.") % 'g.region') <NEW_LINE> <DEDENT> Debug.msg(2, "MapFrame._initMap():") <NEW_LINE> Map.ChangeMapSize(self.GetClientSize()) <N... | Initialize map display, set dimensions and map region
| 625941ce23e79379d52ee69c |
def commit(self) -> None: <NEW_LINE> <INDENT> return self.__conn.commit() | PostgreSQLデータベースにクエリをコミット | 625941ce711fe17d825424a3 |
def remove(units, polymer): <NEW_LINE> <INDENT> return ''.join([u for u in polymer if u not in units]) | Remove all instances of ``units`` from polymer. | 625941ced268445f265b4fa6 |
def is_offer_element_valid(self, offer_html): <NEW_LINE> <INDENT> return True | Overriding of this method is not required. This methods check if given html is an valid offer, by default
all offers are valid.
:param offer_html: the soup objects that consists the offer html
:return: | 625941ce5510c4643540f51c |
def detruire_objet(self, conteneur): <NEW_LINE> <INDENT> if hasattr(conteneur, "potion") and conteneur.potion: <NEW_LINE> <INDENT> objet = conteneur.potion <NEW_LINE> if objet.unique and objet.e_existe: <NEW_LINE> <INDENT> importeur.objet.essayer_supprimer_objet(objet) | Détruit l'objet passé en paramètre.
On va détruire tout ce qu'il contient. | 625941ced486a94d0b98e27d |
def test8MissingKyes(self): <NEW_LINE> <INDENT> self.failUnlessEqual(ProbeFormatRenderer(stream=self.wr).render({'a':1}), 3, 'Should have exited with 3 on missing mandatory keys.') | Mandatory keys missing. | 625941ce3317a56b86939d90 |
def read_word_list(): <NEW_LINE> <INDENT> with open(setting.VOCAB_PATH, 'r') as f: <NEW_LINE> <INDENT> word_list = [word for word in f.read().decode('utf8').strip().split('\n')] <NEW_LINE> <DEDENT> return word_list | 从文件读取词汇表
:return: 词汇列表 | 625941ce8c0ade5d55d3eaf3 |
def integrate(f: Callable[[T, float], DT], y0: T, update: Callable[[T, DT, float], T], t0=0., t_max=1., dt=.001, t=None, method='rk4'): <NEW_LINE> <INDENT> if method == 'euler': <NEW_LINE> <INDENT> step = _step_euler <NEW_LINE> <DEDENT> elif method == 'midpoint': <NEW_LINE> <INDENT> step = _step_midpoint <NEW_LINE> <DE... | Numerically solve ordinary differential equations (ODEs) of the form :math:`y'(t) = f(y, t)`, with
initial conditions :math:`y(0) = y_0`.
Parameters
----------
f : (T, float) -> DT
Derivative: :math:`f(y, t) = y'(t)`
y0 : T
Initial conditions: :math:`y_0 = y(0)`
update : (T, DT, float) -> T
Function which ... | 625941cef8510a7c17cf9834 |
def base58_check_decode(s, version): <NEW_LINE> <INDENT> n = 0 <NEW_LINE> for c in s: <NEW_LINE> <INDENT> n *= 58 <NEW_LINE> if c not in b58_digits: <NEW_LINE> <INDENT> raise exceptions.InvalidBase58Error('Not a valid Base58 character: ‘{}’'.format(c)) <NEW_LINE> <DEDENT> digit = b58_digits.index(c) <NEW_LINE> n += dig... | Decode from base58. | 625941ce8a349b6b435e82ac |
def mesh(self, gsimax=10, dgsi=0.01, etae=8, deta1=0.01, stretch=1.12): <NEW_LINE> <INDENT> self.dgsi = dgsi <NEW_LINE> self.etae = etae <NEW_LINE> self.stretch = stretch <NEW_LINE> if stretch < 1.0001: <NEW_LINE> <INDENT> etamax = etae / deta1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> etamax = np.log(1.0 + (stretc... | Mesh generation for 2D rectangular transformed grid
Args:
gsimax (int, optional): Description
dgsi (float, optional): Description
etae (int, optional): Description
deta1 (float, optional): Description
stretch (float, optional): Description | 625941ce1f037a2d8b946336 |
def __prev_view(self, action, value): <NEW_LINE> <INDENT> curpage = self.notebook.get_current_page() <NEW_LINE> for key in self.page_lookup: <NEW_LINE> <INDENT> if self.page_lookup[key] == curpage: <NEW_LINE> <INDENT> cat_num, view_num = key <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if cat_num > 0: <NEW_LINE> <INDE... | Callback that is called when the previous category action is selected.
It selects the previous category as the active category. If we reach
the beginning of the list, we wrap around to the last. | 625941ceff9c53063f47c32c |
def on_key_press(self, callback): <NEW_LINE> <INDENT> pass | Catch a key event and call the callback function | 625941ce0a366e3fb873e953 |
def ellipse(x, y, rx, ry, n=64): <NEW_LINE> <INDENT> return arc(x, y, rx, ry, 0, np.pi*2, n=n) | Returns a polyline approximating an ellipse.
:param x: the x coordinate of the ellipse's center
:param y: the y coordinate of the ellipse's center
:param rx: the radius of the arc on the x axis
:param ry: the radius of the arc on the y axis
:param n: the number of points approximating the arc | 625941ce15fb5d323cde0c48 |
def parsehelper_460(self, node): <NEW_LINE> <INDENT> oldpos = self.pos <NEW_LINE> childs = [] <NEW_LINE> c = self.parsehelper_461(node) <NEW_LINE> if c is None: <NEW_LINE> <INDENT> self.pos = oldpos <NEW_LINE> return None <NEW_LINE> <DEDENT> childs.extend(c) <NEW_LINE> c = self.parsehelper_462(node) <NEW_LINE> if c is ... | ## subexpr ##
GrammarNode('S', ["'for'", 'exprlist', "'in'", 'testlist', "':'", 'suite', GrammarNode('[', GrammarNode('S', ["'else'", "':'", 'suite']))]) | 625941ce66656f66f7cbc2e3 |
@application.route('/trans/<trans_id>', methods=['DELETE']) <NEW_LINE> @token_required <NEW_LINE> def removeTransaction(currentUser, trans_id): <NEW_LINE> <INDENT> trans = Transaction.query.filter_by(id=trans_id, userId=currentUser.id).first() <NEW_LINE> if not trans: <NEW_LINE> <INDENT> return jsonify({'message': 'No ... | 10. This function removes a transaction from database | 625941cea79ad161976cc27e |
def getJobs(type = 'script', object = {}): <NEW_LINE> <INDENT> assert type in ['script', 'update', 'patch'], 'wrong type' <NEW_LINE> path = '/jobs' <NEW_LINE> query = { 'type': type, } <NEW_LINE> if type in ['script']: <NEW_LINE> <INDENT> assert object != {}, 'no script object' <NEW_LINE> query['id'] = object['scriptId... | Get jobs of a given script
Example:
- getJobs(type='patch') # get applied patch jobs
- getJobs(type='script', object=script) # get script jobs
@note: Currently support script jobs only.
@todo: Add support for update/patch job
@type type: string
@param type: Job type, default is B{script}. Valid values are:
-... | 625941ce66656f66f7cbc2e4 |
def _add_request_to_front_of_queue(self, request): <NEW_LINE> <INDENT> new_queue = deque() <NEW_LINE> new_queue.append(request) <NEW_LINE> while not self._reg_queue.empty(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> new_queue.append(self._reg_queue.get()) <NEW_LINE> <DEDENT> except gevent.queue.Queue.Empty: <NEW_LIN... | Adds item to the front of the queue | 625941ce23849d37ff7b31c8 |
def evaluate(formula, model): <NEW_LINE> <INDENT> pass | Return the truth value of the given formula in the given model | 625941ce63f4b57ef0001251 |
def _sensor_reading_generator(self, t_celsius, h_percent): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> t_celsius += Decimal(str(random.choice((-1, 1)) / 20.0)) <NEW_LINE> h_percent += Decimal(str(random.choice((-1, 1)) / 20.0)) <NEW_LINE> h_percent = min(Decimal("99"), h_percent) <NEW_LINE> yield t_celsius, h_p... | Generates sensor readings that are relatively stable, moving by
+ or -0.05 for each calling | 625941ce925a0f43d2549fb0 |
def train(self, **kwargs): <NEW_LINE> <INDENT> vectorizer = CountVectorizer(binary=False, ngram_range=(1, 2)) <NEW_LINE> self.Doc_term_matrix = vectorizer.fit_transform(self.corpus) <NEW_LINE> X_train, X_val, y_train, y_val = train_test_split(self.Doc_term_matrix, self.target, train_size=0.75, test_size=0.25, random_st... | Train classifier.
:param kwargs: Arbitrary keyword arguments: classifier='LR'
:type kwargs: str
:return: Object | 625941ced58c6744b4257d99 |
def _config_measurement(self): <NEW_LINE> <INDENT> self._inst.write("ROUTe:LTE:MEAS:SCENario:CSPath 'LTE Sig1'") <NEW_LINE> self._inst.write('CONFigure:LTE:MEAS:MEValuation:REPetition SING') <NEW_LINE> self._inst.write('CONFigure:LTE:MEAS:MEValuation:MODulation:MSCHeme AUTO') <NEW_LINE> self._inst.write('CONFigure:LTE:... | 该方法用于配置测量相关参数。 | 625941ceb545ff76a8913f4e |
@mock.patch.object(download_threads, '_MultithreadedDownloader') <NEW_LINE> def test_download_file(mock_multithreaded_downloader_init): <NEW_LINE> <INDENT> syn = mock.Mock() <NEW_LINE> file_handle_id = 1234 <NEW_LINE> object_id = 'syn123' <NEW_LINE> object_type = None <NEW_LINE> path = '/tmp/foo' <NEW_LINE> request = D... | Verify that initiating a download instantiates a downloader and passes it the correct args.
This test simulates a shared executor being set externally via the sharedexecutor context manager | 625941ce6fece00bbac2d877 |
def create_resource(self, name_prefix, creation_func, *args, **kwargs): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> name = self.get_rand_name(n_const.DEV_NAME_MAX_LEN, name_prefix) <NEW_LINE> try: <NEW_LINE> <INDENT> return creation_func(name, *args, **kwargs) <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE>... | Create a new resource that does not already exist.
:param name_prefix: The prefix for a randomly generated name
:param creation_func: A function taking the name of the resource
to be created as it's first argument. An error is assumed
to indicate a name collision.
:param *args *kwargs: These will be pas... | 625941ce97e22403b379d0d2 |
def test_auth_logout(self): <NEW_LINE> <INDENT> output = self.app.get('/logout') <NEW_LINE> self.assertEqual(output.status_code, 302) <NEW_LINE> output = self.app.get('/logout', follow_redirects=True) <NEW_LINE> self.assertEqual(output.status_code, 200) <NEW_LINE> self.assertTrue( '<h2>Fedora Public Active Mirrors</h2>... | Test the auth_logout endpoint. | 625941ced6c5a10208144184 |
def dataFile(self, path: bytes) -> Optional[Resource]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fileName = path.decode('ascii') <NEW_LINE> <DEDENT> except UnicodeDecodeError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> packageName = self.packageName <NEW_LINE> if importlib_resources.is_resource(packageName,... | Tries to open a data file at a relative path.
Returns a static resource on success or None on failure. | 625941ce711fe17d825424a4 |
def pytest_sessionstart(session): <NEW_LINE> <INDENT> app = server.init_app() <NEW_LINE> app.config["TESTING"] = True <NEW_LINE> ctx = app.app_context() <NEW_LINE> ctx.push() <NEW_LINE> logging.disable(logging.DEBUG) | before session.main() is called. | 625941cecad5886f8bd27112 |
def register_infer_correct_layout(op_name, infer_layout=None, level=10): <NEW_LINE> <INDENT> return tvm.ir.register_op_attr(op_name, "FInferCorrectLayout", infer_layout, level) | Register infer op layout function for an op
Parameters
----------
op_name : str
The name of the operator
infer_layout: function (attrs: Attrs, inputs: List[Layout]) -> InferCorrectLayoutOutput
The function to infer correct layout
level : int
The priority level | 625941ce31939e2706e4cfa3 |
@pytest.fixture() <NEW_LINE> def lww_set_object(): <NEW_LINE> <INDENT> set_object = LastWriterWinsSet() <NEW_LINE> return set_object | This fixture will create a LastWriterWinsSet object which will be shared by all tests in this module.
:return: | 625941ce3346ee7daa2b2ea4 |
def get_md_text(md_file): <NEW_LINE> <INDENT> sys.stderr.write("Getting Markdown text from {}/{}".format(os.getcwd(), md_file)) <NEW_LINE> assert os.path.isfile(md_file) <NEW_LINE> with open(md_file, 'r') as this_file: <NEW_LINE> <INDENT> text = this_file.read() <NEW_LINE> <DEDENT> return text | Take a file and return the text of that file | 625941cee1aae11d1e749df0 |
def join(self): <NEW_LINE> <INDENT> return "".join(self) | Свертка аггрегатора в результирующую строку | 625941ce99fddb7c1c9de4ca |
def get_config(self) -> Tuple[str, int, Optional[UserAuth]]: <NEW_LINE> <INDENT> self.check_config() <NEW_LINE> self.get_address() <NEW_LINE> auth = self.get_auth(*self.get_credentials()) <NEW_LINE> host = config.mail.get('host', '127.0.0.1') <NEW_LINE> port = config.mail.get('port', 0) <NEW_LINE> log.debug(f'Mail serv... | Construct user authentication and host/port values. | 625941ce287bf620b61d3b9c |
def get_replace_text(self) -> str: <NEW_LINE> <INDENT> return self.replace_entry.get_text() | Gets the text to replace
The text in Gtk.Entry for replacement.
:return: String containing the Gtk.Entry text | 625941cecc40096d61595a89 |
def maximalRectangle(self, matrix): <NEW_LINE> <INDENT> if not matrix or not matrix[0]: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> n = len(matrix[0]) <NEW_LINE> height = [0] * (n + 1) <NEW_LINE> ans = 0 <NEW_LINE> for row in matrix: <NEW_LINE> <INDENT> for i in xrange(n): <NEW_LINE> <INDENT> height[i] = height[i]... | :type matrix: List[List[str]]
:rtype: int
beats 75.80% | 625941ce3617ad0b5ed68030 |
def create_access_token(*, data: dict, expires_delta: timedelta = None): <NEW_LINE> <INDENT> to_encode = data.copy() <NEW_LINE> if expires_delta: <NEW_LINE> <INDENT> expire = datetime.utcnow() + expires_delta <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> expire = datetime.utcnow() + timedelta(minutes=15) <NEW_LINE> <DE... | create_access_token アクセストークンの生成
Args:
data (dict): データ
expires_delta (timedelta, optional): (不明)。初期値は None。
Returns:
[type]: [description] | 625941ce187af65679ca5258 |
def delete(self, deployment_id, force=False, delete_db_mode=False, with_logs=False): <NEW_LINE> <INDENT> assert deployment_id <NEW_LINE> params = {'force': force, 'delete_logs': with_logs} <NEW_LINE> if delete_db_mode: <NEW_LINE> <INDENT> warnings.warn('delete_db_mode is deprecated and does nothing', DeprecationWarning... | Deletes the deployment whose id matches the provided deployment id.
By default, deletion of a deployment with live nodes or installations
which depend on it is not allowed. This behavior can be changed
using the force argument.
:param deployment_id: The deployment's to be deleted id.
:param force: Delete deployment ev... | 625941ce8a43f66fc4b5419e |
def register(self, job_class, *args, **kwargs): <NEW_LINE> <INDENT> job_instance = job_class() <NEW_LINE> if not isinstance(job_instance, Job): <NEW_LINE> <INDENT> raise TypeError("You can only register a Job not a %r" % job_class) <NEW_LINE> <DEDENT> job, created = models.Job.objects.get_or_create(name=str(job_instanc... | Register the given Job with the scheduler class | 625941cef9cc0f698b140734 |
def __init__(self, default, **kwds): <NEW_LINE> <INDENT> super(DefSubjDesc, self).__init__(default=default, **kwds) | Init. | 625941ce91af0d3eaac9bb52 |
def longestCommonPrefix(self, strs): <NEW_LINE> <INDENT> if not strs: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> commonPrefix = strs[0] <NEW_LINE> for i in range(1, len(strs)): <NEW_LINE> <INDENT> commonPrefix = self.common_start(commonPrefix, strs[i]) <NEW_LINE> <DEDENT> return commonPrefix | :type strs: List[str]
:rtype: str | 625941ce7b25080760e39592 |
def count_fasta_seq(fasta_file): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fh= open(fasta_file) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return('chipseq_motif.count_fasta_seq: Cannot open file %s' %(fasta_file)) <NEW_LINE> <DEDENT> ncount= 0 <NEW_LINE> for n in fh: <NEW_LINE> <INDENT> if n.startswith('>'): <N... | Count the number of sequences in the input fasta_file.
Returns an integer. | 625941ce507cdc57c6306e14 |
def send_accel_data(s, accelBuffer): <NEW_LINE> <INDENT> pbuf = parse_accel_data(accelBuffer) <NEW_LINE> msg = dict(cmd = 'ADM', timestamp = str(datetime.datetime.now()), clid = raspidata.get_serial(), data = pbuf) <NEW_LINE> if (pbuf is not None) and (len(pbuf) > 0): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> loggin... | Send acceleration data to the server | 625941ce10dbd63aa1bd2cdd |
def prepare_assignment(self, assignment, datasets): <NEW_LINE> <INDENT> success = self.set_assignment(assignment) <NEW_LINE> assert success <NEW_LINE> dataset_id, task_index = assignment <NEW_LINE> logger.debug('Assigning task to slave %s: %s, %s' % (self.id, dataset_id, task_index)) <NEW_LINE> dataset = datasets[datas... | Sets up an RPC request to make the slave work on the assignment.
Called from the Runner. Note that the assignment will _not_ actually
happen until `send_assignment` is subsequently called. This is the
responsibility of the caller. | 625941ce76e4537e8c3517ac |
def Run(self, args): <NEW_LINE> <INDENT> adapter = self.context['api_adapter'] <NEW_LINE> project_ref = adapter.registry.Create('container.projects', projectsId=properties.VALUES.core .project.GetOrFail()) <NEW_LINE> try: <NEW_LINE> <INDENT> return adapter.ListUsableSubnets(project_ref, args.network_project, args.filte... | This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later. | 625941ce50812a4eaa59c45a |
def retrain_net_main(_): <NEW_LINE> <INDENT> tr_files = training_file() <NEW_LINE> retrainer.retrain_net(tr_files) | Retrains Inception custom data set | 625941ced10714528d5ffe1d |
def string2List(ustring): <NEW_LINE> <INDENT> retList = [] <NEW_LINE> utmp = [] <NEW_LINE> for uchar in ustring: <NEW_LINE> <INDENT> if is_other(uchar): <NEW_LINE> <INDENT> if len(utmp) == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> retList.append("".join(utmp)) <NEW_LINE> <DE... | 将ustring按照中文,字母,数字分开 | 625941ce91f36d47f21ac62c |
def eventFilter(self, obj, event): <NEW_LINE> <INDENT> if event.type() == QtCore.QEvent.Enter: <NEW_LINE> <INDENT> self._no_edit_lbl.show() <NEW_LINE> <DEDENT> elif event.type() == QtCore.QEvent.Leave: <NEW_LINE> <INDENT> self._no_edit_lbl.hide() <NEW_LINE> <DEDENT> return False | Filter mouse enter/leave events in order to show/hide the "no edit" label. | 625941ce26068e7796caee18 |
def _pyt_batchsort_train(self, datatype, preprocess): <NEW_LINE> <INDENT> defaults = integration_test_parser_defaults.copy() <NEW_LINE> defaults['datatype'] = datatype <NEW_LINE> defaults['pytorch_preprocess'] = preprocess <NEW_LINE> defaults['pytorch_teacher_batch_sort'] = True <NEW_LINE> if preprocess: <NEW_LINE> <IN... | Tests the functionality of training with batchsort
:param string datatype:
datatype to train with
:param bool preprocess:
whether to preprocess the data | 625941ce099cdd3c635f0d94 |
def launch_activity(args: list) -> None: <NEW_LINE> <INDENT> if len(clean_argument_flags(args)) < 1: <NEW_LINE> <INDENT> click.secho('Usage: android intent launch_activity <activity_class>', bold=True) <NEW_LINE> return <NEW_LINE> <DEDENT> intent_class = args[0] <NEW_LINE> click.secho('Launching Activity: {0}...'.forma... | Launches an activity class using an Android Intent
:param args:
:return: | 625941ce21a7993f00bc7e29 |
def replace(self, pat, repl, *fileglobs): <NEW_LINE> <INDENT> match = False <NEW_LINE> for g in fileglobs: <NEW_LINE> <INDENT> for f in rglob(self._out(g)): <NEW_LINE> <INDENT> match = True <NEW_LINE> replace(f, pat, repl) <NEW_LINE> <DEDENT> <DEDENT> if not match: <NEW_LINE> <INDENT> raise IOError("no files matched %s... | replace PATTERN REPLACEMENT FILEGLOB [FILEGLOB ...]
Find-and-replace the given PATTERN (Python-style regex) with the given
REPLACEMENT string for each of the files listed.
Example:
replace @VERSION@ ${product.version} /boot/grub.conf /boot/isolinux.cfg | 625941ce236d856c2ad44914 |
def noforcepoint(QTextStream): <NEW_LINE> <INDENT> return QTextStream | noforcepoint(QTextStream) -> QTextStream | 625941ce85dfad0860c3af94 |
@contextmanager <NEW_LINE> def suppress_logging(level=logging.CRITICAL): <NEW_LINE> <INDENT> orig_level = logging.root.manager.disable <NEW_LINE> logging.disable(level) <NEW_LINE> try: <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> logging.disable(orig_level) | Context manager to suppress logging messages.
:param level: logging level and below to suppress | 625941cef548e778e58cd6b7 |
def convertBST(self, root): <NEW_LINE> <INDENT> res = [] <NEW_LINE> def travel(root): <NEW_LINE> <INDENT> if root: <NEW_LINE> <INDENT> travel(root.left) <NEW_LINE> res.append(root.val) <NEW_LINE> travel(root.right) <NEW_LINE> <DEDENT> <DEDENT> travel(root) <NEW_LINE> self.s = 0 <NEW_LINE> def travel2(root): <NEW_LINE> ... | :type root: TreeNode
:rtype: TreeNode | 625941ce24f1403a92600c9f |
def generate_rgb_grid(grid: list) -> list: <NEW_LINE> <INDENT> for row in range(len(grid)): <NEW_LINE> <INDENT> for col in range(len(grid[row])): <NEW_LINE> <INDENT> average_rgb = avg_rgb(grid[row][col]) <NEW_LINE> grid[row][col] = (grid[row][col], average_rgb) <NEW_LINE> <DEDENT> <DEDENT> return grid | Calculates all of the average RGB values of the Images in a grid.
GRID is the two-dimensional Image list which contains the Image objects which this function calculates the average
RGB values for. | 625941ce004d5f362079a46c |
def encrypt(self, gp, pks, message, policy_str, t): <NEW_LINE> <INDENT> s = self.group.random() <NEW_LINE> w = self.group.init(ZR, 0) <NEW_LINE> policy = self.util.createPolicy(policy_str) <NEW_LINE> attribute_list = self.util.getAttributeList(policy) <NEW_LINE> secret_shares = self.util.calculateSharesDict(s, policy) ... | Encrypt a message under an access policy
:param gp: The global parameters.
:param pks: The public keys of the relevant attribute authorities, as dict from authority name to public key.
:param message: The message to encrypt.
:param policy_str: The access policy to use.
:return: The encrypted message. | 625941cea17c0f6771cbe189 |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941ced4950a0f3b08c488 |
def get_trace (self): <NEW_LINE> <INDENT> self._check_not_closed () <NEW_LINE> r = libguestfsmod.get_trace (self._o) <NEW_LINE> return r | Return the command trace flag.
| 625941ce090684286d50ee1f |
def make_supercell(self, scaling_matrix): <NEW_LINE> <INDENT> new_structure = self.copy_structure() <NEW_LINE> new_structure.make_supercell(scaling_matrix) <NEW_LINE> return new_structure | Create a supercell.
Args:
scaling_matrix: A scaling matrix for transforming the lattice vectors.
Has to be all integers. Several options are possible:
a. A full 3x3 scaling matrix defining the linear combination of the old lattice vectors.
E.g., [[2,1,0],[0,3,0],[0,0,1]] generates a ne... | 625941ce9f2886367277a9c6 |
def hits(self): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> return self.statistics.hits | How many hits has the cache had? | 625941ce66673b3332b921ca |
def __init__(self, game, x = 0, y = 0, value = 1000): <NEW_LINE> <INDENT> super(Diamond, self).__init__(image = Diamond.image, x = x, y = y) <NEW_LINE> self.value = value <NEW_LINE> self.game = game | Intialize a diamond object | 625941cedc8b845886cb566e |
def nnPredict(w1, w2, data): <NEW_LINE> <INDENT> print(data.shape) <NEW_LINE> labels = np.zeros(len(data)) <NEW_LINE> data = np.c_[data,np.ones(len(data))] <NEW_LINE> act_hidden_layer = np.dot(w1,data.T) <NEW_LINE> output_hidden_layer = sigmoid(act_hidden_layer) <NEW_LINE> act_output_layer = np.dot(w2,np.vstack([output... | % nnPredict predicts the label of data given the parameter w1, w2 of Neural
% Network.
% Input:
% w1: matrix of weights of connections from input layer to hidden layers.
% w1(i, j) represents the weight of connection from unit i in input
% layer to unit j in hidden layer.
% w2: matrix of weights of connections... | 625941ce4f88993c3716c1a0 |
def find_encrypt_key(p, q): <NEW_LINE> <INDENT> phi = (p-1) * (q-1) <NEW_LINE> encrypt_key = random.randrange(1, phi) <NEW_LINE> g = gcd(encrypt_key, phi) <NEW_LINE> while g != 1: <NEW_LINE> <INDENT> encrypt_key = random.randrange(1, phi) <NEW_LINE> g = gcd(encrypt_key, phi) <NEW_LINE> <DEDENT> return encrypt_key | Finds e such that e and (p-1) * (q-1) are relatively prime. | 625941ce4c3428357757c461 |
def fold_imag(z): <NEW_LINE> <INDENT> return np.real(z) + 1j*((np.imag(z) + np.pi)%(2*np.pi) - np.pi) | Returns z with imaginary values translated to the [-pi,pi] range. (If z is interpreted as a principal-branch logarithm.) | 625941ce7b25080760e39593 |
def test_version(): <NEW_LINE> <INDENT> from cds_sorenson import __version__ <NEW_LINE> assert __version__ | Test version import. | 625941ce5e10d32532c5f060 |
@pytest.fixture(scope="function") <NEW_LINE> def user_language_preference_en_explicit(request, test_session, en_locale, admin_user): <NEW_LINE> <INDENT> from assembl.models.auth import ( UserLanguagePreference, LanguagePreferenceOrder ) <NEW_LINE> locale_from = en_locale <NEW_LINE> ulp = UserLanguagePreference( user=ad... | User Language Preference fixture with English (en) explicit level | 625941ce57b8e32f524835d4 |
def test_query_with_no_parameters(self): <NEW_LINE> <INDENT> with pytest.raises(e.ParamError) as err_info: <NEW_LINE> <INDENT> query = self.as_connection.query() <NEW_LINE> <DEDENT> err_code = err_info.value.code <NEW_LINE> assert err_code == AerospikeStatus.AEROSPIKE_ERR_PARAM | Invoke query() without any mandatory parameters. | 625941cec432627299f04d7f |
def test_grant_response_type_backend_application(self): <NEW_LINE> <INDENT> client = self.new_client( vals={'application_type': 'backend application'}) <NEW_LINE> self.assertEqual(client.grant_type, 'client_credentials') <NEW_LINE> self.assertEqual(client.response_type, 'none') | Check the value of the grant_type and response_type fields | 625941ce656771135c3eb9a8 |
def t_LV(self, t): <NEW_LINE> <INDENT> t.value = int(t.value[2:]) <NEW_LINE> if t.value > 110: <NEW_LINE> <INDENT> t.value = 110 <NEW_LINE> <DEDENT> return t | [lL][vV]\d{1,3} | 625941cec432627299f04d80 |
def getDefaultGlobalMounts(self): <NEW_LINE> <INDENT> mounts = [] <NEW_LINE> mountConfigPairs = {} <NEW_LINE> return mounts, mountConfigPairs | Returns service-wide default mounts and mount config pairs | 625941ce4d74a7450ccd42fd |
def train_step(self, model, batches: list): <NEW_LINE> <INDENT> sum_tokens = 0 <NEW_LINE> sum_loss = 0 <NEW_LINE> for batch in batches: <NEW_LINE> <INDENT> new_batch = self.rebatch(batch) <NEW_LINE> log_prob = model.forward(new_batch.src, new_batch.src_mask, new_batch.trg_input, new_batch.trg, new_batch.trg_mask)['log_... | a step includes a forward and a backward, and we rebatch it with some batch options
:param batches: [domain1 batch, domain2 batch ...]
:param model:
:return: sum loss, sum tokens | 625941ce4527f215b584c590 |
def test_set_unset_max_job_sequence_id(self): <NEW_LINE> <INDENT> seq_id = {ATTR_max_job_sequence_id: 123456789} <NEW_LINE> try: <NEW_LINE> <INDENT> self.server.manager(MGR_CMD_SET, SERVER, seq_id, runas=TEST_USER1) <NEW_LINE> <DEDENT> except PbsManagerError as e: <NEW_LINE> <INDENT> self.assertTrue('Unauthorized Reque... | Set/Unset max_job_sequence_id attribute and
also verify the attribute value after server qterm/kill | 625941cee5267d203edcddd7 |
def view_matrix(self): <NEW_LINE> <INDENT> z = normr(self.direction().unsqueeze(0)) <NEW_LINE> x = normr(cross(self.up_vector.unsqueeze(0), z)) <NEW_LINE> y = cross(z, x) <NEW_LINE> p = self.position.unsqueeze(0) <NEW_LINE> M = torch.cat((torch.cat((x.t(), y.t(), z.t(), -p.t()), dim=1), torch.tensor([[0, 0, 0, 1]], dty... | Returns the current view matrix
Returns
-------
Tensor
a (4,4,) view matrix | 625941cecb5e8a47e48b7be3 |
def _make_generator(input_layer): <NEW_LINE> <INDENT> dense1 = tf.layers.dense(inputs=input_layer, units = 1024, activation = tf.nn.relu) <NEW_LINE> dropout = tf.layers.dropout(inputs = dense1, rate = 0.4) <NEW_LINE> dense2 = tf.layers.dense(inputs = dropout, units = 7*7*64, activation = tf.nn.relu) <NEW_LINE> dense2_ ... | This is a bit more tricky to implement as it uses deconvolution blocks to m-
-ake an image. I will try to mimick the architecture of convolutional blocks. | 625941ce627d3e7fe0d68f8a |
def _annotations(request): <NEW_LINE> <INDENT> result = search.Search(request).run(MultiDict(request.params)) <NEW_LINE> return fetch_ordered_annotations(request.db, result.annotation_ids) | Return the annotations from the search API. | 625941ce0c0af96317bb8321 |
def srvcmd(cmd, sub_mode=0): <NEW_LINE> <INDENT> def actual(func): <NEW_LINE> <INDENT> func.__service__ = cmd <NEW_LINE> func.__sub_mode__ = sub_mode <NEW_LINE> return func <NEW_LINE> <DEDENT> return actual | sub_mode : 0 时所有消费端都可以执行,-1时,只允许其中一个消费端执行 | 625941ce4f88993c3716c1a1 |
def random_collection_method(invalid_data): <NEW_LINE> <INDENT> return (random.choice(covid19_vocab_dict.get('collection_method')), global_valid_data) | Generate Random Collection Device
return: string containing "collection device" from CanCOGeN vocabulary. | 625941ce1f5feb6acb0c4c8a |
def get_test_feed_dict(self, minibatch): <NEW_LINE> <INDENT> learned_embedding_batch = minibatch['learned_embedding_batch'] <NEW_LINE> batch_size = learned_embedding_batch.shape[0] <NEW_LINE> g_match_noise_batch = sample_z(batch_size) <NEW_LINE> feed_dict = { self.placeholders['fake_desc_component']: learned_embedding_... | Gets the feed dict.
Args:
minibatch: Minibatch of data.
Returns:
feed_dict: Feed dictionary.
batch_size: Batch size. | 625941ce3617ad0b5ed68031 |
def random_sample(m, n): <NEW_LINE> <INDENT> if m == 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> S = random_sample(m - 1, n - 1) <NEW_LINE> i = random.randint(1, n) <NEW_LINE> if i in S: <NEW_LINE> <INDENT> S.append(n) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> S.append(i) <NEW_LIN... | Returns a random sample of m integers from [1,...,n] as a list. | 625941ceac7a0e7691ed4206 |
def set_libtorrent_max_download_rate(self, value): <NEW_LINE> <INDENT> self.config['libtorrent']['max_download_rate'] = value | Sets the maximum download rate (kB / s).
:param value: the new maximum download rate in kB / s
:return: | 625941ce0fa83653e46570f4 |
def chooseRandomPokemon(self, pkmnInPlay): <NEW_LINE> <INDENT> pkmnOut = [] <NEW_LINE> for pkmn in pkmnInPlay: <NEW_LINE> <INDENT> pkmnOut.append(pkmn.pkmn) <NEW_LINE> <DEDENT> pkmn = None <NEW_LINE> while pkmn in pkmnOut or pkmn is None or pkmn.fainted(): <NEW_LINE> <INDENT> pkmn = random.choice(self.beltPokemon) <NEW... | Chooses a Random Pokemon | 625941ce8e7ae83300e4b106 |
def SetByteArray(self,item_name,*__args): <NEW_LINE> <INDENT> pass | SetByteArray(self: GH_IWriter,item_name: str,item_index: int,item_value: Array[Byte])
Add a new data item to this chunk.
The combination of name and index must be
unique or an exception will be thrown.
item_name: Name of item to add.
item_index: Index of item to add.
item_value: Value of item to ad... | 625941cef7d966606f6aa13e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.