code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def add_job(self, j, target='engrave'): <NEW_LINE> <INDENT> target_queue = self._queues.get(target, None) <NEW_LINE> if not target_queue: <NEW_LINE> <INDENT> raise ValueError(_("Invalid job queue target: {name}").format(name=target)) <NEW_LINE> <DEDENT> target_queue.add_job(j) | Add a job to the specified job queue. | 625941d392d797404e304368 |
def parse(self, text, context=None, substitutions=None): <NEW_LINE> <INDENT> if not substitutions: substitutions = {} <NEW_LINE> text = phrases.parse_all(text) <NEW_LINE> substitutions[settings.BOT_DISPLAY_NAME] = self.client.user.name <NEW_LINE> substitutions[settings.BOT_NAME] = self.client.user.display_name <NEW_LIN... | Interprets a string and formats accordingly, substitutes values, etc.
Args:
text(unicode): String to parse.
context(GeneralContext, optional): Current context of the message.
substitutions(dict, optional): Other substitutions to perform.
Replaces key with corresponding value.
Returns:
text(uni... | 625941d338b623060ff0afcb |
def load_sram_generator_tool(self, run_dir: str = "") -> bool: <NEW_LINE> <INDENT> if self.tech is None: <NEW_LINE> <INDENT> self.log.error("Must load technology before loading SRAM Generator tool") <NEW_LINE> return False <NEW_LINE> <DEDENT> if run_dir == "": <NEW_LINE> <INDENT> run_dir = os.path.join(self.obj_dir, "s... | Loads an SRAM Generator tool on a given database
:param run_dir: Directory to use for the tool run_dir. Defaults to the run_dir passed in the HammerDriver
constructor.
:return: True if SRAM Generator tool loading was successful, False otherwise. | 625941d37c178a314d6ef63f |
def __init__(self, repo, binsha, mode=None, path=None, name=None, parent_commit=None, url=None, branch_path=None): <NEW_LINE> <INDENT> super(Submodule, self).__init__(repo, binsha, mode, path) <NEW_LINE> self.size = 0 <NEW_LINE> if parent_commit is not None: <NEW_LINE> <INDENT> self._parent_commit = parent_commit <NEW_... | Initialize this instance with its attributes. We only document the ones
that differ from ``IndexObject``
:param repo: Our parent repository
:param binsha: binary sha referring to a commit in the remote repository, see url parameter
:param parent_commit: see set_parent_commit()
:param url: The url to the remote reposit... | 625941d3236d856c2ad449b9 |
def request_wants_json(): <NEW_LINE> <INDENT> if flask.request.args.get('format') == 'json': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif flask.request.args.get('format') == 'html': <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> best = flask.request.accept_mimetypes .best_match(['application/ld... | Determine from the request headers whether this is a Web browser that wants
pretty rendering, or an API user that wants actual JSON-LD. | 625941d30fa83653e4657198 |
def __init__(self, M0, C0, K0, nonlin, NH=3, npow2=8, nu=1, scale_x=1, scale_t=1, amp0=1e-3, tol_NR=1e-6, max_it_NR=15, stability=True, rcm_permute=False, anim=True, xstr='Hz', sca=1/(2*np.pi)): <NEW_LINE> <INDENT> self.NH = NH <NEW_LINE> self.npow2 = npow2 <NEW_LINE> self.nu = nu <NEW_LINE> self.scale_x = scale_x <NEW... | Because frequency(in rad/s) and amplitude have different orders of
magnitude, time and displacement have to be rescaled to avoid
ill-conditioning.
Parameters
----------
Harmonic balance parameters:
NH: number of harmonic retained in the Fourier series
npow: number of time samples in the Fourier transform, ie. 2^8=256
... | 625941d326068e7796caeebe |
@attr('ctp') <NEW_LINE> def test_open_position_with_stop_price(): <NEW_LINE> <INDENT> assert False | 打开头寸的同时使用止损价格,并触发止损价格使头寸关闭
NOTE: CTP似乎不支持止损价格,这里是CTPTrader接口模拟的 | 625941d330c21e258bdfa67b |
def unprocess_payload(sysid, payload, key=None): <NEW_LINE> <INDENT> if not key: <NEW_LINE> <INDENT> key = get_key(sysid) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> decrypted_payload = rc4_decrypt(key, payload) <NEW_LINE> <DEDENT> except UnicodeDecodeError: <NEW_LINE> <INDENT> raise DecryptionError('Could not decrypt... | RC4 decrypts the 'unprepared' payload. | 625941d332920d7e50b283af |
def create_ext_df(self, max_iter=150): <NEW_LINE> <INDENT> total_weeks = self.train_weeks + self.pred_weeks <NEW_LINE> ext_df = pd.DataFrame(0, index=range(0, total_weeks), columns=['t', 'ext', '2F1', 'z']) <NEW_LINE> ext_df['t'] = ext_df.apply(lambda x: x +1/7.).cumsum() <NEW_LINE> ext_df['z'] = ext_df.t.apply(lambda ... | - EXt = the expected number of transactions for a randomly-chosen individual in a time period of length t given r, alpha, a and b
- returns df with the gaussian hypergeometric cost function for every day
Iterates untill uj is close to 0 or maximum iterations is reached | 625941d3b545ff76a8913ff3 |
def close(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.unlink(self.filename) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> run_gimp_script( MULTI_LAYER_SCRIPT.format( layers=' '.join( quote_string(s) for (s, _) in self._layers), titles=' '.join( quot... | Combines the written figuers into a multi-layer GIMP file | 625941d391af0d3eaac9bbf8 |
def test_scaninfo(self): <NEW_LINE> <INDENT> opts = self.default_options <NEW_LINE> opts['__modules__'] = dict() <NEW_LINE> sfwebui = SpiderFootWebUi(self.web_default_options, opts) <NEW_LINE> scan_info = sfwebui.scaninfo("example scan instance") <NEW_LINE> self.assertIsInstance(scan_info, str) | Test scaninfo(self, id) | 625941d356ac1b37e62643ab |
def test_bbb_build_frame_container(): <NEW_LINE> <INDENT> fco = build_frame_container(0, 1, 0) <NEW_LINE> assert fco.camId == 0 <NEW_LINE> assert fco.fromTimestamp == 0 <NEW_LINE> assert fco.toTimestamp == 1 <NEW_LINE> ts1 = to_timestamp(datetime(1970, 1, 1, tzinfo=pytz.utc)) <NEW_LINE> ts2 = to_timestamp(datetime(2015... | Tests the generation of a ``FrameContainer`` via function. | 625941d30a366e3fb873e9f9 |
def test_STUDENT_ID_OR_PERSONNEL_ID_INCORRECT_MESSAGE (self): <NEW_LINE> <INDENT> self.assertTrue("STUDENT_ID_OR_PERSONNEL_ID_INCORRECT_MESSAGE" in globals().keys()) | Test to see if STUDENT_ID_OR_PERSONNEL_ID_INCORRECT_MESSAGE exists after being imported | 625941d3090684286d50eec4 |
def calc_pm(c, t): <NEW_LINE> <INDENT> if not t or c != t['date_str']: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if half_end_time < t['time_obj'] <= end_time: <NEW_LINE> <INDENT> return 4 <NEW_LINE> <DEDENT> return 0 | 计算下午工作时间
有一次提交默认为下午工作
:return: | 625941d3cb5e8a47e48b7c86 |
def test_print(self): <NEW_LINE> <INDENT> str_string = "Detection {'', [0, 0, 0, 0], 0.0%}" <NEW_LINE> self.assertEqual(str(self.det), str_string) | Test annotation __str__ function | 625941d3b57a9660fec33a64 |
def setting(self, name, default=NoDefault): <NEW_LINE> <INDENT> return self.model().setting(name, default) | Return the value of a particular configuration setting taken from the model.
Implementation note: Perhaps a future version should ask the klass and so on up the chain. | 625941d34e4d5625662d45b4 |
def invSym(*args): <NEW_LINE> <INDENT> return _spams_wrap.invSym(*args) | invSym(Matrix< double > * A)
invSym(Matrix< float > * A) | 625941d38e05c05ec3eea554 |
def _is_post_parameters_ok(self): <NEW_LINE> <INDENT> if self.message is None: <NEW_LINE> <INDENT> raise MissingParameterException("Facebook POST needs a message") <NEW_LINE> <DEDENT> return True | Check if parameters required to POST a message are present.
:return: True, if parameters are OK, raise exception otherwise.
.. raises:: MissingParameterException | 625941d38c0ade5d55d3eb99 |
def set_axis_color(self, row_index, col_index, is_main, color): <NEW_LINE> <INDENT> axis = self._myCanvas.get_axis(row_index, col_index, is_main) <NEW_LINE> if is_main: <NEW_LINE> <INDENT> side = 'left' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> side = 'right' <NEW_LINE> <DEDENT> axis.spines[side].set_color(color) | set the color of axis
:param row_index:
:param col_index:
:param is_main:
:param color:
:return: | 625941d3851cf427c661a6eb |
def recv_packet(self, packet): <NEW_LINE> <INDENT> raise NotImplementedError("recv_packet() not implemented") | Receives a packet from the other party.
:param packet: the packet
:return: has the packet been handled? | 625941d31f5feb6acb0c4d2c |
def next_element( self, ) -> tuple[Optional[VertexID], Any, frozenset[VertexID]]: <NEW_LINE> <INDENT> if not self.non_visited: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> result = next((k for k in self.non_visited if self.pred_number[k] == 0), None) <NEW_LINE> if result is None: <NEW_LINE> <INDENT> if n... | Retrieve next element in topological order.
:return: a vertex id, data, predecessors. (None, None, frozenset()) is
returned if no element is available). | 625941d3ab23a570cc250361 |
def test_sub_pixel(ellip,theta): <NEW_LINE> <INDENT> import fimage <NEW_LINE> import images <NEW_LINE> sigma_vals = linspace(1.0,3.0,10) <NEW_LINE> nsub_vals = array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],dtype='i4') <NEW_LINE> data = subpixel_struct(sigma_vals.size, nsub_vals.size) <NEW_LINE> ct=0 <NEW_LINE> amt=0 <... | Round objects for now | 625941d330bbd722463cbfa5 |
def createProjectedProduct(self, mapInfo, name, desc): <NEW_LINE> <INDENT> return Product(Product_createProjectedProduct(self._obj, mapInfo._obj, name, desc)) | Creates a map-projected version of this product.
@param mapInfo the map information
@param name the name for the new product
@param desc the description for the new product
@return the product subset, or <code>null</code> if the product/subset combination is not valid
@throws IOException if an I/O error occurs | 625941d3a79ad161976cc323 |
def TT_tenvecs_product(cores, xs): <NEW_LINE> <INDENT> res = None <NEW_LINE> for c,x in zip(cores[:len(xs)],xs): <NEW_LINE> <INDENT> if res is None: <NEW_LINE> <INDENT> res = np.tensordot(c,x,axes=(1,0)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res = np.tensordot(res,c,axes=(1,0)) <NEW_LINE> res = np.tensordot(res... | perform the prodcut H imes_1 x1 imes_2 x2 imes_3 x3 ...
where cores are the cores of the TT decomposition of H and
xs = [x1,x2,x3,...] is the input sequence | 625941d3dc8b845886cb5714 |
def calc_time_diff(x, y): <NEW_LINE> <INDENT> scheduled = convert_to_minofday(x) <NEW_LINE> actual = convert_to_minofday(y) <NEW_LINE> return actual - scheduled | Calculates delay times y - x
Args:
x (float64): array of scheduled time given in military format.
Takes on values in 0.0-2359.0 due to float64 representation.
y (float64): array of same dimensions giving actual time
Returns:
array (float64): array of input dimension with delay time | 625941d3187af65679ca52fd |
def __idiv__(self, other): <NEW_LINE> <INDENT> return self.__itruediv__(other) | interne Division für Python 2.x
:param Bruch other: other Bruch
:return: self | 625941d35e10d32532c5f104 |
def _load_app_settings(self): <NEW_LINE> <INDENT> data = appsettings.load_app_settings() <NEW_LINE> account_info, deletion_filters, storing_filters = data <NEW_LINE> if account_info: <NEW_LINE> <INDENT> server_info, user_info = account_info <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> server_info = '', 0, '110' <NEW_L... | Load application settings from home directory. | 625941d356ac1b37e62643ac |
def save_draft(account_id, message_id, db_session): <NEW_LINE> <INDENT> account = db_session.query(Account).get(account_id) <NEW_LINE> message = db_session.query(Message).get(message_id) <NEW_LINE> assert message.is_draft <NEW_LINE> recipients = Recipients(message.to_addr, message.cc_addr, message.bcc_addr) <NEW_LINE> ... | Sync a new/updated draft back to the remote backend. | 625941d33317a56b86939e33 |
@misc_tools.set_attributes(i=0) <NEW_LINE> def counting_func(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return counting_func.i <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> counting_func.i += 1 | Return a bigger number every time. | 625941d391f36d47f21ac6d1 |
def get_ldbws_status(): <NEW_LINE> <INDENT> page = urllib2.urlopen("http://realtime.nationalrail.co.uk/OpenLDBWSRegistration/").read() <NEW_LINE> status_soup = BeautifulSoup(page, "lxml") <NEW_LINE> status_elm = status_soup.findAll("span") <NEW_LINE> status_text = status_elm[0].findAll(text=True) <NEW_LINE> return stat... | This function retreives the url for the OpenLDBWS status and returns
a string of the value it contains.
Currently the way this is built is very fragile, as any changes in
the website would break it. Good thing is, the website will rarely change... | 625941d3460517430c394360 |
def has_physical_port(self, location): <NEW_LINE> <INDENT> location = self._canonize(location) <NEW_LINE> has = location in self.port_map <NEW_LINE> if has: <NEW_LINE> <INDENT> return has <NEW_LINE> <DEDENT> return self.try_connect(location) | True if the location has a physical port | 625941d399cbb53fe6792dc5 |
def search_urls(text, exclusion_char=None, clean=False, schemes=None): <NEW_LINE> <INDENT> schemes = schemes or ['http', 'https', 'ftp'] <NEW_LINE> schemes_patterns = '|'.join(re.escape(scheme) for scheme in schemes) <NEW_LINE> re_url = r'((?:%s)(?::\/\/\S+))' % schemes_patterns <NEW_LINE> if exclusion_char is not None... | Extracts all URLs in ``text``.
:param str text: the text to search for URLs
:param str exclusion_char: optional character that, if placed before a URL
in the ``text``, will exclude it from being extracted
:param bool clean: if ``True``, all found URLs are passed through
:py:func:`~.trim_url` before being retur... | 625941d3be7bc26dc91cd7dc |
def make_new_images(self): <NEW_LINE> <INDENT> if len(self.new_old_field_nums) > 0: <NEW_LINE> <INDENT> dirs = self.get_make_directories() <NEW_LINE> if dirs is not None: <NEW_LINE> <INDENT> for dirpath, dirnames, filenames in os.walk(dirs['src']): <NEW_LINE> <INDENT> for filename in filenames: <NEW_LINE> <INDENT> src_... | makes new image versions with new file names
by walking the directory to find image files | 625941d3ac7a0e7691ed42a8 |
def check_is_local_file(input_file: str) -> str: <NEW_LINE> <INDENT> if os.path.isfile(input_file): <NEW_LINE> <INDENT> with open(input_file, 'r', newline='') as localfile: <NEW_LINE> <INDENT> content = localfile.read() <NEW_LINE> return content <NEW_LINE> <DEDENT> <DEDENT> return False | Check if the passed para is a valid file. | 625941d385dfad0860c3b039 |
def _right_speed(self, speed): <NEW_LINE> <INDENT> assert 0 <= speed <= 255, 'Speed must be a value between 0 to 255 inclusive!' <NEW_LINE> front_speed = speed + self._front_right_trim <NEW_LINE> rear_speed = speed + self._rear_right_trim <NEW_LINE> front_speed = max(0, min(255, speed)) <NEW_LINE> rear_speed = max(0, m... | Set the speed of the right motor, taking into account its trim offset.
| 625941d3d99f1b3c44c6776b |
def set_location_property_separately(self, botengine, additional_property_name, additional_property_json, overwrite=False, timestamp_ms=None): <NEW_LINE> <INDENT> if timestamp_ms is None: <NEW_LINE> <INDENT> additional_properties = self.get_location_property(botengine, 'additional_properties') <NEW_LINE> if additional_... | Set a large location property. The name is referenced by our 'location_properties' but stored separately
and referenced in the location_properties as 'additional_properties'.
You must use botengine.get_ui_content(..) when retrieving the content of this additional property,
since it is referenced by the 'location_prope... | 625941d3d8ef3951e324371c |
def add_minutes(self, minutes=1): <NEW_LINE> <INDENT> self.minute += minutes <NEW_LINE> self.time_passed += minutes <NEW_LINE> if self.minute >= 60: <NEW_LINE> <INDENT> if self.minute == 60: <NEW_LINE> <INDENT> self.hour += 1 <NEW_LINE> self.minute = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> over = self.minute - ... | Adds passed minutes to the clock.
Time: O(1) | 625941d3be383301e01b5662 |
def __init__( self, *, created_by: Optional[str] = None, created_by_type: Optional[Union[str, "CreatedByType"]] = None, created_at: Optional[datetime.datetime] = None, last_modified_by: Optional[str] = None, last_modified_by_type: Optional[Union[str, "CreatedByType"]] = None, last_modified_at: Optional[datetime.datetim... | :keyword created_by: The identity that created the resource.
:paramtype created_by: str
:keyword created_by_type: The type of identity that created the resource. Possible values
include: "User", "Application", "ManagedIdentity", "Key".
:paramtype created_by_type: str or
~open_energy_platform_management_service_apis.m... | 625941d3046cf37aa974cf25 |
def detach(self): <NEW_LINE> <INDENT> self._device.ctrl_transfer(0x21, Request.DETACH, 0, 0, None) | Detaches from the DFU target. | 625941d34d74a7450ccd43a1 |
def _python_to_mod_modify(changes: Changeset) -> Dict[str, List[Tuple[Operation, List[bytes]]]]: <NEW_LINE> <INDENT> table: LdapObjectClass = type(changes.src) <NEW_LINE> changes = changes.changes <NEW_LINE> result: Dict[str, List[Tuple[Operation, List[bytes]]]] = {} <NEW_LINE> for key, l in changes.items(): <NEW_LINE>... | Convert a LdapChanges object to a modlist for a modify operation. | 625941d35f7d997b87174c77 |
def clean_telephone_number(self, s, area_code=None): <NEW_LINE> <INDENT> splits = re.split(r'(?:\b \(|/|x|ext[.:]?|p\.|poste)[\s-]?(?=\b|\d)', s, flags=re.IGNORECASE) <NEW_LINE> digits = re.sub(r'\D', '', splits[0]) <NEW_LINE> if len(digits) == 7 and area_code: <NEW_LINE> <INDENT> digits = '1' + str(area_code) + digits... | @see http://www.btb.termiumplus.gc.ca/tpv2guides/guides/favart/index-eng.html?lang=eng&lettr=indx_titls&page=9N6fM9QmOwCE.html | 625941d3435de62698dfde2b |
def test_error_when_no_pattern_but_additional_expressions(self): <NEW_LINE> <INDENT> ioerr = StringIO() <NEW_LINE> with contextlib.redirect_stderr(ioerr): <NEW_LINE> <INDENT> with self.assertRaises(SystemExit) as e: <NEW_LINE> <INDENT> u = self.get_output(["-E", "1", "examples/dummy.csv"]) <NEW_LINE> <DEDENT> <DEDENT> ... | "todo, maybe redundant | 625941d3ad47b63b2c50a15e |
def _generic_response_handler(self, resp, prompt): <NEW_LINE> <INDENT> return resp, prompt | Pass through response handler
@param resp: response
@param prompt: prompt
@return: (response, prompt) | 625941d301c39578d7e7501a |
def sparse_column_with_integerized_feature(column_name, bucket_size, combiner=None, dtype=dtypes.int64): <NEW_LINE> <INDENT> if combiner is None: <NEW_LINE> <INDENT> logging.warn("The default value of combiner will change from \"sum\" " "to \"sqrtn\" after 2016/11/01.") <NEW_LINE> combiner = "sum" <NEW_LINE> <DEDENT> r... | Creates an integerized _SparseColumn.
Use this when your features are already pre-integerized into int64 IDs, that
is, when the set of values to output is already coming in as what's desired in
the output. Integerized means we can use the feature value itself as id.
Typically this is used for reading contiguous range... | 625941d3a8ecb033257d32ab |
def test_publisher_proxies(self): <NEW_LINE> <INDENT> self.image_create(self.rurl) <NEW_LINE> self.pkg("publisher test") <NEW_LINE> self.assertTrue("Proxy:" not in self.output) <NEW_LINE> for add, remove in [("-g", "-G"), ("-m", "-M")]: <NEW_LINE> <INDENT> self.image_create(self.rurl) <NEW_LINE> self.pkg("set-publisher... | Tests that set-publisher can add and remove proxy values
per origin. | 625941d32eb69b55b151ca8f |
def add_gene_family_to_graph(self, family_id): <NEW_LINE> <INDENT> family = Family(self.graph) <NEW_LINE> gene_family = self.globaltt['gene_family'] <NEW_LINE> self.model.addIndividualToGraph( family_id, None, gene_family, ind_category=blv.terms['GeneFamily'] ) <NEW_LINE> family.addMember( family_id, self.sub, group_ca... | Make an association between a group of genes and some grouping class.
We make the assumption that the genes in the association
are part of the supplied family_id, and that the genes have
already been declared as classes elsewhere.
The family_id is added as an individual of type DATA:gene_family.
Triples:
<family_id> a... | 625941d30383005118ecf7c0 |
@register.assignment_tag <NEW_LINE> def xcontent_status(): <NEW_LINE> <INDENT> return get_completed() | возвращает то насколько сайт наполнен (требует конфигурирования) | 625941d34e696a04525c962a |
def run(pvdb, *, interfaces=None, log_pv_names=False, startup_hook=None): <NEW_LINE> <INDENT> loop = asyncio.get_event_loop() <NEW_LINE> task = loop.create_task( start_server(pvdb, interfaces=interfaces, log_pv_names=log_pv_names, startup_hook=startup_hook)) <NEW_LINE> try: <NEW_LINE> <INDENT> loop.run_until_complete(t... | Run an IOC, given its PV database dictionary.
A synchronous function that wraps start_server and exits cleanly.
Parameters
----------
pvdb : dict
The PV database.
interfaces : list, optional
List of interfaces to listen on.
log_pv_names : bool, optional
Log PV names at startup.
startup_hook : coroutine... | 625941d332920d7e50b283b0 |
def construct_docstring(declaration, indent=0): <NEW_LINE> <INDENT> docstring = "" <NEW_LINE> try: <NEW_LINE> <INDENT> typename, name, params = declaration <NEW_LINE> lines = [] <NEW_LINE> lines.append('"""[description]\n\n') <NEW_LINE> if typename == "class": <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif typename ... | @summary: construct docstring according to the declaration
@param declaration: the result of parse_declaration() reurns
@param indent: the indent space number | 625941d321a7993f00bc7ed0 |
def setup(): <NEW_LINE> <INDENT> GPIO.setmode(GPIO.BCM) <NEW_LINE> GPIO.setup(all_channels, GPIO.IN, pull_up_down=GPIO.PUD_UP) | Initial setup. | 625941d3e1aae11d1e749e97 |
@app.before_first_request <NEW_LINE> def setup_logging(): <NEW_LINE> <INDENT> if not app.debug: <NEW_LINE> <INDENT> app.logger.addHandler(logging.StreamHandler()) <NEW_LINE> app.logger.setLevel(logging.INFO) | setup logging so we can actually see whats happening | 625941d3d164cc6175782f2d |
def test_create(self): <NEW_LINE> <INDENT> self.stub_out('nova.compute.api.API.volume_snapshot_create', fakes.stub_compute_volume_snapshot_create) <NEW_LINE> subs = { 'volume_id': '521752a6-acf6-4b2d-bc7a-119f9148cd8c', 'snapshot_id': '421752a6-acf6-4b2d-bc7a-119f9148cd8c', 'type': 'qcow2', 'new_file': 'new_file_name' ... | Create a volume snapshots. | 625941d3711fe17d82542548 |
def KSY_precondition(self, matrix): <NEW_LINE> <INDENT> if matrix.is_zero_matrix: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> m, n = matrix.shape <NEW_LINE> matrix = simplify(matrix.rref()[0]) <NEW_LINE> rows = [i for i in range(m) if any(matrix[i, j] != 0 for j in range(n))] <NEW_LINE> matrix = matrix[rows,:]... | Test for the validity of the Kapur-Saxena-Yang precondition.
The precondition requires that the column corresponding to the
monomial 1 = x_1 ^ 0 * x_2 ^ 0 * ... * x_n ^ 0 is not a linear
combination of the remaining ones. In sympy notation this is
the last column. For the precondition to hold the last non-zero
row of ... | 625941d3377c676e91272387 |
def disconnect(self): <NEW_LINE> <INDENT> self._mac = None | Disconnect from sensor.
Connection handling is not required when using gatttool. | 625941d382261d6c526ab67f |
def exec_sql_in_db(cmd, **kwargs): <NEW_LINE> <INDENT> password = get_db_password() <NEW_LINE> log.debug('Using password %s', password) <NEW_LINE> cmd = 'mysql -uroot -p\'{password}\' -B -t -e "{cmd}" {db}'.format( cmd=cmd, db=DB_NAME, password=password) <NEW_LINE> for line in exec_in_container('db', cmd, **kwargs): <N... | Run a SQL command in the database | 625941d3b7558d58953c50f1 |
def test_colored(self): <NEW_LINE> <INDENT> with OutputIO() as buf: <NEW_LINE> <INDENT> with redirect_stdout(buf): <NEW_LINE> <INDENT> l= LogConsole(show_verbose=False, show_debug=False, color=True) <NEW_LINE> l.verbose("verbose") <NEW_LINE> l.debug("debug") <NEW_LINE> <DEDENT> with redirect_stdout(buf): <NEW_LINE> <IN... | test with color output | 625941d33317a56b86939e34 |
def compute_latency(frames): <NEW_LINE> <INDENT> avg_latency = defaultdict(list) <NEW_LINE> anomaly_cnt = 0 <NEW_LINE> for frame in frames: <NEW_LINE> <INDENT> latencies = defaultdict(list) <NEW_LINE> for trial in frame['retries']: <NEW_LINE> <INDENT> _, _, last_stamp = trial[0] <NEW_LINE> last_op_stamp = -1 <NEW_LINE>... | Computue additional data on each frame | 625941d321bff66bcd684b30 |
def create_code_cell (cell_name, code): <NEW_LINE> <INDENT> cell = nbf.v4.new_code_cell(code) <NEW_LINE> cell.metadata["name"] = cell_name <NEW_LINE> return cell | create a code cell | 625941d3cc0a2c11143dd06f |
def unique_freq(self): <NEW_LINE> <INDENT> unique_freq = [] <NEW_LINE> for i in self.timestamp: <NEW_LINE> <INDENT> if self.state_time_map[i] not in unique_freq and self.state_time_map[i] != self.UNKNOWNSTATE: <NEW_LINE> <INDENT> unique_freq.append(self.state_time_map[i]) <NEW_LINE> <DEDENT> <DEDENT> for i in self.mini... | Determine the unique Frequency and state | 625941d382261d6c526ab680 |
def findNumberOfLIS(self, nums): <NEW_LINE> <INDENT> if len(nums) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> m = [0 for i in range(len(nums))] <NEW_LINE> count = [0 for i in range(len(nums))] <NEW_LINE> maxSoFar = 0 <NEW_LINE> ans = 0 <NEW_LINE> for i in range(len(nums) - 1, -1, -1): <NEW_LINE> <INDENT> m[i... | :type nums: List[int]
:rtype: int | 625941d3596a897236089c9e |
def _handle_bind_resource(self, features): <NEW_LINE> <INDENT> log.debug("Requesting resource: %s", self.xmpp.boundjid.resource) <NEW_LINE> iq = self.xmpp.Iq() <NEW_LINE> iq['type'] = 'set' <NEW_LINE> iq.enable('bind') <NEW_LINE> if self.xmpp.boundjid.resource: <NEW_LINE> <INDENT> iq['bind']['resource'] = self.xmpp.bou... | Handle requesting a specific resource.
Arguments:
features -- The stream features stanza. | 625941d30383005118ecf7c1 |
def test_add_user_duplicate_email(self): <NEW_LINE> <INDENT> with self.client: <NEW_LINE> <INDENT> self.client.post( '/users', data=json.dumps({ 'username': 'vannesschancc', 'email': 'vannesschancc@live.com', 'password': 'greaterthaneight' }), content_type='application/json', ) <NEW_LINE> response = self.client.post( '... | Ensure error is thrown if the email already exists. | 625941d3462c4b4f79d1d8af |
def test_handle_does_not_exist(self): <NEW_LINE> <INDENT> pass | Test if service handles DoesNotExistExceptions. | 625941d30fa83653e4657199 |
def vectorDistance(vector1, vector2): <NEW_LINE> <INDENT> return math.sqrt(math.pow((vector2.x - vector1.x), 2) + math.pow((vector2.y - vector1.y), 2)) | Return the distance between vectors. | 625941d3bde94217f3682fcf |
def find_item(self, condition=None, db_name=None, collection_name=None): <NEW_LINE> <INDENT> if condition is None: <NEW_LINE> <INDENT> condition = {} <NEW_LINE> <DEDENT> if db_name is not None: <NEW_LINE> <INDENT> self._db = self._client[db_name] <NEW_LINE> <DEDENT> if collection_name is not None: <NEW_LINE> <INDENT> s... | To search a document in MongoDB
Args:
condition (dict): search parameter
db_name (str):
collection_name (str):
Returns:
document : | 625941d3e64d504609d74a1f |
def test_timeout_timeout(self): <NEW_LINE> <INDENT> a = MockAgent(self, commands = [("isdir /mnt/sdcard/tests", "TRUE"), ("cd /mnt/sdcard/tests", ""), ("ls", "test.txt"), ("rm /mnt/sdcard/tests/test.txt", 0)]) <NEW_LINE> d = mozdevice.DroidSUT("127.0.0.1", port=a.port, debugLevel=mozlog.DEBUG) <NEW_LINE> d.default_time... | Tests DeviceManager timeout, timeout case. | 625941d3bd1bec0571d9080f |
def topological_sort(self): <NEW_LINE> <INDENT> graph_unsorted = self.tasks[:] <NEW_LINE> graph_sorted = [] <NEW_LINE> if len(self.tasks) == 0: <NEW_LINE> <INDENT> return tuple(graph_sorted) <NEW_LINE> <DEDENT> while graph_unsorted: <NEW_LINE> <INDENT> acyclic = False <NEW_LINE> for node in list(graph_unsorted): <NEW_L... | Sorts tasks in topographical order, such that a task comes after any of its
upstream dependencies.
Heavily inspired by:
http://blog.jupo.org/2012/04/06/topological-sorting-acyclic-directed-graphs/
:returns: list of tasks in topological order | 625941d331939e2706e4d048 |
def write_data_to_tfrecord(is_training=True, chunkify=False): <NEW_LINE> <INDENT> kind = "train" if is_training else "test" <NEW_LINE> print("Start writing affnist {} data.".format(kind)) <NEW_LINE> start = time.time() <NEW_LINE> if is_training: <NEW_LINE> <INDENT> images = np.load("data/affnist/train-images.npy") <NEW... | Adapted from https://github.com/www0wwwjs1/Matrix-Capsules-EM-Tensorflow/blob/master/data/smallNORB.py | 625941d3956e5f7376d7104b |
def get_query_set(self): <NEW_LINE> <INDENT> return (super(LanguageManager, self). get_query_set(). filter(language__exact=best_languange)) | Overrides the default ``QuerySet`` to only include rows
with the current best language. | 625941d33d592f4c4ed1d24a |
def log(self, txt, dt=None): <NEW_LINE> <INDENT> dt = dt or self.simulate.datas[0].date[0] <NEW_LINE> print('%s, %s' % (dt, txt)) | Logging function fot this strategy | 625941d330bbd722463cbfa6 |
def __init__(self, resolution=(120, 160), nb_frames=1, actions=[], depth_radius=1.0, depth_contrast=0.8, distilled=False): <NEW_LINE> <INDENT> self.resolution = resolution <NEW_LINE> self.actions = actions <NEW_LINE> self.nb_actions = len(actions) <NEW_LINE> self.nb_frames = nb_frames <NEW_LINE> self.depth_radius = dep... | DQN models have the following network architecture:
- Input : (# of previous frames, img_width, img_length)
- ConvLayer: 32 filters, 8x8 filter size, 4x4 stride, rectifier activation
- ConvLayer: 64 filters, 5x5 filter size, 4x4 stride, rectifier activation
- FullyConnectedLayer : 4032 nodes with 0.5 dropout rate
- Out... | 625941d3d10714528d5ffec4 |
def campaign_files(_campaign, cache_directory=None): <NEW_LINE> <INDENT> Campaign = namedtuple( 'Campaign', 'history_file thunderbird_file campaign cache_directory') <NEW_LINE> regex = re.compile('[^A-Za-z0-9 ]+') <NEW_LINE> if bool(cache_directory) is False: <NEW_LINE> <INDENT> cache_directory = os.path.abspath(os.pat... | Create the names of files used to track the email campaign.
Args:
_campaign: Campaign name
cache_directory: Directory where the campaign files are stored.
Returns:
result: Campaign object | 625941d3498bea3a759b9c8e |
def _record_items(lib, items): <NEW_LINE> <INDENT> m3u_path = _get_m3u_path(lib) <NEW_LINE> with open(m3u_path, 'a') as f: <NEW_LINE> <INDENT> for item in items: <NEW_LINE> <INDENT> path = os.path.relpath(item.path, os.path.dirname(m3u_path)) <NEW_LINE> f.write(path + '\n') | Records relative paths to the given items in the appropriate M3U
file. | 625941d38a43f66fc4b54243 |
def add_states(self, states): <NEW_LINE> <INDENT> back_states = self.states.copy() <NEW_LINE> back_final = self.final.copy() <NEW_LINE> if isinstance(states, list) or isinstance(states, set) or isinstance(states, tuple) or isinstance(states, frozenset): <NEW_LINE> <INDENT> for state in states: <NEW_LINE> <INDENT> if se... | Add states to automaton. States can be list, tuple, set and frozen set of states objects. States can also be an an state object (object of b_State class or class derived from b_State class). If state is final its added to the final set of automaton. If state can not be added due an id collision exception is raised and ... | 625941d36fb2d068a760f27e |
def load(self): <NEW_LINE> <INDENT> if self.isTransferring(): <NEW_LINE> <INDENT> logger.debug('File Transfer Thread active, please wait for transfer thread to end') <NEW_LINE> return None <NEW_LINE> <DEDENT> with self._commandLock: <NEW_LINE> <INDENT> self._beeCon.sendCmd("M701\n", "3") <NEW_LINE> return | load method
performs load filament operation | 625941d35fc7496912cc3b5d |
def test_getonemeal_endpoint(self): <NEW_LINE> <INDENT> response = self.app.post('/api/v1/meals', data=json.dumps(self.meal4), content_type='application/json', headers={'x-access-token':self.token}) <NEW_LINE> self.assertEqual(response.status_code, 201) <NEW_LINE> data = json.loads(response.get_data()) <NEW_LINE> resul... | Test API endpoint can get one meal given the meal id | 625941d32ae34c7f2600d310 |
def __eq__(self, other: 'AccumulatedFiltersCatalogFiltersItemCatalog') -> bool: <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Return `true` when self and other are equal, false otherwise. | 625941d3236d856c2ad449bb |
def get_endpoints_credentials(): <NEW_LINE> <INDENT> user = endpoints.get_current_user() <NEW_LINE> if not user: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not 'HTTP_AUTHORIZATION' in os.environ: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> token = os.environ['HTTP_AUTHORIZATION'].split(' ').pop() ... | Gets the oauth2 credentials from the user authenticated to Google Cloud Endpoints.
Presently, this does not work for Android and iOS clients. We are open to patches to fix it. | 625941d36fece00bbac2d920 |
@app.route('/users/<int:user_id>/trails/<int:trail_id>/notes', methods=['POST']) <NEW_LINE> def add_trail_note(trail_id): <NEW_LINE> <INDENT> comment = request.json['comment'] <NEW_LINE> note = Note(comment=comment, trail_id=trail_id) <NEW_LINE> db.session.add(note) <NEW_LINE> db.session.commit() <NEW_LINE> response = ... | Add a note to a trail | 625941d33cc13d1c6d3c7559 |
def _test_case_result(self): <NEW_LINE> <INDENT> if False in self.exp_vs_act_list: <NEW_LINE> <INDENT> self.testcase_result = 'FAIL' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.testcase_result = 'PASS' | verify api call test status
| 625941d3293b9510aa2c3474 |
def __onWikiParserPrepare(self, parser): <NEW_LINE> <INDENT> [*map(lambda command: parser.addCommand(command(parser)), self._commands)] | Вызывается до разбора викитекста. Добавление команды(:counter:) | 625941d3097d151d1a223038 |
def process_decoder_input(data, vocab_to_int, batch_size): <NEW_LINE> <INDENT> ending = tf.strided_slice(data, [0, 0], [batch_size, -1], [1, 1]) <NEW_LINE> decoder_input = tf.concat([tf.fill([batch_size, 1], vocab_to_int['<GO>']), ending], 1) <NEW_LINE> return decoder_input | 补充<GO>,并移除最后一个字符 | 625941d3bf627c535bc133ae |
def store_exit(): <NEW_LINE> <INDENT> village_01_01() | Allows the user to exit the store. | 625941d3c4546d3d9de72c14 |
def get_by_natural_key(self, email): <NEW_LINE> <INDENT> return self.get(**{self.model.USERNAME_FIELD: email}) | metod to permit authenticate by email | 625941d3b5575c28eb68e1e0 |
def open_zarr(s3_path, anon=False, cache=False): <NEW_LINE> <INDENT> s3 = s3fs.S3FileSystem(anon=anon) <NEW_LINE> store = s3fs.S3Map(s3_path, s3=s3, check=False, create=False) <NEW_LINE> if cache: <NEW_LINE> <INDENT> lrucache = zarr.LRUStoreCache(store=store, max_size=1<<29) <NEW_LINE> root = zarr.group(store=lrucache)... | Open a zarr archive and return its root. | 625941d3cdde0d52a9e53213 |
def course_certificate(): <NEW_LINE> <INDENT> mode = session.s3.hrm.mode <NEW_LINE> if mode is not None: <NEW_LINE> <INDENT> session.error = T("Access denied") <NEW_LINE> redirect(URL(f="index")) <NEW_LINE> <DEDENT> def postp(r, output): <NEW_LINE> <INDENT> if r.interactive: <NEW_LINE> <INDENT> output["dashboard"] = hr... | Courses to Certificates Controller | 625941d3cad5886f8bd271b8 |
def _parse_attr_onvalue (self, attribute, **kw): <NEW_LINE> <INDENT> self._tkRAD_any_value_support(attribute, **kw) | value attribute;
no return value (void); | 625941d321bff66bcd684b31 |
def related_change_on_moving(obj, event): <NEW_LINE> <INDENT> if IObjectWillBeAddedEvent.providedBy(event) or IObjectWillBeRemovedEvent.providedBy(event): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if event.oldParent and event.newParent and event.oldParent == event.newParent: <NEW_LINE> <INDENT> return <NEW_LINE> <... | Set local roles on related objects before moving | 625941d3dd821e528d63b388 |
def isAnagram(self, s, t): <NEW_LINE> <INDENT> char = [0] * 26 <NEW_LINE> for c in s: <NEW_LINE> <INDENT> char[ord(c)-ord('a')] += 1 <NEW_LINE> <DEDENT> for c in t: <NEW_LINE> <INDENT> char[ord(c)-ord('a')] -= 1 <NEW_LINE> <DEDENT> return len([x for x in char if x == 0]) == 26 | :type s: str
:type t: str
:rtype: bool | 625941d30c0af96317bb83c8 |
def __matmul__( self, other: Union[AnyArrayLike, FrameOrSeriesUnion] ) -> FrameOrSeriesUnion: <NEW_LINE> <INDENT> return self.dot(other) | Matrix multiplication using binary `@` operator in Python>=3.5. | 625941d356ac1b37e62643ad |
def __init__(self,max_age=1,min_hits=3, model_type = 0): <NEW_LINE> <INDENT> self.max_age = max_age <NEW_LINE> self.min_hits = min_hits <NEW_LINE> self.trackers = [] <NEW_LINE> self.frame_count = 0 <NEW_LINE> self.model_type = model_type | Sets key parameters for SORT
Model type: if 0 --> constant velocity
if 1 --> constant acceleration | 625941d38e05c05ec3eea556 |
def strStr(self, haystack, needle): <NEW_LINE> <INDENT> len_haystack = len(haystack) <NEW_LINE> len_needle = len(needle) <NEW_LINE> for i in range(len_haystack-len_needle+1): <NEW_LINE> <INDENT> if haystack[i:i+len_needle] == needle: <NEW_LINE> <INDENT> return i <NEW_LINE> <DEDENT> <DEDENT> return -1 | :type haystack: str
:type needle: str
:rtype: int | 625941d34e4d5625662d45b6 |
def ValidateValues(arguments): <NEW_LINE> <INDENT> if arguments.timeout <= 0: <NEW_LINE> <INDENT> print("\nInvalid timeout value: %s\n" % arguments.timeout) <NEW_LINE> print_help() <NEW_LINE> exit() <NEW_LINE> <DEDENT> if arguments.hostname is None: <NEW_LINE> <INDENT> print("\nNo hostname provided\n") <NEW_LINE> print... | Validate values - input values | 625941d37cff6e4e81117b65 |
def get(self, request): <NEW_LINE> <INDENT> context = cache.get('index_page_data') <NEW_LINE> if context is None: <NEW_LINE> <INDENT> types = GoodsType.objects.all() <NEW_LINE> goods_banners = IndexGoodsBanner.objects.all().order_by('index') <NEW_LINE> promotion_banners = IndexPromotioBanner.objects.all().order_by('ind... | 显示首页 | 625941d34c3428357757c507 |
def __instructions(self): <NEW_LINE> <INDENT> self += comment('Julia version {}'.format(self.__version)) <NEW_LINE> self += packages(ospackages=self.__ospackages) <NEW_LINE> self += shell(commands=self.__commands) <NEW_LINE> self += environment(variables=self.environment_step()) | Fill in container instructions | 625941d3a79ad161976cc326 |
def and_or_graph_search(problem, player, plys): <NEW_LINE> <INDENT> plan = [] <NEW_LINE> path = {} <NEW_LINE> next_moving_player = get_next_moving_player(player) <NEW_LINE> final_plan = or_search(problem, path, next_moving_player, plan, plys) <NEW_LINE> return final_plan.pop(0) | Run the and_or_graph_search algorithm and return the first action from the final plan
:param problem: The initial mancala board state
:param player: Which player is planning
:param plys: Number of plys to search
:return: | 625941d34428ac0f6e5ba9d3 |
def on_epoch_end(self, trainer, pl_module): <NEW_LINE> <INDENT> if (trainer.current_epoch + 1) % self.every_n_epochs == 0: <NEW_LINE> <INDENT> self.receiver_imgs = self.receiver_imgs.to(pl_module.device) <NEW_LINE> choices = [] <NEW_LINE> for choice in self.sender_choices: <NEW_LINE> <INDENT> choices.append(choice.to(p... | This function is called after every epoch.
Call the save_and_sample function every N epochs. | 625941d38e71fb1e9831d989 |
def add_aliases(self, values: AliasesTypeHint): <NEW_LINE> <INDENT> for key, value in values.items(): <NEW_LINE> <INDENT> self.add_alias(key, value) <NEW_LINE> <DEDENT> return self | Adds aliases to the set of inferred aliases.
:param values: mapping object (parameter name: class)
:return: self | 625941d35e10d32532c5f106 |
def convert_model_metadata_to_row(meta): <NEW_LINE> <INDENT> return Row( dataframe_created=datetime.utcnow(), from_date=meta.get('from_date'), listens_count=meta.get('listens_count'), model_created=meta.get('model_created'), model_deleted=meta.get('model_deleted'), model_id=meta.get('model_id'), model_param=Row( alpha=... | Convert model metadata to row object.
Args:
meta (dict): A dictionary containing model metadata.
Returns:
pyspark.sql.Row object - A Spark SQL row. | 625941d37b180e01f3dc49db |
def build_shift_dict(self, shift): <NEW_LINE> <INDENT> assert (shift >=0 and shift < 26), "Error: 0 <= shift < 26" <NEW_LINE> self.dicionario = {} <NEW_LINE> alfabeto = string.ascii_lowercase <NEW_LINE> alfabeto_alt = alfabeto[shift:] + alfabeto[:shift] <NEW_LINE> for l in alfabeto: <NEW_LINE> <INDENT> self.dicionario[... | Creates a dictionary that can be used to apply a cipher to a letter.
The dictionary maps every uppercase and lowercase letter to a
character shifted down the alphabet by the input shift. The dictionary
should have 52 keys of all the uppercase letters and all the lowercase
letters only.
shift (integer): the amo... | 625941d34f88993c3716c246 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.