code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def t_comentario_block(t): <NEW_LINE> <INDENT> t.lexer.lineno += t.value.count('\n') <NEW_LINE> print("Comentario de multiple linea") | /\*(.|\n)*?\*/ | 625941e06fece00bbac2dacf |
def get_list_sec_filings (duration = 5, dbname = "edgar_idx.db"): <NEW_LINE> <INDENT> import datetime <NEW_LINE> current_year = datetime.date.today().year <NEW_LINE> current_quarter = (datetime.date.today().month - 1) // 3 + 1 <NEW_LINE> start_year = current_year - duration <NEW_LINE> with open("logfile.txt", "a+") as ... | Generate the list of index files archived in EDGAR since start_year (earliest: 1993) until the most recent quarter
Note: this does not download the filings itself, just enough information to generate the filing urls from it. | 625941e0d6c5a102081443db |
def add(self, element, hide_hotkey=False): <NEW_LINE> <INDENT> self.elements.append(element) <NEW_LINE> self._refresh_context_elements() <NEW_LINE> if not hide_hotkey and not isinstance(element, UxTabButton): <NEW_LINE> <INDENT> self._draw_element_hotkey(element) | Add an element to this UxManager. munch. | 625941e091af0d3eaac9bda9 |
def __span2event(self, span_node_ids): <NEW_LINE> <INDENT> return (self.toknode2id[span_node_ids[0]], self.toknode2id[span_node_ids[-1]]+1) | converts a span of tokens (list of token node IDs) into an Exmaralda
event (start and end ID).
Parameters
----------
span_node_ids : list of str
sorted list of node IDs representing a span of tokens
Returns
-------
event : tuple of (str, str)
event start ID and event end ID | 625941e055399d3f05588a43 |
def get_urls(advisory): <NEW_LINE> <INDENT> urls = re.findall(url_marker.URL_REGEX_NO_NAKED, json.dumps(advisory)) <NEW_LINE> for u in urls: <NEW_LINE> <INDENT> if not ("http://" in u or "https://" in u): <NEW_LINE> <INDENT> logging.warning("%s does not contains http:// or https://",u) <NEW_LINE> logging.warning("addin... | Given an advisory (dictionary), return a list with contained urls. | 625941e04f6381625f114dc9 |
def vote_on_proposal(NetworkId=None, ProposalId=None, VoterMemberId=None, Vote=None): <NEW_LINE> <INDENT> pass | Casts a vote for a specified ProposalId on behalf of a member. The member to vote as, specified by VoterMemberId , must be in the same AWS account as the principal that calls the action.
See also: AWS API Documentation
Exceptions
:example: response = client.vote_on_proposal(
NetworkId=... | 625941e07d847024c06be64c |
def write_comment_to_keystore(form): <NEW_LINE> <INDENT> k = keystore_write(form.vars.comment) <NEW_LINE> form.vars.comment = k | Gets a submission form, and writes the comment to the keystore, replacing
it by the keystore key. | 625941e0e64d504609d74bcd |
def csv_clean_colnames(self, file, sep=''): <NEW_LINE> <INDENT> import re <NEW_LINE> import csv <NEW_LINE> import os <NEW_LINE> def remove_special_characters(text, sep=sep): <NEW_LINE> <INDENT> pattern = r'[^a-zA-Z0-9!"#$%&\'()*+, -./:; <= >?@[\]^_`{|}~]' <NEW_LINE> return re.sub(pattern, sep, text) <NEW_LINE> <DEDENT>... | Given the path to a csv file, this function cleans the column names by
converting removing leading and trailing white spaces, converting all
letters to lowercase, replacing all remaining whitespaces with
underscores, removing brackets, forward slashes, and other special
characters. The csv file is then replaced with a ... | 625941e0cb5e8a47e48b7e32 |
def simulate_steps(grid: List[List[int]], steps: int = 100) -> int: <NEW_LINE> <INDENT> flashes = 0 <NEW_LINE> for _ in range(steps): <NEW_LINE> <INDENT> flashes += next_step(grid) <NEW_LINE> <DEDENT> return flashes | Return total number of flashes. | 625941e0e76e3b2f99f3ab93 |
def rewind_search(self) -> None: <NEW_LINE> <INDENT> if not self.matching: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> prev = self.matching[self.search_index] <NEW_LINE> self.apply_unselected_styling(prev) <NEW_LINE> self.search_index -= 1 <NEW_LINE> self.search_index %= len(self.matching) <NEW_LINE> self.apply_sele... | Focus on the previous search result | 625941e00fa83653e4657346 |
def predecessors(self, v, etype=None): <NEW_LINE> <INDENT> if not self.has_nodes(v, self.to_canonical_etype(etype)[-1]): <NEW_LINE> <INDENT> raise DGLError('Non-existing node ID {}'.format(v)) <NEW_LINE> <DEDENT> return self._graph.predecessors(self.get_etype_id(etype), v) | Return the predecessor(s) of a particular node with the specified edge type.
Node ``u`` is a predecessor of node ``v`` if there is an edge ``(u, v)`` with type
``etype`` in the graph.
Parameters
----------
v : int
The destination node for query.
etype : str or tuple of str, optional
The edge type for query, w... | 625941e09c8ee82313fbbb03 |
def set_writer(self, writer): <NEW_LINE> <INDENT> self.writer = writer | Override the currently registered writer object.
:param writer:
An instance of :class:`~.writer.BasePdfFileWriter`. | 625941e0097d151d1a2231e5 |
def get_midnight_tonight(self, botengine): <NEW_LINE> <INDENT> return self.get_local_datetime(botengine).replace(hour=23, minute=59, second=59, microsecond=999999) | Get a datetime of midnight tonight in local time
:param botengine: BotEngine environment
:return: Datetime object of midnight tonight in the local timezone | 625941e0baa26c4b54cb14a9 |
@mod_api_izbori.route("/", methods=['GET']) <NEW_LINE> def index(): <NEW_LINE> <INDENT> return 'Izbori API' | Renders the API documentation page.
:return: | 625941e0e1aae11d1e74a048 |
def set_matcher(self, func): <NEW_LINE> <INDENT> self.match = func.__get__(self, self.__class__) | Sets the function called to match URIs.
:param func:
A function that receives ``(router, request)`` and returns
a tuple ``(route, args, kwargs)`` if any route matches, or
raise ``exc.HTTPNotFound`` if no route matched or
``exc.HTTPMethodNotAllowed`` if a route matched but the HTTP
method was not al... | 625941e0f548e778e58cd90d |
def __init__(self): <NEW_LINE> <INDENT> transport = AIOHTTPTransport(url="http://localhost:3000/graphql") <NEW_LINE> self.client = Client(transport=transport, fetch_schema_from_transport=True) | Creates graphql client | 625941e030bbd722463cc155 |
@content_replay_retry <NEW_LINE> def obj_in_objstorage(obj_id, dst): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return obj_id in dst <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> raise ReplayError(obj_id=obj_id, exc=exc) from None | Check if an object is already in an objstorage, tenaciously | 625941e0a934411ee3751a22 |
def __query_date_from_string(self, date_string, user_id): <NEW_LINE> <INDENT> converted_date = datetime.datetime.strptime( date_string, "%Y-%m-%d").date() <NEW_LINE> info = Date.query.filter_by(date=converted_date, uid=user_id).all() <NEW_LINE> if info == []: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <N... | return a Date object after quering the Datebase | 625941e044b2445a33932421 |
def genRepository(self): <NEW_LINE> <INDENT> self.File.checkPath(self.GenRepository.repositoryDir) <NEW_LINE> sheetNames = self.Xls.getSheetNames() <NEW_LINE> for sheetName in sheetNames: <NEW_LINE> <INDENT> self.GenRepository.GenRepositoryFile(sheetName) <NEW_LINE> self.File.Save(self.GenRepository.fileName,self.GenRe... | 執行產生Asp.net Core Repository | 625941e0167d2b6e31218f22 |
def _field_from_query_item(self, item_lines: list, field: str): <NEW_LINE> <INDENT> val = '' <NEW_LINE> indent = '' <NEW_LINE> in_field = False <NEW_LINE> lines_collected = 0 <NEW_LINE> for i, line in enumerate(item_lines): <NEW_LINE> <INDENT> m = re.match(r'(\s+)(.*):\s*(.*)$', line) <NEW_LINE> if m and m.group(2).low... | Extracts display field from xrandr --verbose output | 625941e03617ad0b5ed68284 |
def _render_boot( self ): <NEW_LINE> <INDENT> if self.sideType != GL_TRIANGLES and self.backwardPoints is not None: <NEW_LINE> <INDENT> glVertexPointerd(self.backwardPoints ) <NEW_LINE> glEnableClientState(GL_VERTEX_ARRAY); <NEW_LINE> glDrawArrays(GL_TRIANGLES, 0, len(self.backwardPoints)) <NEW_LINE> glDisableClientSta... | Render the shadow-volume boot (backward-facing faces projected) | 625941e073bcbd0ca4b2c403 |
def test_query_apply_with_no_parameters(self): <NEW_LINE> <INDENT> with pytest.raises(TypeError) as typeError: <NEW_LINE> <INDENT> self.as_connection.query_apply() | Invoke query_apply() without any mandatory parameters.
It should raise a type error as the wrong parameters are passed | 625941e07d43ff24873a3030 |
def ask_name(robot_name): <NEW_LINE> <INDENT> print(CONVERSATION_BREAK) <NEW_LINE> print("{robot_name}: こんにちは!私は{robot_name}です。あなたの名前は何ですか?".format(robot_name=robot_name)) <NEW_LINE> print(CONVERSATION_BREAK) <NEW_LINE> user_name = input() <NEW_LINE> return user_name | 名前を尋ねる。アイスブレイクは大事。
:param robot_name: roboter()から渡しています。
:return: ユーザーの名前を返します。 | 625941e0f9cc0f698b140986 |
def __init__(self, debug_obj): <NEW_LINE> <INDENT> self.obj = debug_obj | Pass in a FlaskSqlaDebug object here. | 625941e0046cf37aa974d0d2 |
def testDestroyFlowStates(self): <NEW_LINE> <INDENT> session_id = rdfvalue.SessionID("aff4:/flows/test2") <NEW_LINE> request = rdfvalue.RequestState( id=1, client_id=self.client_id, next_state="TestState", session_id=session_id) <NEW_LINE> with queue_manager.QueueManager(token=self.token) as manager: <NEW_LINE> <INDENT... | Check that we can efficiently destroy the flow's request queues. | 625941e0851cf427c661a89a |
def _fix_headers(patients_df: pd.DataFrame) -> pd.DataFrame: <NEW_LINE> <INDENT> if "cxr_severity_3" in patients_df: <NEW_LINE> <INDENT> patients_df.rename( columns={"cxr_severity_3": "cxr_severity_2"}, inplace=True, ) <NEW_LINE> <DEDENT> return patients_df | Fixes known mistakes in column headers.
Should always be run last as it acts on the cleaned columns. | 625941e096565a6dacc8fa58 |
def get_authority_load( session: Session, authority: typing.Text, start_at: http.QueryParam, end_at: http.QueryParam): <NEW_LINE> <INDENT> start_dt = get_dt_from_string( start_at, default_dt=pytz.utc.localize(dt.utcnow() - td(days=1)) ) <NEW_LINE> end_dt = get_dt_from_string( end_at, default_dt=pytz.utc.localize(dt.utc... | Get a timeseries of energy load for a balancing authority. | 625941e00a366e3fb873ebab |
def get_users(self): <NEW_LINE> <INDENT> self.validate_root() <NEW_LINE> return [] | get the users list
Return:
A list of users
Raise:
ConfigError in-case of an error | 625941e0167d2b6e31218f23 |
def ancestor(self, a, b): <NEW_LINE> <INDENT> a, b = self.rev(a), self.rev(b) <NEW_LINE> try: <NEW_LINE> <INDENT> ancs = self.index.ancestors(a, b) <NEW_LINE> <DEDENT> except (AttributeError, OverflowError): <NEW_LINE> <INDENT> ancs = ancestor.ancestors(self.parentrevs, a, b) <NEW_LINE> <DEDENT> if ancs: <NEW_LINE> <IN... | calculate the "best" common ancestor of nodes a and b | 625941e063f4b57ef000149d |
def percentiles_files(xml_input_path, xml_output_path): <NEW_LINE> <INDENT> reader = SeriesReader(xml_input_path) <NEW_LINE> converter = PercentileConverter() <NEW_LINE> writer = SeriesWriter(xml_output_path) <NEW_LINE> writer.write(converter.convert(reader.read())) | Uses the PercentileConverter to calculate 10, 50 and 90 percentiles. | 625941e063b5f9789fde7474 |
def _add_step(self, pos): <NEW_LINE> <INDENT> self._steps.append(pos) <NEW_LINE> self._rec_x = pos[0] <NEW_LINE> self._rec_y = pos[1] | Add a step to the end of the current recorded path.
:param pos: The position tuple (x, y) to add to the list. | 625941e099fddb7c1c9de71d |
def list_experiments(self, limit=None): <NEW_LINE> <INDENT> if not self._ICP: <NEW_LINE> <INDENT> experiment_resources = self.get_experiment_details(limit=limit)[u'resources'] <NEW_LINE> experiment_values = [(m[u'metadata'][u'guid'], m[u'entity'][u'settings'][u'name'], m[u'metadata'][u'created_at']) for m in experiment... | List stored experiments. If limit is set to None there will be only first 50 records shown.
:param limit: limit number of fetched records (optional)
:type limit: int
:returns: None
:rtype: None
.. note::
This function only prints the list of stored experiments
**Example**:
>>> client.repository.list_experiment... | 625941e023e79379d52ee8ed |
def on_search_config_btn_clicked_cb(btn, data=None): <NEW_LINE> <INDENT> lbl = self.builder.get_object('search_config_entry') <NEW_LINE> self.controller.select_remote(lbl.get_text()) | User clicked "Search remote" button. | 625941e04527f215b584c7e1 |
def _update_indicator(self,K,L): <NEW_LINE> <INDENT> _update = {'term': self.n_terms*np.ones((K,L)).T.ravel(), 'row': np.kron(np.arange(K)[:,np.newaxis],np.ones((1,L))).T.ravel(), 'col': np.kron(np.ones((K,1)),np.arange(L)[np.newaxis,:]).T.ravel()} <NEW_LINE> for key in list(_update.keys()): <NEW_LINE> <INDENT> self.in... | update the indicator | 625941e055399d3f05588a44 |
def blogonpasswords(*args, silent=False, fork=None, sync=True): <NEW_LINE> <INDENT> return engine.call('blogonpasswords', args, silent=silent, fork=fork, sync=sync) | "
Documentation from https://www.cobaltstrike.com/aggressor-script/functions.html:
Ask Beacon to dump in-memory credentials with mimikatz
Arguments
$1 - the id for the beacon. This may be an array or a single ID.
Example
item "Dump &Passwords" {
binput($1, "logonpasswords");
blogonp... | 625941e0566aa707497f48f2 |
@accepts(t.enum, t.sizei, t.enum, t.sizei, t.sizei, t.sizei, t.boolean) <NEW_LINE> @returns(t.void) <NEW_LINE> @binds(dll) <NEW_LINE> def tex_storage3_d_multisample(target, samples, internalformat, width, height, depth, fixedsamplelocations): <NEW_LINE> <INDENT> pass | specify storage for a two-dimensional multisample array texture.
Args:
target: the target to which the texture object is bound for
gltexstorage3dmultisample.
samples: the number of samples in the texture.
internalformat: the sized internal format to be used to store texture
image data.
... | 625941e0d53ae8145f87a5f8 |
def unmount_device(dev): <NEW_LINE> <INDENT> cmd = "sudo umount " + str(dev) <NEW_LINE> exitcode, stdout, stderr = LocalMachine.run_command(cmd) <NEW_LINE> check_exitcode(cmd, exitcode, stderr) <NEW_LINE> time.sleep(1) <NEW_LINE> if device_is_mounted(dev): <NEW_LINE> <INDENT> time.sleep(1) <NEW_LINE> unmount_device(dev... | device example: /dev/sda1 or mount point example: /media/device | 625941e03c8af77a43ae3b32 |
def lasersOff(self): <NEW_LINE> <INDENT> self._left_laser.off() <NEW_LINE> self._right_laser.off() | Turn off both lasers | 625941e0090684286d50f079 |
def get_tokens(source): <NEW_LINE> <INDENT> stmts = sqlparse.parse(source) <NEW_LINE> if stmts: <NEW_LINE> <INDENT> retval = stmts[0].tokens <NEW_LINE> tokens = chain.from_iterable(stmt.tokens for stmt in stmts[1:]) <NEW_LINE> retval.extend(sql.Token(Token.Error.Next, t.value) for t in tokens) <NEW_LINE> return retval ... | Returns a list of all tokens, not separated by statement. All
tokens not belonging to the first statement are returned as error
tokens. | 625941e0d58c6744b4257fec |
def stop(self): <NEW_LINE> <INDENT> if not self._is_running: <NEW_LINE> <INDENT> raise RuntimeError("Profiler is not running") <NEW_LINE> <DEDENT> yappi.stop() <NEW_LINE> yappi_stats = yappi.get_func_stats() <NEW_LINE> yappi_stats.sort('tsub', sort_order="desc") <NEW_LINE> log_dir = self.logs_dir <NEW_LINE> file_path =... | Stop Yappi and write the stats to the output directory.
Return the path of the statistics file. | 625941e0b57a9660fec33c17 |
def get_hasher(algorithm='default'): <NEW_LINE> <INDENT> if hasattr(algorithm, 'algorithm'): <NEW_LINE> <INDENT> return algorithm <NEW_LINE> <DEDENT> elif algorithm == 'default': <NEW_LINE> <INDENT> return get_hashers()[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hashers = get_hashers_by_algorithm() <NEW_LINE> try... | Returns an instance of a loaded password hasher.
If algorithm is 'default', the default hasher will be returned.
This function will also lazy import hashers specified in your
settings file if needed. | 625941e0b545ff76a89141a4 |
def AssertOlderBuild(self, timestamp, timestamp_text): <NEW_LINE> <INDENT> self.script.append( ('(!less_than_int(%s, getprop("ro.build.date.utc"))) || ' 'abort("E%d: Can\'t install this package (%s) over newer ' 'build (" + getprop("ro.build.date") + ").");') % (timestamp, common.ErrorCode.OLDER_BUILD, timestamp_text)) | Assert that the build on the device is older (or the same as)
the given timestamp. | 625941e0507cdc57c6307071 |
def test_create_networking_resource_from_context(self): <NEW_LINE> <INDENT> shell_name = "test shell name" <NEW_LINE> supported_os = "test OS" <NEW_LINE> context = mock.MagicMock() <NEW_LINE> result = create_firewall_resource_from_context(shell_name=shell_name, supported_os=supported_os, context=context) <NEW_LINE> sel... | Check that method will create and return GenericNetworkingResource instance from given context | 625941e0f8510a7c17cf9a8d |
def test_permitted_symbols(): <NEW_LINE> <INDENT> assert calc.permitted_symbols() == ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] | test for permitted symbols | 625941e030bbd722463cc156 |
def __init__(self): <NEW_LINE> <INDENT> super(EditorAPIsPage, self).__init__() <NEW_LINE> self.setupUi(self) <NEW_LINE> self.setObjectName("EditorAPIsPage") <NEW_LINE> self.apiFileButton.setIcon(UI.PixmapCache.getIcon("open.png")) <NEW_LINE> self.prepareApiButton.setText(self.tr("Compile APIs")) <NEW_LINE> self.__curre... | Constructor | 625941e0046cf37aa974d0d3 |
def normalize_antenna_sel(self, args): <NEW_LINE> <INDENT> if args.antenna is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> antennas = [x.strip() for x in args.antenna.split(",")] <NEW_LINE> if len(antennas) != 1 and len(antennas) != len(args.channels): <NEW_LINE> <INDENT> raise ValueError("Invalid antenna ... | Make sure the --antenna option matches the --channels option. | 625941e0596a897236089e4b |
def fitTerms(self, x0, y0, terms='a*exp(b*x)+c'): <NEW_LINE> <INDENT> if (isnumber(x0) and np.isnan(x0)) or (isnumber(y0) and np.isnan(y0)): <NEW_LINE> <INDENT> return Exception("Need at least 2 dimensional data to fit"), None, None, None <NEW_LINE> <DEDENT> p0, bounds0 = None, None <NEW_LINE> if terms == 'a*exp(b*x)':... | Fit a function with predefined equation | 625941e024f1403a92600ef2 |
def generate(self): <NEW_LINE> <INDENT> self.valid() <NEW_LINE> lower_num = random.randint(1, self.length-self.level) <NEW_LINE> lower_str = self.choice_n(string.ascii_lowercase, lower_num) <NEW_LINE> if self.level == 1: <NEW_LINE> <INDENT> upper_num = self.length - lower_num <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDEN... | :param level:
level 1 : lower letters + upper letter
level 2 : lower letters + upper letter + digits (default)
level 3 : lower letters + upper letter + digits + punctuations | 625941e06e29344779a6299e |
def _get_socket(self): <NEW_LINE> <INDENT> s = socket.socket() <NEW_LINE> s.connect((self._host, 6600)) <NEW_LINE> s.recv(32) <NEW_LINE> return s | Connect to the MPD instance and flush the greeting | 625941e08c0ade5d55d3ed4c |
def _load_pascal_annotation(self, index): <NEW_LINE> <INDENT> filename = os.path.join(self._data_path, 'Annotations', index.replace('.jpg','') + '.xml') <NEW_LINE> tree = ET.parse(filename) <NEW_LINE> objs = tree.findall('object') <NEW_LINE> num_objs = len(objs) <NEW_LINE> count = 0 <NEW_LINE> for ix, obj in enumerate(... | Load image and bounding boxes info from XML file in the PASCAL VOC
format. Exclude bounding boxes which are not included in self._classes. | 625941e08a349b6b435e8501 |
def test_deployment_view_find_deployment_node(empty_workspace: Workspace): <NEW_LINE> <INDENT> model = empty_workspace.model <NEW_LINE> software_system = model.add_software_system("Software System") <NEW_LINE> container1 = software_system.add_container("Container 1") <NEW_LINE> node1 = model.add_deployment_node("Deploy... | Test _find_deployment_node. | 625941e07cff6e4e81117d14 |
def __init__(self, system_owned=None, display_name=None, description=None, tags=None, create_user=None, protection=None, create_time=None, last_modified_time=None, last_modified_user=None, id=None, resource_type=None, collectors=None, *args, **kwargs): <NEW_LINE> <INDENT> self._system_owned = None <NEW_LINE> self._disp... | IpfixCollectorUpmProfile - a model defined in Swagger | 625941e057b8e32f5248382c |
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(RecognizeObjectRequest, self).__init__(*args, **kwds) | Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
@param args: complete set of fie... | 625941e0d10714528d600076 |
def test_out_json(self, capsys): <NEW_LINE> <INDENT> params = ['-o', 'json', self.all_nodes, 'cat /tmp/out'] <NEW_LINE> rc = cli.main(argv=self.default_params + params) <NEW_LINE> out, err = capsys.readouterr() <NEW_LINE> sys.stdout.write(out) <NEW_LINE> sys.stderr.write(err) <NEW_LINE> assert _EXPECTED_LINES['all_targ... | The -o/--out json option should print a JSON with hostnames as keys and output as values. | 625941e010dbd63aa1bd2f31 |
def find_two_smallest(L): <NEW_LINE> <INDENT> if L[0] < L[1]: <NEW_LINE> <INDENT> min1, min2 = 0, 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> min2, min1 = 1, 0 <NEW_LINE> <DEDENT> for i in range(2, len(L)): <NEW_LINE> <INDENT> if L[i] < L[min1]: <NEW_LINE> <INDENT> min2 = min1 <NEW_LINE> min1 = i <NEW_LINE> <DEDENT... | Return a tuple of the indices of the two smallest values in list L. | 625941e09f2886367277ac1a |
def prime_tdd(number): <NEW_LINE> <INDENT> if not isinstance(number, int): <NEW_LINE> <INDENT> return "Unexpected non integer input" <NEW_LINE> <DEDENT> if number < 0: <NEW_LINE> <INDENT> return "error" <NEW_LINE> <DEDENT> results = [] <NEW_LINE> for i in range(2, number+1): <NEW_LINE> <INDENT> if isPrime(i): <NEW_LINE... | input
number(int) -> this is a positive number
outputs:
results(list) -> list of numbers | 625941e016aa5153ce362807 |
def test_stage1_check_rhel_version(test_instance): <NEW_LINE> <INDENT> aminame = test_instance.info['name'] <NEW_LINE> if 'Atomic' in aminame: <NEW_LINE> <INDENT> test_instance.skipTest('not run in Atomic AMIs') <NEW_LINE> <DEDENT> if is_fedora(test_instance): <NEW_LINE> <INDENT> release_file = 'fedora-release' <NEW_LI... | check if rhel provider matches /etc/redhat-release and ami name | 625941e06fb2d068a760f431 |
def gen_grep(pattern, lines): <NEW_LINE> <INDENT> pat = re.compile(pattern) <NEW_LINE> for n, line in enumerate(lines, 1): <NEW_LINE> <INDENT> if pat.search(line): <NEW_LINE> <INDENT> yield n, line | 匹配文件序列的全部行中内容 | 625941e08e7ae83300e4b35c |
def test_log_add_remove_stdout(): <NEW_LINE> <INDENT> log = pytan3.LOG.getChild("log11") <NEW_LINE> h = pytan3.utils.logs.add_stdout(obj=log) <NEW_LINE> assert h.name in [h.name for h in log.handlers] <NEW_LINE> pytan3.utils.logs.remove_stdout(obj=log) <NEW_LINE> assert h.name not in [h.name for h in log.handlers] | Test add/remove stdout. | 625941e091f36d47f21ac885 |
def __init__(self, l, v, r): <NEW_LINE> <INDENT> self._left = l <NEW_LINE> self._value = v <NEW_LINE> self._right = r <NEW_LINE> self._height = 1 | Construct of Node | 625941e031939e2706e4d1f4 |
def p_in_after_n(G, v, n, comm): <NEW_LINE> <INDENT> return p_in_after_n_r_cached(G, v, n, set(comm), {}) | Finds the probability that a particle will remain
within the community during every step of an
n step random walk, beginning from v. At each step,
the particle is equally likely to travel to any
of its neighbors.
TODO: use weights | 625941e0eab8aa0e5d26dee8 |
def searchDate(date: str, groups: list)->list: <NEW_LINE> <INDENT> raise NotImplementedError | This function should be capable of searching a douban group or multiple
groups' topics within a certain time period or date.
# Arguments
date: {type: str; formate: "yyyy-mm-dd"(str)}
groups: {type: [str, ...]} (list of url strings)
Returns a list to contain applied url strings. | 625941e0097d151d1a2231e6 |
def _schedule_write(self, handle, write_func, *args): <NEW_LINE> <INDENT> if self._mode == Scheduler._MODE_READONLY: <NEW_LINE> <INDENT> raise Exception( f"Write to object {handle._name} was scheduled during a read-only sync phase." ) <NEW_LINE> <DEDENT> if self._write_coro_inst is None: <NEW_LINE> <INDENT> self._write... | Queue `write_func` to be called on the next ReadWrite trigger. | 625941e0fff4ab517eb2f7cd |
def _validation_loss(self) -> Tuple[float, int]: <NEW_LINE> <INDENT> logger.info("Validating") <NEW_LINE> self._model.eval() <NEW_LINE> if self._validation_iterator is not None: <NEW_LINE> <INDENT> val_iterator = self._validation_iterator <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> val_iterator = self._iterator <NEW_... | Computes the validation loss. Returns it and the number of batches. | 625941e082261d6c526ab833 |
def empty(self): <NEW_LINE> <INDENT> return not bool(self.b) | Returns whether the stack is empty.
:rtype: bool | 625941e0ab23a570cc250514 |
def counting(self, lim): <NEW_LINE> <INDENT> if self.count > lim: <NEW_LINE> <INDENT> raise Exception("QF: CANNOT LOCATE INTEGRATION PARAMETERS") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.count = self.count + 1 | This module counts number of calls to ERRBD(), TRUNCN(), and CFE().
:param lim: Maximum number of integration terms
:return: | 625941e001c39578d7e751ca |
def __repr__(self): <NEW_LINE> <INDENT> context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) <NEW_LINE> return '<Connio.Api.V3.AlertContext {}>'.format(context) | Provide a friendly representation
:returns: Machine friendly representation
:rtype: str | 625941e0b7558d58953c529c |
def person(request, slug, active_tab=""): <NEW_LINE> <INDENT> person = get_object_or_404(Person, slug=slug, active=True) <NEW_LINE> meta = {} <NEW_LINE> tabs = PERSON_TABS(person, active_tab) <NEW_LINE> if active_tab: <NEW_LINE> <INDENT> if active_tab not in tabs.live_tabs: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> ... | Responsible for the person pages | 625941e0c4546d3d9de72dc6 |
def deleteDuplicates(self, head): <NEW_LINE> <INDENT> curr = head <NEW_LINE> while curr and curr.next: <NEW_LINE> <INDENT> if curr.val == curr.next.val: <NEW_LINE> <INDENT> curr.next = curr.next.next <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> curr = curr.next <NEW_LINE> <DEDENT> <DEDENT> return head | :type head: ListNode
:rtype: ListNode | 625941e05e10d32532c5f2b4 |
def _element_if_complete(element, complete=True): <NEW_LINE> <INDENT> return element if element.get_property('complete') == complete else False | Shortcut: 元素complete属性符合要求时,返回该元素
:param element: 指定元素
:param complete: 指定状态
:return: 状态符合时返回element | 625941e0236d856c2ad44b6e |
def basic_forest_no_categories(data): <NEW_LINE> <INDENT> original_data = data.select_dtypes(exclude='object') <NEW_LINE> y = original_data[['Survived']] <NEW_LINE> predictors = original_data.drop(['Survived'], axis=1) <NEW_LINE> train_X, test_X, train_y, test_y = train_test_split(predictors, y, test_size=0.1, random_s... | Use RandomForestRegression on numerical features only | 625941e063d6d428bbe4487f |
def __str__(self): <NEW_LINE> <INDENT> return self.username | Retrun Username | 625941e0cc0a2c11143dd221 |
def anagrams_cntr(str1: str, str2: str) -> bool: <NEW_LINE> <INDENT> c: Counter[str] = Counter(str1) <NEW_LINE> for ch in str2: <NEW_LINE> <INDENT> c[ch] -= 1 <NEW_LINE> <DEDENT> for key, value in c.items(): <NEW_LINE> <INDENT> if value == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> re... | anagrams_dd(str1, str2) that returns True if str1 and str2 are anagrams, False if not.
with Counter implementation | 625941e0cad5886f8bd27368 |
def get_review_metrics(record): <NEW_LINE> <INDENT> review_text = record[Constants.TEXT_FIELD] <NEW_LINE> log_sentences = math.log(len(nlp_utils.get_sentences(review_text)) + 1) <NEW_LINE> tagged_words = record[Constants.POS_TAGS_FIELD] <NEW_LINE> log_words = math.log(len(tagged_words) + 1) <NEW_LINE> counts = Counter(... | Returns a list with the metrics of a review. This list is composed
in the following way: [log(num_sentences + 1), log(num_words + 1),
log(num_past_verbs + 1), log(num_verbs + 1),
(log(num_past_verbs + 1) / log(num_verbs + 1))
:type record: dict
:param record: the review that wants to be analyzed, it should contain the... | 625941e03539df3088e2e6da |
def ordercancel(self, event): <NEW_LINE> <INDENT> cancelOrderReq = event.dict_ <NEW_LINE> self.request_id += self.inc_request_id() <NEW_LINE> pQryOder = ApiStructure.InputOrderActionField.from_dict({ "InstrumentID": cancelOrderReq.symbol, "ExchangeID": cancelOrderReq.exchange, "OrderRef": 1, "FrontID": cancelOrderReq.f... | 撤单 TODO:to be revised | 625941e0cc40096d61595cde |
def requirements(cfg): <NEW_LINE> <INDENT> reqs = {} <NEW_LINE> for name in cfg.installed_options(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> opt = available_options[name] <NEW_LINE> for dep in opt.require(cfg): <NEW_LINE> <INDENT> reqs[dep.name] = dep <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDEN... | Check all requirements for installed options.
Args:
cfg (Config): current package configuration
Returns:
(list): list of required packages | 625941e0a4f1c619b28b03c0 |
def _getaxes_ortho(self, idx_tuple): <NEW_LINE> <INDENT> axes = [] <NEW_LINE> for i, ix in enumerate(idx_tuple): <NEW_LINE> <INDENT> ax = self.axes[i][ix] <NEW_LINE> if np.ndim(ax) != 0: <NEW_LINE> <INDENT> axes.append(ax) <NEW_LINE> <DEDENT> <DEDENT> return axes | idx: tuple of position indices of length = ndim (orthogonal indexing) | 625941e07d847024c06be64e |
@tf_export('keras.backend.function') <NEW_LINE> def function(inputs, outputs, updates=None, name=None, **kwargs): <NEW_LINE> <INDENT> if ops.executing_eagerly_outside_functions(): <NEW_LINE> <INDENT> if kwargs: <NEW_LINE> <INDENT> raise ValueError('Session keyword arguments are not support during ' 'eager execution. Yo... | Instantiates a Keras function.
Arguments:
inputs: List of placeholder tensors.
outputs: List of output tensors.
updates: List of update ops.
name: String, name of function.
**kwargs: Passed to `tf.Session.run`.
Returns:
Output values as Numpy arrays.
Raises:
ValueError: if invalid kwargs ... | 625941e0dd821e528d63b535 |
def relaxation_voigt(J, tau, Jg, phi_f = 0.0, dt = 1, simul_t = 1, lw = 0): <NEW_LINE> <INDENT> if dt == 1: <NEW_LINE> <INDENT> dt = tau[0]/100.0 <NEW_LINE> <DEDENT> if simul_t ==1: <NEW_LINE> <INDENT> simul_t = tau[len(tau)-1]*10.0e3 <NEW_LINE> <DEDENT> J_a = [] <NEW_LINE> tau_a = [] <NEW_LINE> for i in range(len(J)):... | This function returns the numerical relaxation modulus of a Generalized Voigt model
This numerical relaxation modulus is useful for interconversion from Gen Maxwell model to generalized Voigt model
Parameters:
----------
J : numpy.ndarray
compliances of the springs in the Voigt units of a generalized Voigt ... | 625941e0d486a94d0b98e4d6 |
def write_codes(fn, nmf, bam_names): <NEW_LINE> <INDENT> with open(fn, "wb") as wh: <NEW_LINE> <INDENT> wh.write("\t".join(bam_names) + "\n") <NEW_LINE> for row in nmf: <NEW_LINE> <INDENT> wh.write("\t".join(map(str, list(row))) + "\n") | (internal) Writes codes to file.
| 625941e030c21e258bdfa82f |
def BinaryTree(rootVal): <NEW_LINE> <INDENT> return [rootVal, [], []] | implementing a binary tree using lists | 625941e0be383301e01b580e |
def test_all_documentation(self): <NEW_LINE> <INDENT> self.assertNotEqual(__import__("console").HBNBCommand .do_all.__doc__, None) | Test the documentation | 625941e0bf627c535bc1355f |
def test_lru_policy(self): <NEW_LINE> <INDENT> self.lru_cache.put('1', 1) <NEW_LINE> self.lru_cache.put('2', 2) <NEW_LINE> self.lru_cache.put('3', 3) <NEW_LINE> self.lru_cache.put('4', 2) <NEW_LINE> self.lru_cache.put('5', 3) <NEW_LINE> self.assertFalse(self.lru_cache.get('1')) <NEW_LINE> self.assertFalse(self.lru_cach... | Test LRU Eiction Policy by adding 2 items over capacity | 625941e0a17c0f6771cbe3df |
def _check_argument_types(self, spec=None, param=None): <NEW_LINE> <INDENT> if spec is None: <NEW_LINE> <INDENT> spec = self.argument_spec <NEW_LINE> <DEDENT> if param is None: <NEW_LINE> <INDENT> param = self.params <NEW_LINE> <DEDENT> for (k, v) in spec.items(): <NEW_LINE> <INDENT> wanted = v.get('type', None) <NEW_L... | ensure all arguments have the requested type | 625941e0a8ecb033257d345b |
def GetScalarProductPolVects(dyn1, dyn2, mode_exchange = None, mode_sign = None): <NEW_LINE> <INDENT> if dyn1.nqirr != 1: <NEW_LINE> <INDENT> raise ValueError("Error, this subroutine works only in the Gamma point") <NEW_LINE> <DEDENT> if not dyn1.CheckCompatibility(dyn2): <NEW_LINE> <INDENT> raise ValueError("Error, dy... | This subroutines computes the scalar product between all the
polarization vectors of the dynamical matrix. It is very usefull to
check if the associated mode is almost the same.
This subroutine checks also if the dynamical matrices are compatible
Also this subroutine works only at GAMMA
Parameters
----------
dyn1... | 625941e0a79ad161976cc4d5 |
@app.route('/') <NEW_LINE> def index(): <NEW_LINE> <INDENT> category_news = get_news('general') <NEW_LINE> print(category_news) <NEW_LINE> business_news = get_news('business') <NEW_LINE> sports_news = get_news('sports') <NEW_LINE> title = 'Home - Welcome to The best News Review Website Online' <NEW_LINE> return render_... | View root page function that returns the index page and its data | 625941e08e7ae83300e4b35d |
def doDestroyMe(self, *args, **kwargs): <NEW_LINE> <INDENT> from customer import supplier_connector <NEW_LINE> global _SupplierFinder <NEW_LINE> del _SupplierFinder <NEW_LINE> _SupplierFinder = None <NEW_LINE> if self.target_idurl: <NEW_LINE> <INDENT> sc = supplier_connector.by_idurl(self.target_idurl) <NEW_LINE> if sc... | Remove all references to the state machine object to destroy it. | 625941e00fa83653e4657348 |
def training_samples(num_zero_sum = 10000, num_wrong_sum = 10000) -> List[Tuple[Tuple[int, ...], bool]]: <NEW_LINE> <INDENT> L = [] <NEW_LINE> min_tup_length = 3 <NEW_LINE> max_tup_length = 5 <NEW_LINE> min_digit_count = 4 <NEW_LINE> max_digit_count = 9 <NEW_LINE> if num_zero_sum > 0: <NEW_LINE> <INDENT> L += [z... | Generate training samples of tuples of integers,
some of which "sum to zero" and some of which do not. | 625941e001c39578d7e751cb |
def smembers(self, key): <NEW_LINE> <INDENT> return self._items[key] if key in self._items else set() | Get all the members in a set. | 625941e063f4b57ef000149e |
def __init__(self, deleted_at=None, network_id=None, name=None, updated_at=None, model=None, ziti_id=None, owner_identity_id=None, attributes=None, model_type=None, id=None, config_id_by_config_type_id=None, created_at=None, created_by=None, deleted_by=None, encryption_required=None, authority=None, links=None, local_v... | InlineResponse2005 - a model defined in OpenAPI | 625941e0656771135c3ebc02 |
def cols_list(self): <NEW_LINE> <INDENT> cols = [] <NEW_LINE> conn = sqlite3.connect(db_path[0]) <NEW_LINE> c = conn.cursor() <NEW_LINE> data = c.execute("SELECT * FROM {}".format(current_table[0])) <NEW_LINE> for column in c.description: <NEW_LINE> <INDENT> cols.append(column[0]) <NEW_LINE> <DEDENT> return cols | Returns a list of all columns in a SQLite table | 625941e02eb69b55b151cc43 |
def __init__( self, monitoring_plugins, aggregator, tank, generator_plugin=None): <NEW_LINE> <INDENT> self.monitoring_plugins = monitoring_plugins <NEW_LINE> self.aggregator = aggregator <NEW_LINE> self.tank = tank <NEW_LINE> self._phantom_info = None <NEW_LINE> self.generator_plugin = generator_plugin | :type aggregator: TankAggregator
:type monitoring_plugins: list of | 625941e07d43ff24873a3032 |
def via_socket(func): <NEW_LINE> <INDENT> def send(self): <NEW_LINE> <INDENT> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> sock.connect(('127.0.0.1', self.port)) <NEW_LINE> try: <NEW_LINE> <INDENT> sock.sendall(json.dumps(func(self)).encode()) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> sock... | Send the output of the wrapped function to socket. | 625941e0fbf16365ca6f655a |
def replace_http(url): <NEW_LINE> <INDENT> def __remove_queries(data): <NEW_LINE> <INDENT> return data.split("/")[0] <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> url_list = url.split("//") <NEW_LINE> new_url = url_list[1] <NEW_LINE> return __remove_queries(new_url) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <IND... | replace the http in the url so we can get the IP address | 625941e0283ffb24f3c55c8d |
def event_return(events): <NEW_LINE> <INDENT> _options = _get_options() <NEW_LINE> for event in events: <NEW_LINE> <INDENT> log.trace('Hipchat returner received event: {0}'.format(event)) <NEW_LINE> _send_message(_options.get('room_id'), event['data'], _options.get('from_name'), _options.get('api_key'), _options.get('a... | Return event data to hipchat | 625941e0507cdc57c6307072 |
def dw_auth_required(sign_in_url=None): <NEW_LINE> <INDENT> def wrapper(view_func): <NEW_LINE> <INDENT> @wraps(view_func) <NEW_LINE> def _wrapped_view(request, *args, **kwargs): <NEW_LINE> <INDENT> dw = getattr(request, 'dw', None) <NEW_LINE> if dw and isinstance(dw, DW): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> re... | A decorator that restricts access to specified pages if user is not dw authorized.
As authorization url DW_AUTH_URL setting can be used if it is provided else default is used.
if any troubles then redirects to authorization page.
:param sign_in_url: is used in redirect call when is not None and nothing else where pro... | 625941e085dfad0860c3b1ec |
@curry <NEW_LINE> def map(f, xs): <NEW_LINE> <INDENT> if hasattr(xs, "fmap"): <NEW_LINE> <INDENT> return xs.fmap(f) <NEW_LINE> <DEDENT> return list(builtins.map(f, xs)) | >>> addOne = lambda x: x + 1
>>> map(addOne, [1, 2, 3, 4])
[2, 3, 4, 5]
>>> class Functor():
>>> def __init__(v):
>>> self.v = v
>>> def fmap(self, f):
>>> return Functor(f(self.v))
>>> map(lambda x: x * 3)(Functor(14)).v
42 | 625941e01f5feb6acb0c4eda |
def bet(self, player, bet): <NEW_LINE> <INDENT> self._update_bet(player, bet, 'Bet.') | Player places initial bet. | 625941e04e4d5625662d4763 |
def sync_file(src, dst, restore_files): <NEW_LINE> <INDENT> while islink(src): <NEW_LINE> <INDENT> src = os.readlink(src) <NEW_LINE> <DEDENT> if not mx.can_symlink(): <NEW_LINE> <INDENT> mx.ensure_dir_exists(dirname(dst)) <NEW_LINE> if exists(dst): <NEW_LINE> <INDENT> restore_files[dst] = _FileContentsSupplier(dst, eag... | Ensures that `dst` points at or contains the same contents as `src`.
:param dict restore_files: map from `dst` to a callable that will restore its original
content or to None should `dst` be deleted once the module-info.class has
been produced | 625941e0d99f1b3c44c67918 |
def get_emotion(self, word, pos): <NEW_LINE> <INDENT> if pos in self.flat_pos: <NEW_LINE> <INDENT> pos = self.flat_pos[pos] <NEW_LINE> synsets = self.wn16.synsets(word, self.wn_pos[pos]) <NEW_LINE> if synsets: <NEW_LINE> <INDENT> offset = synsets[0].offset() <NEW_LINE> if offset in self.synsets[pos]: <NEW_LINE> <INDENT... | Returns the emotion of the word.
word -- the word (str)
pos -- part-of-speech (str) | 625941e0ac7a0e7691ed4456 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.