code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def solve_uvOutOfRange(err_items): <NEW_LINE> <INDENT> return [] | UV Out of Range | 625941ddf8510a7c17cf9a28 |
def getFactor(self, currency, context): <NEW_LINE> <INDENT> props = getToolByName(context, 'portal_properties').currency_properties <NEW_LINE> return props.getProperty('factor_%s' % currency, 1) | returns the registered factor for a currency
returns 1 if none was registered | 625941dd462c4b4f79d1d9fa |
def _process_video_request(self, data): <NEW_LINE> <INDENT> pld = data['payload'] <NEW_LINE> if pld['idVideo'] in self.__cachedb: <NEW_LINE> <INDENT> video = self.__cachedb[pld['idVideo']] <NEW_LINE> self._from_cache(size_kb=video['size']) <NEW_LINE> new_data = self._pack_data(video, video['size'], 'video', data['packe... | Main logic of the Proxy. Will serve the video from the cache, or
forward the request to the VideoServer. | 625941dd76e4537e8c35199f |
def wishlist(self, wine_id, username=None, password=None, timeout=None): <NEW_LINE> <INDENT> params = self.basic_params() <NEW_LINE> username, password = self._get_credentials(username, password) <NEW_LINE> timeout = self._get_timeout(timeout) <NEW_LINE> new_params = { 'id': wine_id, 'u': username, 'p': password } <NEW... | Currently just adds to wine list | 625941ddbf627c535bc134f9 |
def compute_hashes_from_fileobj(fileobj, chunk_size=1024 * 1024): <NEW_LINE> <INDENT> linear_hash = hashlib.sha256() <NEW_LINE> chunks = [] <NEW_LINE> chunk = fileobj.read(chunk_size).encode('utf-8') <NEW_LINE> while chunk: <NEW_LINE> <INDENT> linear_hash.update(chunk) <NEW_LINE> chunks.append(hashlib.sha256(chunk).dig... | Compute the linear and tree hash from a fileobj.
This function will compute the linear/tree hash of a fileobj
in a single pass through the fileobj.
:param fileobj: A file like object.
:param chunk_size: The size of the chunks to use for the tree
hash. This is also the buffer size used to read from
`fileobj`... | 625941ddc4546d3d9de72d60 |
def should_be_equal_as_strings(self, first, second, msg=None, values=True, ignore_case=False, formatter='str'): <NEW_LINE> <INDENT> self._log_types_at_info_if_different(first, second) <NEW_LINE> first = self._convert_to_string(first) <NEW_LINE> second = self._convert_to_string(second) <NEW_LINE> if is_truthy(ignore_cas... | Fails if objects are unequal after converting them to strings.
See `Should Be Equal` for an explanation on how to override the default
error message with ``msg``, ``values`` and ``formatter``.
If ``ignore_case`` is given a true value (see `Boolean arguments`),
comparison is done case-insensitively. If both arguments ... | 625941ddc4546d3d9de72d61 |
def __getstate__(self): <NEW_LINE> <INDENT> ret_val = {'isalive': self.isalive(), 'command_path': self.command_path} <NEW_LINE> ret_val['output'], ret_val['last_index'] = self.read() <NEW_LINE> return ret_val | Simpler representation of ProcessControl | 625941ddbde94217f3683118 |
def on_session_closed(self, event): <NEW_LINE> <INDENT> if self.delegate is not None: <NEW_LINE> <INDENT> _dispatch(self.delegate, 'on_session_closed', event) | Callback for when both the local and remote endpoints of a
session have closed.
:param event: The underlying event object. Use this to obtain further
information on the event.
:type event: :class:`proton.Event` | 625941dd711fe17d8254268f |
def kwonly(a, *b, c): <NEW_LINE> <INDENT> print(a, b, c) | c argument must be passed by keyword syntax | 625941dd2ae34c7f2600d45b |
def setUp(self): <NEW_LINE> <INDENT> super(TestPermissions, self).setUp() <NEW_LINE> self.collection.register(Permissions()) | Setup | 625941dd8e71fb1e9831dad2 |
def __str__(self): <NEW_LINE> <INDENT> return "{}, {} Typing, Reflection={}, First appeared in {}".format(self.name, self.typing, self.reflection, self.year) | returns string representing object values | 625941ddac7a0e7691ed43f1 |
def __init__(self, temboo_session): <NEW_LINE> <INDENT> super(AddBasicListing, self).__init__(temboo_session, '/Library/eBay/Trading/AddBasicListing') | Create a new instance of the AddBasicListing Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied. | 625941dd26068e7796caf00d |
def _calc_julday(self): <NEW_LINE> <INDENT> utc_dt = self.utc_datetime <NEW_LINE> hour = utc_dt.hour + (utc_dt.minute / 60.0) + (utc_dt.second / 3600.0) <NEW_LINE> if self.calendar in ('gregorian', None): <NEW_LINE> <INDENT> jd = swe.date_conversion(utc_dt.year, utc_dt.month, utc_dt.day, hour) <NEW_LINE> <DEDENT> elif ... | Get chart Julian day number, based on local datetime and zoneinfo.
For ambiguous dates, set the 'dst' property.
For dates below 1900, set the 'utcoffset' property only.
:rtype: float | 625941dd4e696a04525c9777 |
def check_limits(self, value, obj): <NEW_LINE> <INDENT> start, stop, step = self._load_limits(obj) <NEW_LINE> if start is not None and value < start: <NEW_LINE> <INDENT> raise ValueError("Value below lower limit of {}".format( Q_(start, self.units) if self.units else start)) <NEW_LINE> <DEDENT> if stop is not None and ... | Check raw value (magnitude) against the Facet's limits | 625941dd99fddb7c1c9de6ba |
def _poly_drift(order, frametimes): <NEW_LINE> <INDENT> order = int(order) <NEW_LINE> pol = np.zeros((np.size(frametimes), order + 1)) <NEW_LINE> tmax = frametimes.max() <NEW_LINE> for k in range(order + 1): <NEW_LINE> <INDENT> pol[:, k] = (frametimes / tmax) ** k <NEW_LINE> <DEDENT> pol = _orthogonalize(pol) <NEW_LINE... | Create a polynomial drift matrix
Parameters
----------
order, int, number of polynomials in the drift model
tmax, float maximal time value used in the sequence
this is used to normalize properly the columns
Returns
-------
pol, array of shape(n_scans, order + 1)
all the polynomial drift plus a constant reg... | 625941ddbe383301e01b57ab |
def todict(self, functionKey, functionValue, useList=False): <NEW_LINE> <INDENT> res = {} <NEW_LINE> if useList: <NEW_LINE> <INDENT> for row in self.values: <NEW_LINE> <INDENT> v = self._interpret_row(row) <NEW_LINE> key = functionKey(v) <NEW_LINE> val = functionValue(v) <NEW_LINE> if key in res: <NEW_LINE> <INDENT> re... | convert the table as a dictionary { key:value }
each of them is defined by functions.
@param functionKey defines the key
@param functionValue defines the value
@param useList if there are multiple rows sharing the same key, it should be true,
all values are stor... | 625941dd4527f215b584c77e |
def test_nic_name(self): <NEW_LINE> <INDENT> self.assertEqual(self.ins.guess_nic_name(1), "GigabitEthernet0/0") <NEW_LINE> self.assertEqual(self.ins.guess_nic_name(2), "GigabitEthernet0/1") <NEW_LINE> self.assertEqual(self.ins.guess_nic_name(3), "GigabitEthernet0/2") <NEW_LINE> self.assertEqual(self.ins.guess_nic_name(... | Test NIC name construction. | 625941dd76e4537e8c3519a0 |
def load_sac(self, catalog_name, sac_file_obj): <NEW_LINE> <INDENT> utils.create_catalog_from_sac(catalog_name, self, sac_file_obj) | Loads a xephem edb database specified in edb_file_obj and stores it
into catalog_name. | 625941dd8e71fb1e9831dad3 |
def ex_get_shared_storage(self, storage_id): <NEW_LINE> <INDENT> response = self.connection.request( action='shared_storages/%s' % (storage_id), method='GET' ) <NEW_LINE> return response.object | Gets a shared storage
:return: 'dict' | 625941dd004d5f362079a65c |
def _init_config_variables(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.check_config_file_exists(): <NEW_LINE> <INDENT> self.set_config_with_str(get_file_content(self.config_file_location)) <NEW_LINE> <DEDENT> <DEDENT> except Exception as error: <NEW_LINE> <INDENT> log_msg = "Error setting variables from... | Sets configuration settings from file, saves default if missing. | 625941dd16aa5153ce3627a2 |
def tversky_loss(true, logits, alpha, beta, eps=1e-7): <NEW_LINE> <INDENT> num_classes = logits.shape[1] <NEW_LINE> batch_size = logits.shape[0] <NEW_LINE> if len(logits.shape) > 4: <NEW_LINE> <INDENT> one_hot_encoder = One_Hot(num_classes).forward <NEW_LINE> true_1_hot = one_hot_encoder(true) <NEW_LINE> if num_classes... | Computes the Tversky loss [1]. 2D, 3D and potentially beyond (not tested)...
Args:
true: a tensor of shape [B, H, W] or [B, 1, H, W] or [B, 1, H, W, Z ... [
logits: a tensor of shape [B, C, H, W]. Corresponds to
the raw output or logits of the model.
alpha: controls the penalty for false positives.
... | 625941dd796e427e537b08f2 |
def disco_output_stream(stream, partition, url, params): <NEW_LINE> <INDENT> from disco.fileutils import DiscoOutputStream <NEW_LINE> return DiscoOutputStream(stream) | Output stream for Disco's internal compression format. | 625941dd31939e2706e4d190 |
def test_compound_input_units_equivalencies(): <NEW_LINE> <INDENT> s1 = Shift(10 * u.deg) <NEW_LINE> s1.input_units_equivalencies = {'x': u.pixel_scale(0.5 * u.deg / u.pix)} <NEW_LINE> s2 = Shift(10 * u.deg) <NEW_LINE> sp = Shift(10 * u.pix) <NEW_LINE> cs = s1 | s2 <NEW_LINE> out = cs(10 * u.pix) <NEW_LINE> assert_quan... | Test setting input_units_equivalencies on one of the models. | 625941dd3539df3088e2e675 |
def test_factory_error(self): <NEW_LINE> <INDENT> data_inc = {'to': '+16263882600', 'callUri': 'https://api.catapult.inetwork.com/v1/users/u-2qep/calls/c-kmg', 'callState': 'error', 'eventType': 'error', 'from': '+17146143600', 'callId': 'c-kmg'} <NEW_LINE> event = Event.create(**data_inc) <NEW_LINE> self.assertEqual(s... | Event.create factory methods for error | 625941dd796e427e537b08f3 |
def _set_band_indicator(self, band): <NEW_LINE> <INDENT> symbol = {'GSM850': 'NA', 'GSM900': 'NA', 'DCS1800': 'G18', 'PCS1900': 'G19'} <NEW_LINE> result = self._inst.query('CONFigure:GSM:SIGN:CELL:BINDicator?') <NEW_LINE> if cmp(symbol[band], 'NA'): <NEW_LINE> <INDENT> if cmp(symbol[band], result): <NEW_LINE> <INDENT> ... | 该方法用于配置频段indicator,在切换至1800或1900时,必须得修改该参数。 | 625941dd379a373c97cfae71 |
def create_file(self, **kwargs): <NEW_LINE> <INDENT> if not 'name' in kwargs: <NEW_LINE> <INDENT> kwargs['name'] = self.uniq_name(prefix=kwargs.get('prefix', '')) <NEW_LINE> <DEDENT> kwargs.pop('prefix', None) <NEW_LINE> file = Synapse.client().store(File(**kwargs)) <NEW_LINE> self.dispose_of(file) <NEW_LINE> return fi... | Creates a new File and adds it to the trash queue. | 625941ddcc40096d61595c7a |
def most_similar(s, slist): <NEW_LINE> <INDENT> if len(slist) == 0: <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> scores = [editdistance.eval(s, t) for t in slist] <NEW_LINE> return slist[np.argmin(scores)] | 从词表中找最相近的词(当无法全匹配的时候)
| 625941dd5fc7496912cc3ca9 |
def ProcessKeyBoard(self, direction, deltaTime): <NEW_LINE> <INDENT> velocity = self.MovementSpeed * deltaTime <NEW_LINE> if direction == Camera_Movement.FORWARD: <NEW_LINE> <INDENT> self.Position += self.Front * velocity <NEW_LINE> <DEDENT> if direction == Camera_Movement.BACKWARD: <NEW_LINE> <INDENT> self.Position -=... | Processes input received from any keyboard-like input system.
Accepts input parameter in the form of camera defined ENUM
(to abstract it from windowing systems). | 625941dd0383005118ecf90c |
def get_average_record(self, n): <NEW_LINE> <INDENT> history_deque = collections.deque() <NEW_LINE> averages = [] <NEW_LINE> for d in self.data_points: <NEW_LINE> <INDENT> history_deque.appendleft(d) <NEW_LINE> if len(history_deque) > n: <NEW_LINE> <INDENT> history_deque.pop() <NEW_LINE> <DEDENT> avg = sum(history_dequ... | Returns a list of average current numbers, each representing the
average over the last n data points.
Args:
n: Number of data points to average over.
Returns:
A list of average current values. | 625941ddb5575c28eb68e32e |
def _escapeValue(value, dtype): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return "NULL" <NEW_LINE> <DEDENT> if dtype == 'geometry': <NEW_LINE> <INDENT> if isinstance(value, str): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = json.dumps(value) <NEW_LINE> return "S... | Escape value for SQL based on field type
INPUT value: the value to be included in the query (can be of different data types as listed below)
dtype: the data types of the value (string)
RETURN SQL string ready to be included in the query to Carto API (string)
TYPE Escaped
None -> NULL
geometry ... | 625941dd99fddb7c1c9de6bb |
def cmc( distmat, query_ids=None, gallery_ids=None, query_cams=None, gallery_cams=None, topk=100, separate_camera_set=False, single_gallery_shot=False, first_match_break=False, average=True): <NEW_LINE> <INDENT> assert isinstance(distmat, np.ndarray) <NEW_LINE> assert isinstance(query_ids, np.ndarray) <NEW_LINE> assert... | Args:
distmat: numpy array with shape [num_query, num_gallery], the
pairwise distance between query and gallery samples
query_ids: numpy array with shape [num_query]
gallery_ids: numpy array with shape [num_gallery]
query_cams: numpy array with shape [num_query]
gallery_cams: numpy array wit... | 625941dd6e29344779a6293b |
def find_active_links(node_status, node_at_link_ends): <NEW_LINE> <INDENT> node_at_link_start, node_at_link_end = _split_link_ends(node_at_link_ends) <NEW_LINE> if len(node_at_link_end) != len(node_at_link_start): <NEW_LINE> <INDENT> raise ValueError("Link arrays must be the same length") <NEW_LINE> <DEDENT> status_at_... | find_active_links(node_status, (node0, node1)) IDs of active links.
Parameters
----------
node_status : ndarray
Status of nodes.
node0, node1 : sequence of array-like
Node ID at link start and end.
Returns
-------
ndarray :
Links IDs of active links.
Examples
--------
>>> from landlab.grid.unstructured.l... | 625941ddfff4ab517eb2f769 |
def _request(self, func, url, *args, **kwargs): <NEW_LINE> <INDENT> return_json = kwargs.pop('return_json', False) <NEW_LINE> url = self.api_url + url <NEW_LINE> try : <NEW_LINE> <INDENT> response = func(url, *args, **kwargs) <NEW_LINE> <DEDENT> except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) ... | Make a generic request, adding in any proxy defined by the instance.
Raises a ``requests.HTTPError`` if the response status isn't 200, and
raises a :class:`BitfinexError` if the response contains a json encoded
error message. | 625941dd5fcc89381b1e19eb |
def check_stack_analysis_status(resp_json, err): <NEW_LINE> <INDENT> assert resp_json.get("status") == "success", err | Ensure that the stack analyses result has been asserted in the loop. | 625941dd26238365f5f0f19d |
def test00_deepTree(self): <NEW_LINE> <INDENT> self._check_tree(self.file) | Creation of a large depth object tree. | 625941dd046cf37aa974d070 |
def natpolicyrules(self, natpolicyset_id, natpolicyrule_id=None, tenant_id=None, api_version="v2.0"): <NEW_LINE> <INDENT> if tenant_id is None and self._parent_class.tenant_id: <NEW_LINE> <INDENT> tenant_id = self._parent_class.tenant_id <NEW_LINE> <DEDENT> elif not tenant_id: <NEW_LINE> <INDENT> raise TypeError("tenan... | Get policy rules of policy set
**Parameters:**:
- **natpolicyset_id**: NAT Policy Set ID
- **natpolicyrule_id**: (optional) NAT Policy Rule ID
- **tenant_id**: Tenant ID
- **api_version**: API version to use (default v2.0)
**Returns:** requests.Response object extended with cgx_status and cgx_content prope... | 625941dd283ffb24f3c55c29 |
def get_user_by_id(self, id): <NEW_LINE> <INDENT> return self.db_adapter.get_object(self.UserClass, id=id) | Retrieve a User object by ID. | 625941dd507cdc57c630700c |
def fetch_words(url_to_fetch): <NEW_LINE> <INDENT> with urlopen(url_to_fetch) as story: <NEW_LINE> <INDENT> word_list = [] <NEW_LINE> for line in story: <NEW_LINE> <INDENT> line_words = line.decode('utf-8').split() <NEW_LINE> for word in line_words: <NEW_LINE> <INDENT> word_list.append(word) <NEW_LINE> <DEDENT> <DEDENT... | Fetch a list of words from a URL
Args:
url_to_fetch: The url of a utf-8 text doc.
Returns:
A List of words from the doc. | 625941dd7b25080760e39783 |
def assert_structural_schema(self, schema): <NEW_LINE> <INDENT> assert(self.validate_schema(schema) == [True, 'XMLSchema']), 'Schema \'{}\' has not been validated as a structural schema.' | Raise an error if a schema is not a structural one
:param str schema: xml (schema itself) or unique_key
:raises AssertionError: if schema is not a structural one | 625941dd0a50d4780f6671c0 |
def get_inv_stock_cards(self): <NEW_LINE> <INDENT> return self.inv.get("stock_cards", False) | Use Stock Cards | 625941dda79ad161976cc470 |
def setup(app, pyramidConfig): <NEW_LINE> <INDENT> box = app.GetObjectConf("box") <NEW_LINE> if box: <NEW_LINE> <INDENT> for field in box.data: <NEW_LINE> <INDENT> if field.id == "span": <NEW_LINE> <INDENT> if not field.listItems: <NEW_LINE> <INDENT> field.listItems = grid_span <NEW_LINE> <DEDENT> <DEDENT> elif field.i... | process all configurations and set form list fields for css selection | 625941dd287bf620b61d3d8d |
def __init__(self, nelx: int, nely: int): <NEW_LINE> <INDENT> self.nelx = nelx <NEW_LINE> self.nely = nely <NEW_LINE> self.ndof = 2 * (nelx + 1) * (nely + 1) | Create the boundary conditions with the size of the grid.
Parameters
----------
nelx:
The number of elements in the x direction.
nely:
The number of elements in the y direction. | 625941dd24f1403a92600e8f |
def add_entry(self, data): <NEW_LINE> <INDENT> if self.__is_valid_entry(data): <NEW_LINE> <INDENT> user = data[8] <NEW_LINE> if user in self.__users: <NEW_LINE> <INDENT> self.__users[user].update(data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__uid += 1 <NEW_LINE> self.__users[user] = UserEntry(self.__uid, da... | Add an entry to the user database. | 625941ddb830903b967e9c33 |
def _validate_key(key): <NEW_LINE> <INDENT> if not isinstance(key, six.binary_type): <NEW_LINE> <INDENT> raise TypeError('Key must be bytes') <NEW_LINE> <DEDENT> if len(key) not in (16, 32): <NEW_LINE> <INDENT> raise ValueError('Key must be 16 or 32 bytes long') <NEW_LINE> <DEDENT> return key | confirm `key` is suitable for AES encryption, or raise ValueError | 625941ddd58c6744b4257f89 |
def _init_fields(self, cr, uid, data, context): <NEW_LINE> <INDENT> budget_obj = pooler.get_pool(cr.dbname).get('c2c_budget') <NEW_LINE> version_obj = pooler.get_pool(cr.dbname).get('c2c_budget.version') <NEW_LINE> res = {} <NEW_LINE> if data['model'] == 'c2c_budget': <NEW_LINE> <INDENT> if len(data['ids']) == 1: <NEW_... | init the form's fields | 625941dd004d5f362079a65d |
def add_task(tid, name, project, tags, priority, entry, due, recur): <NEW_LINE> <INDENT> with io.with_feedback(f"Importing '{name}' ({project})"): <NEW_LINE> <INDENT> return taskwarrior.task_add( name, project=project, tags=tags, priority=priority, entry=entry, due=due, recur=recur, todoist_id=tid, ) | Add a taskwarrior task from todoist task
Returns the taskwarrior task. | 625941dd7c178a314d6ef790 |
def begin_create_or_update( self, resource_group_name, resource_name, parameters, **kwargs ): <NEW_LINE> <INDENT> polling = kwargs.pop('polling', True) <NEW_LINE> cls = kwargs.pop('cls', None) <NEW_LINE> lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) <NEW_LINE> cont_token = kwargs.pop('cont... | Create or update a resource.
:param resource_group_name: The name of the resource group that contains the resource. You can
obtain this value from the Azure Resource Manager API or the portal.
:type resource_group_name: str
:param resource_name: The name of the resource.
:type resource_name: str
:param parameters: Pa... | 625941ddcb5e8a47e48b7dd1 |
def __init__(self, stream_name: str, partition_key: str, *, chunk_size: int = DEFAULT_CHUNK_SIZE, encoder: str = 'utf-8', workers: int = 1, **boto_session_kwargs): <NEW_LINE> <INDENT> self._client = client('kinesis', **boto_session_kwargs) <NEW_LINE> self.chunk_size = chunk_size <NEW_LINE> self.stream_name = stream_nam... | :param stream_name: Name of the Kinesis stream
:type stream_name: str
:param partition_key: Kinesis partition key used to group data by shards
:type partition_key: str
:param chunk_size: the size of a a chunk of records for rotation threshold (default 524288)
:type chunk_size: int
:param encoder: the encoder to be used... | 625941dd4527f215b584c77f |
def test_request_type_value(self): <NEW_LINE> <INDENT> buffer = copy(self.entity1) <NEW_LINE> buffer.request_type = "99" <NEW_LINE> with self.assertRaises(ValidationError): <NEW_LINE> <INDENT> buffer.save() <NEW_LINE> <DEDENT> transaction.rollback() | Tests CHECK constraint of request_type.
| 625941dd96565a6dacc8f9f6 |
def get_optional_args(self, timestamp): <NEW_LINE> <INDENT> args = [arg for c in self.get_children() for arg in c.get_optional_args(timestamp)] <NEW_LINE> return args | returns the list of arguments to be placed in the optional part of RSYNC command line.
:param timestamp: the actual timestamp to be used in arguments using it (eg. name of log files)
:return: list of string | 625941dd67a9b606de4a81e3 |
def run_memoryprofiler(self): <NEW_LINE> <INDENT> self.analyze(self.main.editor.get_current_filename()) | Run memory profiler. | 625941dda8ecb033257d33f7 |
def run_withhold(self,attacker_power): <NEW_LINE> <INDENT> public_vals = [] <NEW_LINE> private_vals = [] <NEW_LINE> total_hash_cnt = 0 <NEW_LINE> miners = [ATTACKER,HONEST,HONEST] <NEW_LINE> mining = True <NEW_LINE> while (mining): <NEW_LINE> <INDENT> val= random.getrandbits(self.bits) <NEW_LINE> total_hash_cnt+=1 <NEW... | In this scenario, the winning miner maliciously withholds their proofs,
but does make use of the publicly released blocks. | 625941ddd58c6744b4257f8a |
def testDatabaseMultiValue(self): <NEW_LINE> <INDENT> self.persistDatabaseEmpty() <NEW_LINE> self._log.debug( "\ntestDatabaseMultiValue" ) <NEW_LINE> self.loader = EventRouterLoader() <NEW_LINE> self.loader.loadHandlers( getDictFromXmlString(testPersistCfg) ) <NEW_LINE> self.loader.start() <NEW_LINE> self.router = self... | Test to write multi value to database | 625941ddd53ae8145f87a596 |
def __init__(self, config, environ, logdispatch, statechglogger): <NEW_LINE> <INDENT> Rule.__init__(self, config, environ, logdispatch, statechglogger) <NEW_LINE> self.logger = logdispatch <NEW_LINE> self.rulenumber = 363 <NEW_LINE> self.rulename = "STIGConfigureRestrictionsPolicy" <NEW_LINE> self.formatDetailedResults... | Constructor | 625941dd566aa707497f4890 |
def test_repr_formatting(self): <NEW_LINE> <INDENT> stream = StringIO() <NEW_LINE> observer = make_JSON_observer(stream) <NEW_LINE> log = make_logger(observer=observer) <NEW_LINE> class BracketThing(object): <NEW_LINE> <INDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<BracketThing kwargs={}>" <NEW_LINE> <DEDENT... | Non-JSON-serialisable parameters are repr()'d, and any curly brackets
in the result are escaped. | 625941ddd8ef3951e3243869 |
@app.route('/users/profile', methods=["GET", "POST"]) <NEW_LINE> def profile(): <NEW_LINE> <INDENT> if not g.user: <NEW_LINE> <INDENT> flash("Access unauthorized.", "danger") <NEW_LINE> return redirect("/login") <NEW_LINE> <DEDENT> form = UserEditForm(obj=g.user) <NEW_LINE> if form.validate_on_submit(): <NEW_LINE> <IND... | Update profile for current user. | 625941dd8c3a8732951586e9 |
def add_col(self, label): <NEW_LINE> <INDENT> self.AppendCols(1) <NEW_LINE> last_col = self.GetNumberCols() - 1 <NEW_LINE> self.SetColLabelValue(last_col, label) <NEW_LINE> self.col_labels.append(label) <NEW_LINE> self.size_grid() <NEW_LINE> return last_col | Add a new column to the grid.
Resize grid to display the column. | 625941ddd10714528d600012 |
def new(self, obj): <NEW_LINE> <INDENT> a = {obj.to_dict()['__class__'] + '.' + obj.id: obj} <NEW_LINE> self.all().update(a) | ADDS a new object TO storage DICTIONARY:
sets in __objects the obj with key <obj class name>.id | 625941dd7047854f462a1732 |
def os(): <NEW_LINE> <INDENT> x, y = int(a, 2), int(b, 2) <NEW_LINE> while y: <NEW_LINE> <INDENT> ans = x ^ y <NEW_LINE> carry = (x & y) << 1 <NEW_LINE> x, y = ans, carry <NEW_LINE> <DEDENT> return bin(x)[2:] | Runtime: 34 ms, faster than 87.46% of Python3 online submissions for Add Binary.
TODO: learn bit manipulation | 625941dd627d3e7fe0d6917d |
def test_pso_nested_groups(self): <NEW_LINE> <INDENT> group1_pso = PasswordSettings("group1-PSO", self.ldb, precedence=50, password_len=12, history_len=3) <NEW_LINE> group2_pso = PasswordSettings("group2-PSO", self.ldb, precedence=25, password_len=10, history_len=5, complexity=False) <NEW_LINE> group3_pso = PasswordSet... | PSOs operate correctly when applied to nested groups | 625941dd090684286d50f015 |
@lru_cache(maxsize=None) <NEW_LINE> def find_posix_python(version): <NEW_LINE> <INDENT> if version: <NEW_LINE> <INDENT> path = find_executable('python' + version) <NEW_LINE> if not path: <NEW_LINE> <INDENT> path = find_executable('python' + version[0]) <NEW_LINE> if not path: <NEW_LINE> <INDENT> path = find_executable(... | Find the nearest version of python and return its path. | 625941dd32920d7e50b284fe |
def getHostGroupMembers(hostGroupName): <NEW_LINE> <INDENT> hostList = [] <NEW_LINE> lines = os.popen('bmgroup -r ' + str(hostGroupName)).readlines() <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> if re.search('No such user/host group', line): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> elif re.match('^' + str(hos... | Get host group members with bmgroup.
====
[yanqing.li@nxnode03 openlavaMonitor]$ bmgroup pd
GROUP_NAME HOSTS
pd dm006 dm007 dm010 dm009 dm002 dm003 dm005
==== | 625941dd50485f2cf553d0c7 |
def display_info(window, text): <NEW_LINE> <INDENT> if text: <NEW_LINE> <INDENT> msg = window.font_text.render(text, True, html_color_codes['black']) <NEW_LINE> top_margin = (TOP_MARGIN - window.font_text.get_ascent()) // 2 <NEW_LINE> info_rect = pygame.Rect((LEFT_MARGIN, top_margin, window_size()[0] - 2 * LEFT_MARGIN,... | Display info 'text' starting at the left top corner of the window | 625941dd379a373c97cfae72 |
def update(self, message): <NEW_LINE> <INDENT> self.content_type = "application/json" <NEW_LINE> self.method = "PATCH" <NEW_LINE> entity = Message(json.loads(self.send(message).content)) <NEW_LINE> self._initialize_collection_properties(entity) <NEW_LINE> return entity | Updates the specified Message.
Args:
message (:class:`Message<msgraph.model.message.Message>`):
The Message to update.
Returns:
:class:`Message<msgraph.model.message.Message>`:
The updated Message. | 625941dd63d6d428bbe4481c |
def set_CommentID(self, value): <NEW_LINE> <INDENT> super(DeleteMediaCommentInputSet, self)._set_input('CommentID', value) | Set the value of the CommentID input for this Choreo. ((required, string) The ID of the comment to delete.) | 625941ddbe7bc26dc91cd926 |
def __init__(self): <NEW_LINE> <INDENT> Record.__init__(self) <NEW_LINE> self._mandatory_fields = ['SiteName', 'Month', 'Year', 'NumberOfVMs'] <NEW_LINE> self._msg_fields = ['SiteName', 'Month', 'Year', 'GlobalUserName', 'VO', 'VOGroup', 'VORole', 'Status', 'CloudType', 'ImageId', 'EarliestStartTime', 'LatestStartTime... | Provide the necessary lists containing message information. | 625941dd8e05c05ec3eea6a3 |
def SetDifferenceThreshold(self, *args): <NEW_LINE> <INDENT> return _itkDifferenceImageFilterPython.itkDifferenceImageFilterIUS2IUS2_SetDifferenceThreshold(self, *args) | SetDifferenceThreshold(self, unsigned short _arg) | 625941dda934411ee37519c0 |
def is_client_error(status): <NEW_LINE> <INDENT> return 400 <= status <= 499 | 检查状态码是否客户端错误
:param:
* status: http 状态码
:return:
* result: True or False | 625941dd99cbb53fe6792f12 |
def __getattr__(self, name): <NEW_LINE> <INDENT> registry = self._registry or get_recent_plugins_registry() <NEW_LINE> if not registry: <NEW_LINE> <INDENT> return lambda *a, **kwa: [] <NEW_LINE> <DEDENT> return lambda *a, **kwa: registry._call_by_name(name, *a, **kwa) | Proxy a call to all implementation callables | 625941dd9f2886367277abb7 |
def recv_data(self): <NEW_LINE> <INDENT> data, addr = self.sock.recvfrom(self.packetsize) <NEW_LINE> matrix = map(ord, data.strip()) <NEW_LINE> if len(matrix) == self.packetsize: <NEW_LINE> <INDENT> self.matrix = matrix[:-4] | Grab the next frame and put it on the matrix. | 625941dd566aa707497f4891 |
def get_clttimeout(self): <NEW_LINE> <INDENT> return self.options['clttimeout'] | The timeout value in seconds for idle client connection.
Default value: 0
Minimum value = 0
Maximum value = 31536000 | 625941ddd18da76e23532805 |
def backup_model_to_disk( model, dict_to_pkl, directory='../data/temp/' ): <NEW_LINE> <INDENT> now = datetime.datetime.now() <NEW_LINE> prefix = now.strftime("%Y%m%d-%H%M") + '_' <NEW_LINE> saved_files = [] <NEW_LINE> desc = '{}_{:.4f}_'.format(trainset_infos['target_group'], training_infos['loss']) <NEW_LINE> model_in... | Backup model to disk
## Inputs:
model (Keras model): model to backup
trainset_infos (dict): Info of the training session
- total_epochs (integer): total number of epochs used to train the model
- loss (float): up to date loss of the model
- acc (float): up to date accuracy of the model
trainset_utils (dict... | 625941dd3d592f4c4ed1d392 |
def config_item(self) -> ItemConfigBase: <NEW_LINE> <INDENT> return self._config_item | :return: Returns the composer item configuration. This should be a
sub-class of item configuration base.
:rtype: ItemConfigBase | 625941ddd8ef3951e324386a |
def use(name): <NEW_LINE> <INDENT> global toolkit, family <NEW_LINE> name = name.lower() <NEW_LINE> if name.startswith('choose'): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif name.startswith('qt') or name.startswith('pyside'): <NEW_LINE> <INDENT> family = 'qt' <NEW_LINE> if name == 'qt': <NEW_LINE> <INDENT> name =... | Set the name of the GUI toolkit we should use. | 625941dd4e696a04525c9778 |
def test_get_level_non_default(init_statick): <NEW_LINE> <INDENT> args = Args("Statick tool") <NEW_LINE> args.parser.add_argument( "--profile", dest="profile", type=str, default="profile-test.yaml" ) <NEW_LINE> level = init_statick.get_level("package", args.get_args([])) <NEW_LINE> assert level == "package_specific" | Test searching for a level when a package has a custom level.
Expected result: Some level is returned | 625941ddf8510a7c17cf9a2a |
def get_filtered_md5sum_dict(md5dir, excluded_extensions=[]): <NEW_LINE> <INDENT> return get_md5sums([fname for fname in glob(os.path.join(md5dir, '*')) if os.path.isfile(fname) and os.path.splitext(fname)[1] not in excluded_extensions ] ) | Simulate filtered Linux md5sum command on md5dir directory | 625941dd8c0ade5d55d3ece9 |
def detect_edges_gray( img, downscale=32, smooth=2, sigma=3, return_img=False): <NEW_LINE> <INDENT> from skimage.filters import gaussian <NEW_LINE> from skimage.feature import canny <NEW_LINE> from skimage.measure import label <NEW_LINE> import numpy as np <NEW_LINE> from .Utility_Functions.image import pool_numpy <NEW... | Detects edges of a single colour sheet by running a Canny edge detector on dowsampled images.
Parameters
----------
img : numpy array
(nrows, ncols) grayscale image
downscale : int
downsampling factor, resulting image will be reduced by 1./downscale times. downscale needs to divide image dimensions exactly.
sm... | 625941dd5f7d997b87174dc7 |
def testCaptureSmileImageWithLocationOn(self): <NEW_LINE> <INDENT> so.setCameraOption('Geo Location','on') <NEW_LINE> tb.captureAndCheckPicCount('smile') | Summary:Capture image with Geo-tag ON.
Step:
1.Launch smile capture activity
2.Set Ge0-tag ON
3.Touch shutter button to capture picture
4.Exit activity | 625941ddd486a94d0b98e473 |
def p_brackets_4(t): <NEW_LINE> <INDENT> if not x86_afs.ad in t[4]: <NEW_LINE> <INDENT> t[4][x86_afs.ad] = True <NEW_LINE> <DEDENT> t[0] = t[4] <NEW_LINE> t[0][x86_afs.imm] = - int(int32(uint32(int(t[2])))) | brackets : MINUS NUMBER LBRA expression RBRA | 625941dd57b8e32f524837c9 |
def quit( self ): <NEW_LINE> <INDENT> return self.driver.quit() | close driver
| 625941dd8a43f66fc4b5438e |
def facing_left(): <NEW_LINE> <INDENT> pass | returns true if the player is facing left, false if not | 625941ddc4546d3d9de72d63 |
def find_commandset_for_command(self, command_name: str) -> Optional[CommandSet]: <NEW_LINE> <INDENT> return self._cmd_to_command_sets.get(command_name) | Finds the CommandSet that registered the command name
:param command_name: command name to search
:return: CommandSet that provided the command | 625941ddc432627299f04f74 |
def use_iterator(self, it): <NEW_LINE> <INDENT> self.assertTrue(hasattr(it, '__iter__')) <NEW_LINE> item = next(it) <NEW_LINE> self.assertIn('id', item) | Checks the first item for a tweet id. | 625941dd7b180e01f3dc4b24 |
def _test_lb_and_listener_and_pool_statuses(self, session, hm): <NEW_LINE> <INDENT> pool = self.repositories.pool.get(session, id=hm.pool_id) <NEW_LINE> load_balancer_id = pool.load_balancer_id <NEW_LINE> if pool.provisioning_status not in consts.MUTABLE_STATUSES: <NEW_LINE> <INDENT> raise exceptions.ImmutableObject(re... | Verify load balancer is in a mutable state. | 625941dd4428ac0f6e5bab20 |
@pytest.mark.slow <NEW_LINE> def test_mean_los_velocity_vs_rp_cross_consistency(): <NEW_LINE> <INDENT> npts = 101 <NEW_LINE> with NumpyRNGContext(fixed_seed): <NEW_LINE> <INDENT> sample1 = np.random.random((npts, 3)) <NEW_LINE> velocities1 = np.random.normal(loc=0, scale=100, size=npts*3).reshape((npts, 3)) <NEW_LINE> ... | Verify that the `~halotools.mock_observables.mean_los_velocity_vs_rp` function
returns self-consistent cross-correlation results
regardless of whether we ask for auto-correlations. | 625941ddbde94217f368311a |
def item_to_element(self, item): <NEW_LINE> <INDENT> if isinstance(item, dict): <NEW_LINE> <INDENT> for name in sorted(item.keys()): <NEW_LINE> <INDENT> self.builder.start(name, dict()) <NEW_LINE> self.item_to_element(item[name]) <NEW_LINE> self.builder.end(name) <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(item, (tupl... | Recursively build elements from the given data item. | 625941dde8904600ed9f225d |
def velocidade(valor): <NEW_LINE> <INDENT> turtle.speed(valor) | Altera a velocidade do desenho (valores de 1 a 10) | 625941dd73bcbd0ca4b2c3a2 |
def draw_distance(self): <NEW_LINE> <INDENT> self.distance = self.foreground.distance <NEW_LINE> return | Use distance from target star. | 625941dd55399d3f055889e2 |
def find_by_id(self, task, params={}, **options): <NEW_LINE> <INDENT> path = "/tasks/%s" % (task) <NEW_LINE> return self.client.get(path, params, **options) | Returns the complete task record for a single task.
Parameters
----------
task : {Id} The task to get.
[params] : {Object} Parameters for the request | 625941dda4f1c619b28b035e |
def __getattr__(self, item): <NEW_LINE> <INDENT> if 'name' == item: <NEW_LINE> <INDENT> return 'wxy' <NEW_LINE> <DEDENT> print(item) <NEW_LINE> print(type(item)) | 定义该方法后,调用类的方法或属性时,如果查找比如student.name,没有name属性,则会立马报错
如果定义了改法,则如果对象中没有该属性,则会直接调用该方法来进行查找
AttributeError: 'Student' object has no attribute 'name'
也可以直接返回一个函数
很适合restful风格 | 625941dde1aae11d1e749fe6 |
def plot_metric(method_metric_dict, dataset_name, x_axis, metric_name, markevery, normalization=None): <NEW_LINE> <INDENT> fig = plt.figure() <NEW_LINE> ax = fig.add_subplot(111) <NEW_LINE> ax.set_xlabel('Instance') <NEW_LINE> ax.set_ylabel(metric_name.title()) <NEW_LINE> marker = itertools.cycle(('o', '^', 's', 'x', '... | Returns an error-bar plot of the aggregated statistics (mean, var) for
a specific dataset and metric, for each method in the provided dict.
:param method_metric_dict: {method: {ds_name: measurements_df}}
Maps each method to dataset names, each one with one aggregate
measurements df.
The df has one line p... | 625941dd66673b3332b923be |
def reset_lookup_tables(nodemap): <NEW_LINE> <INDENT> result = True <NEW_LINE> try: <NEW_LINE> <INDENT> lut_enable = PySpin.CBooleanPtr(nodemap.GetNode("LUTEnable")) <NEW_LINE> if not PySpin.IsAvailable(lut_enable) or not PySpin.IsWritable(lut_enable): <NEW_LINE> <INDENT> print("Unable to disable lookup tables. Non-fat... | This function resets the camera by disabling lookup tables.
:param nodemap: Device nodemap.
:type nodemap: INodeMap
:return: returns True if successful, False otherwise
:rtype: bool | 625941ddad47b63b2c50a2ab |
def display_hierarchy(root_ad_unit, all_ad_units): <NEW_LINE> <INDENT> parent_id_to_children = collections.defaultdict(list) <NEW_LINE> for ad_unit in all_ad_units: <NEW_LINE> <INDENT> if 'parentId' in ad_unit: <NEW_LINE> <INDENT> parent_id_to_children[ad_unit['parentId']].append(ad_unit) <NEW_LINE> <DEDENT> <DEDENT> p... | Display the ad units as a tree.
Args:
root_ad_unit: The root ad unit to begin from.
all_ad_units: A list containing all ad units. | 625941dd8e7ae83300e4b2fa |
def run(test, params, env): <NEW_LINE> <INDENT> lock_test = params["images"] <NEW_LINE> root_dir = data_dir.get_data_dir() <NEW_LINE> test_image = QemuImg(params.object_params(lock_test), root_dir, lock_test) <NEW_LINE> test_filename = test_image.image_filename <NEW_LINE> lock_err_info = 'Failed to get "consistent read... | Image creation locking should be properly released.
1. Create raw image and close it after 0.5 sec.
2. Check there is no lock error of the CML.
:param test: Qemu test object.
:param params: Dictionary with the test parameters.
:param env: Dictionary with test environment. | 625941dd099cdd3c635f0f86 |
def clip(request, clip_id): <NEW_LINE> <INDENT> context = {} <NEW_LINE> clip = get_object_or_404(Clip, pk=clip_id) <NEW_LINE> if 'score' in request.GET: <NEW_LINE> <INDENT> ratingform = RatingForm(request.GET) <NEW_LINE> cliprating, new = ClipRating(clip=clip) <NEW_LINE> if ratingform.is_valid(): <NEW_LINE> <INDENT> cl... | Single-clip view. | 625941dd8c0ade5d55d3ecea |
def addOneRow(self, root, v, d): <NEW_LINE> <INDENT> if d == 1: <NEW_LINE> <INDENT> newRoot = TreeNode(v) <NEW_LINE> newRoot.left = root <NEW_LINE> return newRoot <NEW_LINE> <DEDENT> curDepthStack, D, nextDepthStack = [root], 1, [] <NEW_LINE> while D < d - 1: <NEW_LINE> <INDENT> nextDepthStack = [] <NEW_LINE> for node ... | :type root: TreeNode
:type v: int
:type d: int
:rtype: TreeNode | 625941ddf8510a7c17cf9a2b |
def edit_manifest(manifest_fn, new_repo_and_hash, new_hash_dict): <NEW_LINE> <INDENT> with tempfile.NamedTemporaryFile(mode='w', dir='.', delete=False) as tmp_manifest, open(manifest_fn, 'r') as old_manifest: <NEW_LINE> <INDENT> print("Trying to edit manifest with new repo and Git hash {}".format(new_repo_an... | Edit the provided manifest file to update the githash and SHA256 | 625941dd73bcbd0ca4b2c3a3 |
def Expand(self, foldpanel): <NEW_LINE> <INDENT> fpbextrastyle = 0 <NEW_LINE> if self._extraStyle & FPB_SINGLE_FOLD or self._extraStyle & FPB_EXCLUSIVE_FOLD: <NEW_LINE> <INDENT> fpbextrastyle = 1 <NEW_LINE> for panel in self._panels: <NEW_LINE> <INDENT> panel.Collapse() <NEW_LINE> <DEDENT> <DEDENT> foldpanel.Expand() <... | Expands the given fold panel reference, and updates the foldpanel bar.
:param `foldpanel`: an instance of L{FoldPanelItem}.
:note: With the ``FPB_COLLAPSE_TO_BOTTOM`` style set, they will be removed
from the bottom and the order where the panel originally was placed is
restored. | 625941dd3317a56b86939f7e |
def modifiedIsOverlap(V, W, ind, classId): <NEW_LINE> <INDENT> if (V[ind] > W[ind]).any() == True: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> indcomp = np.nonzero((W >= V).all(axis = 1))[0] <NEW_LINE> if len(indcomp) == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <N... | Checking overlap between hyperbox ind and remaning hyperboxes (1 vs many)
Only do overlap testing with hyperboxes belonging to other classes
INPUT
V Hyperbox lower bounds
W Hyperbox upper bounds
ind Index of the hyperbox to be checked for overlap
classId Class labels of ... | 625941ddbe383301e01b57ad |
def crawl_excel_sheet(sheet): <NEW_LINE> <INDENT> ncols = sheet.ncols <NEW_LINE> stats_per_county = {} <NEW_LINE> for i in range(7, 52): <NEW_LINE> <INDENT> county = sheet.cell_value(i, 0) <NEW_LINE> stats = [] <NEW_LINE> for j in range(1, ncols): <NEW_LINE> <INDENT> val = sheet.cell_value(i, j) <NEW_LINE> stats.append... | Reads the corona statistics from the given excel sheet. | 625941dd4c3428357757c653 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.