code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_user_def_dictionary(self): <NEW_LINE> <INDENT> return self._udd
returns: user defined type organized as a dictionary
625941f3bd1bec0571d90c2e
def write(self, addr, data, control): <NEW_LINE> <INDENT> if not is_u32(addr): <NEW_LINE> <INDENT> raise ValueError('The addr parameter must be an unsigned 32-bit value.') <NEW_LINE> <DEDENT> if not is_valid_buf(data): <NEW_LINE> <INDENT> raise ValueError('The data parameter must be a sequence type with at least one it...
Writes data from the array into the device starting at the given address. @param int addr: Start address of the memory block to write. @param sequence data: Data to write. Any type that implements the sequence API (i.e. string, list, bytearray...) is valid as input. @param boolean control: True for automatic control o...
625941f3377c676e912727a5
def der_Hcore_matrix(a,bset,atoms): <NEW_LINE> <INDENT> nbf = len(bset) <NEW_LINE> dHcore_dXa = zeros((nbf,nbf),'d') <NEW_LINE> dHcore_dYa = zeros((nbf,nbf),'d') <NEW_LINE> dHcore_dZa = zeros((nbf,nbf),'d') <NEW_LINE> for i in xrange(nbf): <NEW_LINE> <INDENT> for j in xrange(nbf): <NEW_LINE> <INDENT> dHcore_dXa[i][j],d...
Evaluates the derivative of the single particle Hamiltonian matrix elements. This amounts to evaluating the derivatives of the kinetic energy and the nuclear-electron attraction.
625941f330bbd722463cc3c8
def load(self, ground_truth, test): <NEW_LINE> <INDENT> self.load_ground_truth(ground_truth) <NEW_LINE> self.load_test(test)
Loads both the ground truth and the test lists. The two lists must have the same length. :param ground_truth: a list of real values (aka ground truth). E.g: [3.0, 1.0, 5.0, 2.0, 3.0] :type ground_truth: list :param test: a list of predicted values. E.g: [2.3, 0.9, 4.9, 0.9, 1.5] :type test: list :return:
625941f37d847024c06be8c0
def get_order(self): <NEW_LINE> <INDENT> if self.check_set_attr('symbols_unique'): <NEW_LINE> <INDENT> return dict([(sym, num+1) for num, sym in enumerate(self.symbols_unique)]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
Dict which maps ``symbols_unique`` to numbers, starting at 1. ``{'Al': 1, 'N':2, 'O': 3, 'Si': 4}`` for ``symbols=['Al']*5 + ['N']*5 + ['O']*10 + ['Si']*20``. Can be used in mapping a atom "type" number to a symbol (e.g. in LAMMPS).
625941f3b830903b967e9f03
def forward(self, inputs, inputs_length, hidden_state): <NEW_LINE> <INDENT> embedded = self.embedding(inputs) <NEW_LINE> embedded = self.dropout(embedded) <NEW_LINE> embedded = embedded.transpose(0, 1) <NEW_LINE> inputs_length = np.asarray(inputs_length, dtype=np.long) <NEW_LINE> sorted_indexs = np.argsort(-inputs_leng...
params: inputs: [seq_len, batch_size] LongTensor hidden_state: [num_layers * bidirectional, batch_size, hidden_size] :return outputs: [seq_len, batch, num_directions * hidden_size] hidden_state: (h_n, c_n)
625941f323849d37ff7b3689
def train(self, X, y, X_val, y_val, learning_rate=1e-3, learning_rate_decay=0.95, reg=5e-6, num_iters=100, batch_size=200, verbose=False): <NEW_LINE> <INDENT> num_train = X.shape[0] <NEW_LINE> iterations_per_epoch = max(num_train / batch_size, 1) <NEW_LINE> loss_history = [] <NEW_LINE> train_acc_history = [] <NEW_LINE>...
Train this neural network using stochastic gradient descent. Inputs: - X: A numpy array of shape (N, D) giving training data. - y: A numpy array f shape (N,) giving training labels; y[i] = c means that X[i] has label c, where 0 <= c < C. - X_val: A numpy array of shape (N_val, D) giving validation data. - y_val: A n...
625941f38da39b475bd6557b
def LoadSingleAppInfo(app_info): <NEW_LINE> <INDENT> builder = yaml_object.ObjectBuilder(AppInfoExternal) <NEW_LINE> handler = yaml_builder.BuilderHandler(builder) <NEW_LINE> listener = yaml_listener.EventListener(handler) <NEW_LINE> listener.Parse(app_info) <NEW_LINE> app_infos = handler.GetResults() <NEW_LINE> if len...
Load a single AppInfo object where one and only one is expected. Args: app_info: A file-like object or string. If it is a string, parse it as a configuration file. If it is a file-like object, read in data and parse. Returns: An instance of AppInfoExternal as loaded from a YAML file. Raises: ValueError: ...
625941f3009cb60464c639ac
def send_notification(msg: str, notification_type: str, user_id: int): <NEW_LINE> <INDENT> message = json.dumps({"message": msg, "type": notification_type}) <NEW_LINE> send_message('notifications', message, user_id)
Send notification to the message queue
625941f326238365f5f0f475
def test_message_logged_in(self): <NEW_LINE> <INDENT> with self.client.session_transaction() as s: <NEW_LINE> <INDENT> s[CURR_USER_KEY] = self.testuser1.id <NEW_LINE> <DEDENT> self.client.post("/messages/new", data={ 'text': "Test message." }) <NEW_LINE> msg = Message.query.filter_by(user_id=self.testuser1_id).first() ...
Tests messaging when logged in.
625941f33d592f4c4ed1d65b
@set_module('mxnet.symbol.numpy') <NEW_LINE> def arange(start, stop=None, step=1, dtype=None, ctx=None): <NEW_LINE> <INDENT> if dtype is None: <NEW_LINE> <INDENT> dtype = 'float32' <NEW_LINE> <DEDENT> if ctx is None: <NEW_LINE> <INDENT> ctx = current_context() <NEW_LINE> <DEDENT> if stop is None: <NEW_LINE> <INDENT> st...
Return evenly spaced values within a given interval. Values are generated within the half-open interval ``[start, stop)`` (in other words, the interval including `start` but excluding `stop`). For integer arguments the function is equivalent to the Python built-in `range` function, but returns an ndarray rather than a...
625941f33539df3088e2e94a
def myPow(self, x, n): <NEW_LINE> <INDENT> if n == 0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> if n < 0: <NEW_LINE> <INDENT> return 1 / self.myPow(x, -n) <NEW_LINE> <DEDENT> if n % 2: <NEW_LINE> <INDENT> return x * self.myPow(x*x, n>>1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.myPow(x*x, n>>1)
:type x: float :type n: int :rtype: float
625941f3b5575c28eb68e605
def set_current_pos(): <NEW_LINE> <INDENT> return steer(_Pos)
Setzt Servo auf zuletzt festgelegte Position.
625941f357b8e32f52483a9e
def gen_label_mat(pm_obj, time_list, mapping_mat): <NEW_LINE> <INDENT> min_time, max_time = time_list[0], time_list[-1] <NEW_LINE> pm_query_sql = session.query(pm_obj.gid, pm_obj.timestamp, pm_obj.pm25) .filter(pm_obj.timestamp >= min_time) .filter(pm_obj.timestamp <= max_time) .order_by(pm_obj.gid...
construct the label matrix, if there is no label for a grid, using Nan to fill in. return: pm_mat: (n_times, n_output=1, n_rows, n_cols)
625941f36fb2d068a760f6a6
def L_model_backward(AL, Y, caches): <NEW_LINE> <INDENT> grads = {} <NEW_LINE> L = len(caches) <NEW_LINE> m = AL.shape[1] <NEW_LINE> Y = Y.reshape(AL.shape) <NEW_LINE> dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)) <NEW_LINE> current_cache = caches[-1] <NEW_LINE> grads["dA" + str(L)], grads["dW" + str(L)], grads...
Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group Arguments: AL -- probability vector, output of the forward propagation (L_model_forward()) Y -- true "label" vector (containing 0 if non-cat, 1 if cat) caches -- list of caches containing: every cache of linear_act...
625941f30a366e3fb873ee1f
def optimize(self, w, b, X, Y, num_iterations, print_cost=False): <NEW_LINE> <INDENT> learning_rate = self.learning_rate <NEW_LINE> costs = [] <NEW_LINE> for i in range(num_iterations): <NEW_LINE> <INDENT> grads, cost = self.propagate(w, b, X, Y) <NEW_LINE> dw = grads["dw"] <NEW_LINE> db = grads["db"] <NEW_LINE> w = w ...
Parameters ---------- w : 2d array-like shape(n_features, 1) b : 1d array-like shape(1,) X : 2d array-like shape(n_features, n_samples) Y : 1d array-like shape(1, n_samples)
625941f3a934411ee3751c94
def set_cost_policy(self, list_of_cost_policy): <NEW_LINE> <INDENT> self.multiple_items_selection_from_kendo_dropdown(self.cost_policy_kendo_dropdown_locator, list_of_cost_policy) <NEW_LINE> price_page_title_element = self.wait().until(EC.element_to_be_clickable(self.price_page_title_locator), 'price page title locator...
Implementing set cost policy functionality :param list_of_cost_policy: :return:
625941f3d58c6744b425825c
def to_sd(self, alpha): <NEW_LINE> <INDENT> _one = K.cast(1, dtype=alpha.dtype) <NEW_LINE> d1 = self.latent_dim - 1 <NEW_LINE> var = (T.polygamma(_one, alpha[:, :d1]) + T.polygamma(_one, alpha[:, -1:])) <NEW_LINE> sigma = T.sqrt(var) <NEW_LINE> return sigma
:param alpha: (Tensor) :return: sigma (Tensor)
625941f3f7d966606f6aa60b
def contains(self, ra, dec): <NEW_LINE> <INDENT> ids=self.polyid(ra, dec) <NEW_LINE> if self.is_veto_mask: <NEW_LINE> <INDENT> return numpy.where(ids >= 0, 0, 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return numpy.where(ids >= 0, 1, 0)
Determine of the input ra,dec points are masked. parameters ---------- mangle_url: string The location of the mangle file ra: array or scalar right ascension in degrees dec: array or scalar declination in degrees output ------ A numpy array, 1 if unmasked 0 if masked. Note for veto masks, you will "keep"...
625941f33617ad0b5ed684f5
def __add_callback(self, type_, func, serialised_if_crud=True): <NEW_LINE> <INDENT> Validation.callable_check(func) <NEW_LINE> with self.__callbacks: <NEW_LINE> <INDENT> self.__callbacks[type_].append((func, serialised_if_crud))
sync_if_crud indicates whether to serialise this callback (applies only to CRUD)
625941f33539df3088e2e94b
def test_starttls_response_repr(self): <NEW_LINE> <INDENT> resp = pureldap.LDAPStartTLSResponse(resultCode=0) <NEW_LINE> resp_repr = "LDAPStartTLSResponse()" <NEW_LINE> self.assertEqual(repr(resp), resp_repr)
LDAPStartTLSResponse.__repr__
625941f33eb6a72ae02ecaee
def difference(self, *args, **kwargs): <NEW_LINE> <INDENT> pass
用于计算set中相对给定集合的差集 {1,2,3}.difference({3,4,5}) -> {1, 2}
625941f3287bf620b61d405f
def _turns_left(self) -> bool: <NEW_LINE> <INDENT> if self.game.current_turn < len(self.game.scoreboard.index) - 1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Function which can be used to check if there is any turns left in the game (rows in the game scoreboard) Returns: boolean: True if game has turns left, else False
625941f307d97122c4178e99
def precision(actual, predictions): <NEW_LINE> <INDENT> tp = len(np.intersect1d(np.where(predictions == 1), np.where(actual == 1))) <NEW_LINE> predictions_positives = np.count_nonzero(predictions == 1) <NEW_LINE> return tp / predictions_positives
INPUT (assumes positive = 1 and negative = 0) :param actual: actual values as a numpy array or pandas series :param predictions: predictions as a numpy array or pandas series :return: returns the precision as a float
625941f3a4f1c619b28b0629
def hovmoller(data_array, xdim, ydim, how='mean', cmap='viridis'): <NEW_LINE> <INDENT> time_groups = ['year', 'month', 'day', 'hour', 'minute', 'second', 'dayofyear', 'week', 'dayofweek', 'weekday', 'quarter'] <NEW_LINE> x_da_dim = xdim in list(data_array.dims) <NEW_LINE> x_tg_dim = xdim in time_groups <NEW_LINE> if x_...
Make a Hovmoller plot
625941f3c432627299f0524a
def read_value(self): <NEW_LINE> <INDENT> raise NotImplementedError
Read a complex value from the lock-in. This method should not wait before taking a measurement. The framework ensures a proper wait time.
625941f3507cdc57c63072e9
def test_service_rbac_no_permission(appliance, role_user_group): <NEW_LINE> <INDENT> role, user = role_user_group <NEW_LINE> error_message = ("The user's role is not authorized for any access, " "please contact the administrator!") <NEW_LINE> with pytest.raises(Exception, match=error_message): <NEW_LINE> <INDENT> with ...
Test service rbac without user permission Polarion: assignee: apagac initialEstimate: 1/4h casecomponent: Services
625941f38e71fb1e9831dda6
def dot(u,v): <NEW_LINE> <INDENT> assert u.D == v.D <NEW_LINE> return sum(u.f[key] * v.f[key] for key in set(u.f.keys()) & set(v.f.keys()))
Returns the dot product of the two vectors. >>> u1 = Vec({'a','b'}, {'a':1, 'b':2}) >>> u2 = Vec({'a','b'}, {'b':2, 'a':1}) >>> u1*u2 5 >>> u1 == Vec({'a','b'}, {'a':1, 'b':2}) True >>> u2 == Vec({'a','b'}, {'b':2, 'a':1}) True >>> v1 = Vec({'p','q','r','s'}, {'p':2,'s':3,'q':-1,'r':0}) >>> v2 = Vec({'p','q','r','s'},...
625941f394891a1f4081c0ac
def packageName(self): <NEW_LINE> <INDENT> if self.type is DependencyType.Lib: <NEW_LINE> <INDENT> if self.name.lower().startswith("lib"): <NEW_LINE> <INDENT> return "lib-{}".format(self.name[3:].lower()) <NEW_LINE> <DEDENT> return "lib-{}".format(self.name.lower()) <NEW_LINE> <DEDENT> if self.type is DependencyType.Pl...
Give the name of the package for the dependency
625941f36aa9bd52df0373a7
def unprovide(self, requirement, environ, local_state_file, overrides, requirement_status=None): <NEW_LINE> <INDENT> project_dir = environ['PROJECT_DIR'] <NEW_LINE> filename = os.path.abspath(os.path.join(project_dir, requirement.filename)) <NEW_LINE> try: <NEW_LINE> <INDENT> if os.path.isdir(filename): <NEW_LINE> <IND...
Override superclass to delete the downloaded file.
625941f373bcbd0ca4b2c675
def test_non_existent(self): <NEW_LINE> <INDENT> UnknownClass = java.FindClass("java/XXX") <NEW_LINE> self.assertIsNone(UnknownClass.value) <NEW_LINE> Example = java.FindClass("org/pybee/rubicon/test/Example") <NEW_LINE> self.assertIsNotNone(Example.value) <NEW_LINE> self.assertIsNone(java.GetMethodID(Example, "xxx", "...
Non-existent classes/methods/fields return None from Find/Get APIs
625941f3adb09d7d5db6cd8b
def toDF(self): <NEW_LINE> <INDENT> if not check_package('pandas'): <NEW_LINE> <INDENT> warnings.warn('Pandas not found!') <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> import pandas as pd <NEW_LINE> <DEDENT> df = pd.DataFrame({'t': self.t, 'I': self.I }) <NEW_LINE> if self.synthetic: <NEW_LINE> <INDE...
Export to pandas dictionary
625941f3099cdd3c635f1257
def run(self, page): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import mdpopups <NEW_LINE> import pymdownx <NEW_LINE> has_phantom_support = (mdpopups.version() >= (1, 10, 0)) and (int(sublime.version()) >= 3124) <NEW_LINE> fmatter = mdpopups.format_frontmatter(frontmatter) if pymdownx.version_info[:3] >= (4, 3, 0) el...
Open page.
625941f3046cf37aa974d341
def is8kmBMNGFile(filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if filename.index('5400') >= 0 : <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> except: pass <NEW_LINE> return False
Returns True or False. Only checks the filename/substring: full path is not required, no 'stat' or I/O check
625941f38e05c05ec3eea979
def __init__(self): <NEW_LINE> <INDENT> self.screen_width = 1200 <NEW_LINE> self.screen_height = 800 <NEW_LINE> self.bg_color = (230, 230, 230) <NEW_LINE> self.ship_speed_factor = 1.5 <NEW_LINE> self.ship_limit = 3 <NEW_LINE> self.bullet_speed_factor = 10 <NEW_LINE> self.bullet_width = 3 <NEW_LINE> self.bullet_height =...
Initialize the game's static settings.
625941f3b545ff76a8914415
def handle(self, factory, request): <NEW_LINE> <INDENT> pass
Handle a Git request. Args: factory (:class:`Factory`): The application object. request (:class:`IRequest`): The request that needs to be handled.
625941f36aa9bd52df0373a8
def test_payment_card_save_business(self): <NEW_LINE> <INDENT> payment_card = FundingSources.get_business_payment_card() <NEW_LINE> updated = self.client.funding_sources.payment_card.save( payment_card.token, self.token_update_request) <NEW_LINE> verify = FundingSources.get_funding_source_verify(payment_card) <NEW_LINE...
Updates a payment card for a business.
625941f382261d6c526abaa8
def stop_scan(self): <NEW_LINE> <INDENT> self.mutex_running.acquire() <NEW_LINE> if self.isRunning(): <NEW_LINE> <INDENT> self.clamav_instance.stop_scan() <NEW_LINE> self.running = False <NEW_LINE> self.inform(_("scan stopped")) <NEW_LINE> <DEDENT> self.mutex_running.release()
Manual stop scan
625941f3b7558d58953c5506
def _matchremove_simple_endings(self, word): <NEW_LINE> <INDENT> was_stemmed = False <NEW_LINE> simple_endings = ['ibus', 'ius', 'ae', 'am', 'as', 'em', 'es', 'ia', 'is', 'nt', 'os', 'ud', 'um', 'us', 'a', 'e', 'i', 'o', 'u'] <NEW_LINE> for ending in simple_endings: <NEW_LINE> <INDENT> if word.endswith(ending): <NEW_LI...
Remove the noun, adjective, adverb word endings
625941f38c3a8732951589c2
def size(self): <NEW_LINE> <INDENT> labels, _, ngroups = self.group_info <NEW_LINE> bin_counts = Series(labels).value_counts() <NEW_LINE> bin_counts = bin_counts.reindex(np.arange(ngroups)) <NEW_LINE> bin_counts.index = self.result_index <NEW_LINE> return bin_counts
Compute group sizes
625941f34f6381625f11503b
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <...
Returns the model properties as a dict
625941f307f4c71912b11a85
def connectingLine(src, dest): <NEW_LINE> <INDENT> loc = spaceLocator() <NEW_LINE> line = annotate(loc, tx='').getParent() <NEW_LINE> line.setParent(src) <NEW_LINE> line.t.set(0, 0, 0) <NEW_LINE> shape = line.getShape() <NEW_LINE> shape.overrideEnabled.set(True) <NEW_LINE> shape.overrideDisplayType.set(1) <NEW_LINE> lo...
Draw an annotation arrow from the src to the dest.
625941f3627d3e7fe0d69452
def on_registered(self, driver, executor, framework, slave): <NEW_LINE> <INDENT> log.debug("{function} not implemented".format(function=sys._getframe().f_code.co_name))
Event handler triggered when the executor driver has been able to successfully connect with Mesos. In particular, a scheduler can pass some data to its executors through the FrameworkInfo.ExecutorInfo's data field. Parameters ---------- driver: ExecutorDriver Interface for interacting with Mesos Agent executor: ...
625941f35fdd1c0f98dc0835
def shufflenet_v2_x2_0(pretrained=False, progress=True, quantize=False, **kwargs): <NEW_LINE> <INDENT> return _shufflenetv2('shufflenetv2_x2.0', pretrained, progress, quantize, [4, 8, 4], [24, 244, 488, 976, 2048], **kwargs)
Constructs a ShuffleNetV2 with 2.0x output channels, as described in `"ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design" <https://arxiv.org/abs/1807.11164>`_. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of t...
625941f3b7558d58953c5507
def execute(self, out=None, err=None): <NEW_LINE> <INDENT> old_stdout = sys.stdout <NEW_LINE> output = StringIO() <NEW_LINE> out_writer = Writer() <NEW_LINE> out_writer.add_writer(output, old_stdout.isatty()) <NEW_LINE> if out: <NEW_LINE> <INDENT> out_writer.add_writer(out) <NEW_LINE> <DEDENT> sys.stdout = out_writer <...
Execute command action both stdout and stderr from the command are captured and saved on self.out/err. Real time output is controlled by parameters @param out: None - no real time output a file like object (has write method) @param err: idem @return failure: see CmdAction.execute
625941f3379a373c97cfb147
def decode(self, pdu): <NEW_LINE> <INDENT> if _debug: BVLCI._debug("decode %s", str(pdu)) <NEW_LINE> PCI.update(self, pdu) <NEW_LINE> self.bvlciType = pdu.get() <NEW_LINE> if self.bvlciType != 0x81: <NEW_LINE> <INDENT> raise DecodingError("invalid BVLCI type") <NEW_LINE> <DEDENT> self.bvlciFunction = pdu.get() <NEW_LIN...
decode the contents of the PDU into the BVLCI.
625941f3956e5f7376d7146b
def buy( self, price, amount, expiration=None, killfill=False, account=None, returnOrderId=False ): <NEW_LINE> <INDENT> if not expiration: <NEW_LINE> <INDENT> expiration = self.bitshares.config["order-expiration"] <NEW_LINE> <DEDENT> if not account: <NEW_LINE> <INDENT> if "default_account" in self.bitshares.config: <NE...
Places a buy order in a given market :param float price: price denoted in ``base``/``quote`` :param number amount: Amount of ``quote`` to buy :param number expiration: (optional) expiration time of the order in seconds (defaults to 7 days) :param bool killfill: flag that indicates if the order shall be killed if it is...
625941f38e7ae83300e4b5cf
def get_stats(self, column): <NEW_LINE> <INDENT> values = self.get_values(column) <NEW_LINE> if not values: <NEW_LINE> <INDENT> dict(mean=0, minimum=0, maximum=0, stddev=0, count=0) <NEW_LINE> <DEDENT> num_items = len(values) <NEW_LINE> mean = sum(values) / num_items <NEW_LINE> diffs = [x - mean for x in values] <NEW_L...
Gets a dictionary stats about the specified column.
625941f332920d7e50b287d5
def get_comments(self): <NEW_LINE> <INDENT> pass
Get freeform comments about a source from text database.
625941f3baa26c4b54cb1719
def run(): <NEW_LINE> <INDENT> r = PulseAnalyzer() <NEW_LINE> print("Starting pulse analysis. When done quit with CTRL-C.") <NEW_LINE> r.measure_pulses(meastime=1.0)
Creates an instance of PulseAnalyzer and runs a simple pulse measurement.
625941f35fdd1c0f98dc0836
def get(self, url: str, headers: dict = None, data: str = None, allow_redirects: bool = None) -> 'MockResponse': <NEW_LINE> <INDENT> self.last_request = MockRequest(url, headers, data, request_type='GET', allow_redirects=allow_redirects) <NEW_LINE> return self._find_response(url)
Mock for requests.get function.
625941f37047854f462a1a02
def StartServer(self): <NEW_LINE> <INDENT> is_posix = sys.platform.startswith('linux') or sys.platform == 'darwin' <NEW_LINE> logging.info('Starting Web-Page-Replay: %s', self._cmd_line) <NEW_LINE> self._CreateTempLogFilePath() <NEW_LINE> with open(self._temp_log_file_path, 'w') as log_fh: <NEW_LINE> <INDENT> self.repl...
Start Web Page Replay and verify that it started. Returns: A dictionary mapping the keys 'http', 'https', and (if used) 'dns' to the respective ports of the replay server. Raises: ReplayNotStartedError: if Replay start-up fails.
625941f36fb2d068a760f6a7
def make_router(): <NEW_LINE> <INDENT> global router <NEW_LINE> router = urls.make_router( ('GET', '^/?$', index), (None, '^/admin/accounts(?=/|$)', accounts.route_admin_class), (None, '^/admin/formulas(?=/|$)', formulas.route_admin_class), (None, '^/admin/sessions(?=/|$)', sessions.route_admin_class), (None, '^/admin/...
Return a WSGI application that searches requests to controllers
625941f3ec188e330fd5ad92
def _check_before_run(self): <NEW_LINE> <INDENT> if not osp.exists(self.dataset_dir): <NEW_LINE> <INDENT> raise RuntimeError("'{}' is not available".format(self.dataset_dir)) <NEW_LINE> <DEDENT> if not osp.exists(self.img_dir): <NEW_LINE> <INDENT> raise RuntimeError("'{}' is not available".format(self.img_dir)) <NEW_LI...
Check if all files are available before going deeper
625941f3bd1bec0571d90c2f
def __init__(self, line): <NEW_LINE> <INDENT> super(HETNAM, self).__init__(line) <NEW_LINE> self.hetID = line[11:14].strip() <NEW_LINE> self.text = line[15:70].strip()
Initialize by parsing line COLUMNS TYPE FIELD DEFINITION ----------------------------------------------------- 12-14 string hetID Het identifier, right-justified. 16-70 string text Chemical name.
625941f399cbb53fe67931e4
def testColorsNoBase(self): <NEW_LINE> <INDENT> dummyScheme = DummyColorScheme() <NEW_LINE> colors = dummyScheme.fetchColors() <NEW_LINE> self.assertEqual( len(colors), 2 ) <NEW_LINE> self.assertEqual( colors[0][0], QColor( 255, 0, 0 ) ) <NEW_LINE> self.assertEqual( colors[0][1], 'red') <NEW_LINE> self.assertEqual( col...
Test getting colors without passing a base color
625941f3b5575c28eb68e606
def __init__( self, hard: dict = None, used: dict = None, ): <NEW_LINE> <INDENT> super(ResourceQuotaStatus, self).__init__( api_version="core/v1", kind="ResourceQuotaStatus" ) <NEW_LINE> self._properties = { "hard": hard if hard is not None else {}, "used": used if used is not None else {}, } <NEW_LINE> self._types = {...
Create ResourceQuotaStatus instance.
625941f399fddb7c1c9de98d
def playHand(hand, wordList, n): <NEW_LINE> <INDENT> totalScore = 0 <NEW_LINE> while calculateHandlen(hand) > 0: <NEW_LINE> <INDENT> print('Current Hand: ',end = '') <NEW_LINE> displayHand(hand) <NEW_LINE> inp = input('Enter word, or a "." to indicate that you are finished: ') <NEW_LINE> if inp == '.': <NEW_LINE> <INDE...
Allows the user to play the given hand, as follows: * The hand is displayed. * The user may input a word or a single period (the string ".") to indicate they're done playing * Invalid words are rejected, and a message is displayed asking the user to choose another word until they enter a valid word or "." * When ...
625941f30c0af96317bb87e7
def getvalue_ordefault(self, key): <NEW_LINE> <INDENT> val = self.getvalue(key) <NEW_LINE> if val is not None: <NEW_LINE> <INDENT> return val <NEW_LINE> <DEDENT> val = self.__mappings__.get(key).get_default_value() <NEW_LINE> logging.debug('<%s object> using default value for %s: %s' % (self.__class__.__name__, key, re...
获取字段value,会去找Field定义的default
625941f366673b3332b92691
def save(self, path: str) -> None: <NEW_LINE> <INDENT> self.data = self.data.astype(np.uint8) <NEW_LINE> pri_hdu = fits.PrimaryHDU(data=self.data) <NEW_LINE> for k, v in self.metadata.items(): <NEW_LINE> <INDENT> if k != 'COMMENT': <NEW_LINE> <INDENT> pri_hdu.header[k] = v <NEW_LINE> <DEDENT> <DEDENT> map_val = [] <NEW...
Write out a thematic map FITS :param path: where to save thematic maps fits file :return:
625941f360cbc95b062c6b44
def list( self, resource_group_name: str, network_interface_name: str, **kwargs: Any ) -> AsyncIterable["_models.NetworkInterfaceIPConfigurationListResult"]: <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } ...
Get all ip configurations in a network interface. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param network_interface_name: The name of the network interface. :type network_interface_name: str :keyword callable cls: A custom type or function that will be passed the direc...
625941f376d4e153a657f133
def color_string(self): <NEW_LINE> <INDENT> color_start = '\033[00m' <NEW_LINE> if self.name == "OPEN": <NEW_LINE> <INDENT> color_start = '\033[32m' <NEW_LINE> <DEDENT> elif self.name == "BUSY": <NEW_LINE> <INDENT> color_start = '\033[31m' <NEW_LINE> <DEDENT> return [color_start, '\033[00m']
Returns the correct color start and finish sequence :returns: A list where the first entry is the start of a color sequence, and the second entry is the ending of the color sequence
625941f3851cf427c661ab0a
def resolve_function_from_operation_id(self, operation_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> module_name, view_name, meth_name = operation_id.rsplit('.', 2) <NEW_LINE> if operation_id and not view_name.endswith('View'): <NEW_LINE> <INDENT> return self.function_resolver(operation_id) <NEW_LINE> <DEDENT> mod ...
Invokes the function_resolver :type operation_id: str
625941f345492302aab5e8ca
def grade_is_valid(self, grade: str) -> bool: <NEW_LINE> <INDENT> if grade in self.grades_available: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Return True if grade in available grades in XML. False otherwise.
625941f3090684286d50f2f1
def getChatCounter(self, userID, friendID, message): <NEW_LINE> <INDENT> client = findClient(userID, self.clients) <NEW_LINE> return client.setMessage(friendID, message)
gets the count on the number of messages sent to the friend
625941f3cdde0d52a9e53639
def __iso(s): <NEW_LINE> <INDENT> if s.startswith('http://') or s.startswith('tftp://') or s.startswith('https://'): <NEW_LINE> <INDENT> tmp_iso = '/tmp/ubuntu-16-server.iso' <NEW_LINE> if os.path.isfile(tmp_iso): <NEW_LINE> <INDENT> LOG.info('File %s already exists.' % tmp_iso) <NEW_LINE>...
If @s is a string that starts with
625941f3d53ae8145f87a864
def get_device_name(self, device): <NEW_LINE> <INDENT> name = next(( result.name for result in self.last_results if result.mac == device), None) <NEW_LINE> return name
Return the name of the given device or None if we don't know.
625941f3fb3f5b602dac3c9b
def __reduce__(self) -> Tuple[Callable, Tuple[object]]: <NEW_LINE> <INDENT> return (ImmutableDict, (list(self.items()),))
Making ImmutableDict work with newer versions of pickle protocol. Without this, it uses the default behavior on loading which tries to create an empty dict and then set its items, which is not an allowed operation on ImmutableDict. In general, there are higher level functions to be redefined for pickle customization,...
625941f37b25080760e39a56
def logout(request, next_page=None, template_name='logged_out.html', redirect_field_name=REDIRECT_FIELD_NAME, current_app=None, extra_context=None): <NEW_LINE> <INDENT> auth_logout(request) <NEW_LINE> if next_page is not None: <NEW_LINE> <INDENT> next_page = resolve_url(next_page) <NEW_LINE> <DEDENT> if (redirect_field...
Logs out the user and displays 'You are logged out' message.
625941f37cff6e4e81117f86
@click.command("submit") <NEW_LINE> @click.argument("url") <NEW_LINE> @click.argument("files", nargs=-1, type=click.Path(exists=True), required=True) <NEW_LINE> @submit_options <NEW_LINE> @click.option("--verbose", "-v", is_flag=True, help="show verbose test results") <NEW_LINE> def action_submit(url, files, select_mac...
submit a test report to the server
625941f330bbd722463cc3ca
@app.route('/nbmnhook', methods=['POST'], strict_slashes=False) <NEW_LINE> def github_push_hook(): <NEW_LINE> <INDENT> hook_type = request.headers.get('X-GitHub-Event', 'NO-HEADER-FOUND!!!') <NEW_LINE> if hook_type != 'push': <NEW_LINE> <INDENT> log.info("Only GitHub push events used, recvd %s" % hook_type) <NEW_LINE> ...
Github is telling us what is up.
625941f39b70327d1c4e13d9
def RunStory(self, results): <NEW_LINE> <INDENT> raise NotImplementedError()
Override to do any action before running each one of all stories that share this same state. This method is styled on unittest.TestCase.run.
625941f35510c4643540f9d5
def ensure_price(stock: str, price): <NEW_LINE> <INDENT> return round(price, 3) if stock.startswith(('16', '50', '15', '51', '18', '13', '90', '204')) else round(price, 2)
格式化价格 :param price: 价格 :param stock: 股票编码 :return: 格式化后的价格
625941f3f548e778e58cdb81
def __init__(self, name, url, description): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.url = url <NEW_LINE> self.description = description
Constructs a Page object against a given name, url and description. Args: name (str): the page name. url (str): the page url. It shall not contain the .html suffix. description (str): the page description.
625941f323849d37ff7b368b
def test_login_success(self): <NEW_LINE> <INDENT> self.login('13601973055', '123456') <NEW_LINE> self.dr.implicitly_wait(2) <NEW_LINE> companies = self.dr.find_element_by_class_name('card-box').find_elements_by_tag_name('li') <NEW_LINE> if len(companies) > 1: <NEW_LINE> <INDENT> companies[0].click() <NEW_LINE> <DEDENT>...
用户名、密码正确
625941f38da39b475bd6557d
def reset_all_user_profile(): <NEW_LINE> <INDENT> for up in UserProfile.objects.all(): <NEW_LINE> <INDENT> up.delete()
Reset to a clean state by deleting all user profiles
625941f326238365f5f0f477
def test_findInstructionCodeInsFlagReg(self): <NEW_LINE> <INDENT> self.parser.relativeAddress = 0 <NEW_LINE> instruction = self.parser._findInstructionCode("InsFlagReg", "JMP") <NEW_LINE> self.assertEqual(instruction, bytes((0b01010001,))) <NEW_LINE> self.assertEqual(self.parser.relativeAddress, 2) <NEW_LINE> instructi...
Tests the method: _findInstructionCode(self, form, line, instruction) for instruction in STATE10 (InsFlagReg)
625941f301c39578d7e7543c
def Results(self): <NEW_LINE> <INDENT> return self.cursor.fetchall()
Return the results from the last search query.
625941f394891a1f4081c0ad
def radial_sublength(self): <NEW_LINE> <INDENT> return self.EtaR.numel() * self.ShfR.numel()
Returns the length of radial subaev of a single species
625941f3d268445f265b5470
def __init__(self, parameters): <NEW_LINE> <INDENT> self.parameters = parameters <NEW_LINE> self.results = [] <NEW_LINE> self.ncandidates = 10 <NEW_LINE> self.fcandidates = 2.0 <NEW_LINE> self.initial = 10 <NEW_LINE> self.nnearest = 20 <NEW_LINE> self.red = None <NEW_LINE> self.last_reload = 0
Explore a parameter space using random maximum discrepancy sequences. :param parameters: ParameterSet to be explored.
625941f38a43f66fc4b5465f
def __init__(self, channel): <NEW_LINE> <INDENT> self.GetGeographicView = channel.unary_unary( '/google.ads.googleads.v1.services.GeographicViewService/GetGeographicView', request_serializer=google_dot_ads_dot_googleads__v1_dot_proto_dot_services_dot_geographic__view__service__pb2.GetGeographicViewRequest.SerializeToSt...
Constructor. Args: channel: A grpc.Channel.
625941f356ac1b37e62647c4
def test_device_tests_with_packages(self): <NEW_LINE> <INDENT> distribution_model = "default" <NEW_LINE> image_url = 'http://image/url/image.bin' <NEW_LINE> test_list = {'device':"foo,bar,baz"} <NEW_LINE> testrun_id = "" <NEW_LINE> storage_address = "" <NEW_LINE> test_filter = "-testsuite=testrunner-tests" <NEW_LINE> t...
Check conductor command with test packages for device
625941f3460517430c394775
def convert_format(self,text): <NEW_LINE> <INDENT> return BeautifulSoup(text, 'lxml').text
去掉文本中的标签 @text: 包含html的文本,string return: 不包含html的文本
625941f33539df3088e2e94d
def __str__(self): <NEW_LINE> <INDENT> report_as_list = [self.__class__.__name__ + ":", "New column", self.name, "is true where input data column", self.source_name, english_relationship(self.relationship), str(self.condition)] <NEW_LINE> report_as = " ".join(report_as_list) <NEW_LINE> if self.preq_column != "": <NEW_L...
str representation Examples: >>> print(NumMapCondition({"Condition" : 4, "New Column Name" : "test new column name", "Relationship" : "ge", "Prerequisite" : "preq_two", "Source Column ID" : "source_test"})) NumMapCondition: New column test new column name is true where input data column source_test is gr...
625941f33eb6a72ae02ecaf0
def exitVersion(self, ctx: blackbirdParser.VersionContext): <NEW_LINE> <INDENT> self._program._version = ctx.versionnumber().getText()
Run after exiting version metadata. Args: ctx: VersionContext
625941f3167d2b6e31219195
def edit_channel(channelInfo, **kw): <NEW_LINE> <INDENT> context.session.assertPerm('admin') <NEW_LINE> channel = get_channel(channelInfo, strict=True) <NEW_LINE> fields = ('description', 'comment', 'name') <NEW_LINE> changes = [] <NEW_LINE> for field in fields: <NEW_LINE> <INDENT> if field in kw and kw[field] != chann...
Edit information for an existing channel. :param str/int channelInfo: channel name or ID :param str name: new channel name :param str description: description of channel :param str comment: comment about channel
625941f35166f23b2e1a575a
def add_comment(self, comment): <NEW_LINE> <INDENT> self._add(comment, pre="# ")
Add a comment
625941f3c432627299f0524c
def MapUserFile(self, profile_path, registry_file): <NEW_LINE> <INDENT> self._user_registry_files[profile_path.upper()] = registry_file
Maps the user Windows Registry file to a specific profile path. Args: profile_path (str): profile path. registry_file (WinRegistryFile): user Windows Registry file.
625941f31b99ca400220b0b5
def circle_statistic(self, lat, lng, radius, **kwargs): <NEW_LINE> <INDENT> if lat is None: <NEW_LINE> <INDENT> raise ValueError("Missing the required parameter `lat` when calling `circle_statistic`") <NEW_LINE> <DEDENT> if lng is None: <NEW_LINE> <INDENT> raise ValueError("Missing the required parameter `lng` when cal...
Heatmap information of a region Returns a set of cells with the number of video counts :param str lat: Latitude (required) :param str lng: Longitude (required) :param str radius: Radius (required) :param str startdate: Start Date :param str enddate: End Date :return: str
625941f3507cdc57c63072eb
def find_headers_html(file_contents: str, depth: int = 1) -> List[str]: <NEW_LINE> <INDENT> if depth < 1 or depth > 6: <NEW_LINE> <INDENT> raise ValueError("Depth must be between 1 and 6") <NEW_LINE> <DEDENT> headers = [line for line in file_contents.split("\n") if f"<h{depth}>" in line] <NEW_LINE> headers = [ header.r...
Find headers in file.
625941f3d7e4931a7ee9e521
def SavingTestData(tv,ytest,ymin,ymax,err,path,name,iter_no = 0): <NEW_LINE> <INDENT> tv = np.hstack((tv,ytest)) <NEW_LINE> Prediction = DeNormImage(tv,ymin,ymax) <NEW_LINE> localpath = path +'Testing/' <NEW_LINE> if not os.path.isdir(localpath): <NEW_LINE> <INDENT> os.makedirs(localpath) <NEW_LINE> <DEDENT> Data={'dat...
Function to save the testing data every iteration. Inputs: tv: Predictions on testing dataset. Same shape as ytest. ytest: Testing dataset, numpy array. ymin,ymax: Data statistics for reversing normalization. Must be broadcastable if array. err: numpy array, same shape as ytest. Gives stddev for...
625941f3cb5e8a47e48b80a1
def _set_look_east_movement(self: "Thornton", units :int): <NEW_LINE> <INDENT> if self._current_look_num <= units: <NEW_LINE> <INDENT> self.image = pygame.image.load("tan_enemy_east0.png") <NEW_LINE> self._looking_east = True <NEW_LINE> self._current_look_num += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._ins...
Takes units of movement and sets the necessary attributes for a look east movement.
625941f3aad79263cf39104c
def led_blink(speed = 0.3, blinks = 10): <NEW_LINE> <INDENT> global pin_led <NEW_LINE> count = blinks <NEW_LINE> while count != 0: <NEW_LINE> <INDENT> GPIO.output(pin_led, 1) <NEW_LINE> time.sleep(speed) <NEW_LINE> GPIO.output(pin_led, 0) <NEW_LINE> time.sleep(speed) <NEW_LINE> count -= 1
This function make led(s) blink with default speed (in seconds) and default number of blinks
625941f3796e427e537b0bcd
def retrieve_picture_by_key(self, key): <NEW_LINE> <INDENT> if key in _PICTURE_CACHE: <NEW_LINE> <INDENT> return _PICTURE_CACHE.get(key) <NEW_LINE> <DEDENT> self.logger.debug("retrieve_picture_by_key(%s)", repr(key)) <NEW_LINE> stmt = 'SELECT id, identifier, path, description ' 'FROM pictures WHERE "id"=$...
Retrieve picture by key. :param key: the id of the picture :type key: int :return: picture. :rtype: Picture
625941f330c21e258bdfaaa6
def get_scope_specifiers(request, domain, perm): <NEW_LINE> <INDENT> if not isinstance(request.auth, TokenAuth): <NEW_LINE> <INDENT> return set() <NEW_LINE> <DEDENT> scope_domains = request.auth.scope_domains <NEW_LINE> specifiers = {s[1] for s in scope_domains.get(domain, []) if perm in s[0]} <NEW_LINE> if not specifi...
Return restricting scope specifiers for a domain and a permission. Examples with perm "read" and domain "domain": scopes "read:domain:helmet read:domain:foo read:other_domain:bar write:domain:baz" -> {'helmet', 'foo'} scopes "read:domain" -> {} scopes "read:domain:helmet read:domain" -> {} (a missing specifier overri...
625941f3ab23a570cc250789
def breadth_first_search(problem): <NEW_LINE> <INDENT> fringe = Queue() <NEW_LINE> been_there = [] <NEW_LINE> fringe.push((problem.get_start_state(), [])) <NEW_LINE> while True: <NEW_LINE> <INDENT> if fringe.isEmpty(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> current_board, actions = fringe.pop() <NEW_LINE> ...
Search the shallowest nodes in the search tree first.
625941f307d97122c4178e9c
@app.route('/api/gs1/', methods=['GET', 'POST']) <NEW_LINE> @cross_origin() <NEW_LINE> def get_gs1(): <NEW_LINE> <INDENT> parser = reqparse.RequestParser() <NEW_LINE> parser.add_argument('gtin', type=str, required=True) <NEW_LINE> params = parser.parse_args() <NEW_LINE> data = gs1.get_gtin(params.get('gtin')) <NEW_LINE...
Call the cloud.gs1.org service to retrieve data based on the gtin.
625941f35fc7496912cc3f7f
def acceptFromImport(self, pofile, suggestion, share_with_other_side=False, lock_timestamp=None): <NEW_LINE> <INDENT> template = pofile.potemplate <NEW_LINE> traits = getUtility(ITranslationSideTraitsSet).getTraits( template.translation_side) <NEW_LINE> if traits.getFlag(suggestion): <NEW_LINE> <INDENT> return <NEW_LIN...
Accept a suggestion coming from a translation import. When importing translations, these are first added as a suggestion and only after successful validation they are made current. This is slightly different to approving a suggestion because no reviewer is credited. :param pofile: The `POFile` that the suggestion is ...
625941f30383005118ecfbe2
def is_initial_tag(self, current_tag_version: str, is_yes: bool = False) -> bool: <NEW_LINE> <INDENT> is_initial = False <NEW_LINE> if not git.tag_exist(current_tag_version): <NEW_LINE> <INDENT> if is_yes: <NEW_LINE> <INDENT> is_initial = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out.info(f"Tag {current_tag_ve...
Check if reading the whole git tree up to HEAD is needed.
625941f36aa9bd52df0373a9
def scan_library(path=""): <NEW_LINE> <INDENT> method = 'VideoLibrary.Scan' <NEW_LINE> params = {'directory': path} <NEW_LINE> return json_rpc(method, params)
Start a library scanning in a specified folder
625941f3a17c0f6771cbe650