code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, V1beta2ScaleStatus): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict()
Returns true if both objects are equal
625941e926238365f5f0f32e
def register_filter(self, exception_filter): <NEW_LINE> <INDENT> for filter in self: <NEW_LINE> <INDENT> if (type(exception_filter.exception('')) == type(filter.exception(''))): <NEW_LINE> <INDENT> txt = 'You can only have one filter for one exception: %s' % ( exception_filter.exception) <NEW_LINE> raise Exception(txt)...
Registers an ExceptionFilter. :Parameters: - `exception_filter`: the ExceptionFilter to add.
625941e960cbc95b062c69fd
def test_ports(self): <NEW_LINE> <INDENT> metadatas = {} <NEW_LINE> metadatas["open_ports"] = "1" <NEW_LINE> metadatas["udp_open_ports"] = "1" <NEW_LINE> product = Product(PRODUCT_NAME, PRODUCT_VERSION, True, metadatas) <NEW_LINE> self.assertEquals(len(product.get_tcp_ports()), 2) <NEW_LINE> self.assertEquals(len(produ...
test the functionalities to get tcp and udp ports for the product
625941e9d8ef3951e32439f7
@functools.lru_cache() <NEW_LINE> def read(metafile): <NEW_LINE> <INDENT> with metafile.open(encoding="utf-8") as f: <NEW_LINE> <INDENT> return f.read()
Return the contents of the given meta data file assuming UTF-8 encoding.
625941e9ab23a570cc250640
def evolve(context): <NEW_LINE> <INDENT> root = zope.generations.utility.getRootFolder(context) <NEW_LINE> context.connection.root()._p_changed = True <NEW_LINE> root._p_changed = True
Update the root folder to be a ``zope.site.folder.Folder`` instead of ``zope.app.folder.folder.Folder``.
625941e944b2445a3393254c
def read_memory(self, state, query): <NEW_LINE> <INDENT> n_queries = tf.shape(query)[0] <NEW_LINE> memory, salience, index_float = state <NEW_LINE> index = tf.cast(index_float, tf.int32) <NEW_LINE> normed_query = tf.nn.l2_normalize(query, dim=1) <NEW_LINE> normed_memory = tf.nn.l2_normalize(memory, dim=2) <NEW_LINE> si...
Read from the memory extension :param state: tuple of state tensors (memory, salience, index), with batch size of 1 :param query: batch of vectors to match against the memory :return: attention over memories, retrieved memory weighted by attention
625941e9187af65679ca55d9
def get_names(self): <NEW_LINE> <INDENT> names = cmd.Cmd.get_names(self) <NEW_LINE> for p in self.plugin_names: <NEW_LINE> <INDENT> names.append('do_' + p) <NEW_LINE> <DEDENT> return names
override default method to auto-complete plug-ins names
625941e90c0af96317bb86a1
def create_instance(self, instance_name, instance_db_name): <NEW_LINE> <INDENT> INSTANCE_DIR = os.path.join(icc.DEFAULT_INSTANCE_DIR, instance_name) <NEW_LINE> try: <NEW_LINE> <INDENT> shutil.copytree(icc.SKEL_DIR, INSTANCE_DIR) <NEW_LINE> os.chdir(INSTANCE_DIR) <NEW_LINE> template = os.path.join(INSTANCE_DIR, 'instanc...
Create the main instance in the instances directory.
625941e95166f23b2e1a5613
def rotate_transpose(x, shift, name="rotate_transpose"): <NEW_LINE> <INDENT> with ops.name_scope(name, values=[x, shift]): <NEW_LINE> <INDENT> x = ops.convert_to_tensor(x, name="x") <NEW_LINE> shift = ops.convert_to_tensor(shift, name="shift") <NEW_LINE> check_ops.assert_integer(shift) <NEW_LINE> shift_value_static = t...
Circularly moves dims left or right. Effectively identical to: ```python numpy.transpose(x, numpy.roll(numpy.arange(len(x.shape)), shift)) ``` When `validate_args=False` additional graph-runtime checks are performed. These checks entail moving data from to GPU to CPU. Example: ```python x = tf.random.normal([1, 2,...
625941e98a43f66fc4b5451a
def transform(self, data, from_space, to_space): <NEW_LINE> <INDENT> if len(data.shape) == 1: <NEW_LINE> <INDENT> data = data[None, :] <NEW_LINE> <DEDENT> if from_space == 'D' and to_space == 'X': <NEW_LINE> <INDENT> return transform_D_to_X(data, self.pca) <NEW_LINE> <DEDENT> elif from_space == 'X' and to_space == 'U':...
Potential_spaces: 'D' <---> 'X' <---> 'U' <---> 'U_model'. DESCRIPTION There are 6 basic transformations to move back and forth between the data space, 'D', and the model's space, 'U_model': 1. From D to X. (i.e. from data space to preprocessed space) Uses the minimum number of components from Princ...
625941e9ff9c53063f47c6ab
def depthFirstSearch(problem): <NEW_LINE> <INDENT> start = problem.getStartState() <NEW_LINE> past = set() <NEW_LINE> fringe = util.Stack() <NEW_LINE> fringe.push((start, [], 0)) <NEW_LINE> while not fringe.isEmpty(): <NEW_LINE> <INDENT> location, path, cost = fringe.pop() <NEW_LINE> if problem.isGoalState(location): <...
Search the deepest nodes in the search tree first [2nd Edition: p 75, 3rd Edition: p 87] Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [2nd Edition: Fig. 3.18, 3rd Edition: Fig 3.7]. To get started, you might want to try some of these s...
625941e999fddb7c1c9de848
@export_as_api <NEW_LINE> @ExecutionContext.enforce_phase(EXECUTION_PHASE.ON_BAR, EXECUTION_PHASE.SCHEDULED) <NEW_LINE> @apply_rules(verify_that('id_or_ins').is_valid_stock(), verify_that('amount').is_number(), verify_that('style').is_instance_of((MarketOrder, LimitOrder))) <NEW_LINE> def order_lots(id_or_ins, amount, ...
指定手数发送买/卖单。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param int amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `Or...
625941e97cff6e4e81117e3f
def set_date_order_and_create(self, old_start_order, old_end_order, new_start_order, new_end_order, expected_status): <NEW_LINE> <INDENT> InterventionReportingPeriod.objects.all().delete() <NEW_LINE> day_0 = datetime.date.today() <NEW_LINE> days = [ day_0, day_0 + 1 * self.one_day, day_0 + 2 * self.one_day, day_0 + 3 *...
Helper method to test combinations of start & end date, making sure that the view returns the ``expected_status``.
625941e93eb6a72ae02ec9a4
def test7_valuedate_success(self): <NEW_LINE> <INDENT> vd = self.proinfo_p.value_date().text <NEW_LINE> vt = self.st + timedelta(days=1) <NEW_LINE> self.assertIn(vd, vt)
起息日
625941e9cc40096d61595e08
def conv_net(x, keep_prob): <NEW_LINE> <INDENT> conv_ksize = (4, 4) <NEW_LINE> conv_strides = (1, 1) <NEW_LINE> pool_ksize = (2, 2) <NEW_LINE> pool_strides = (2, 2) <NEW_LINE> num_outputs = 10 <NEW_LINE> x_tensor = conv2d_maxpool(x, 16, conv_ksize, conv_strides, pool_ksize, pool_strides) <NEW_LINE> x_tensor = conv2d_ma...
Create a convolutional neural network model : x: Placeholder tensor that holds image data. : keep_prob: Placeholder tensor that hold dropout keep probability. : return: Tensor that represents logits
625941e9187af65679ca55da
def load_json_from_endpoint(endpoint): <NEW_LINE> <INDENT> print("Loading file:", BASE_PATH + endpoint + ".json") <NEW_LINE> with open(BASE_PATH + endpoint + ".json") as file: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return json.load(file), True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return {}, False
Loads a json config from the given endpoint BASE_PATH + endpoint -> file_path :param endpoint: String referring to the file_name :return: (to return json, successful)
625941e97d847024c06be77a
def test_empty_files(self): <NEW_LINE> <INDENT> self.loader("""""").load_bundles() <NEW_LINE> assert_raises(LoaderError, self.loader("""""").load_environment)
YAML loader can deal with empty files.
625941e929b78933be1e5b60
def test_outdated_flag(script, data): <NEW_LINE> <INDENT> script.pip( 'install', '-f', data.find_links, '--no-index', 'simple==1.0', 'simple2==3.0', ) <NEW_LINE> script.pip( 'install', '-e', 'git+https://github.com/pypa/pip-test-package.git#egg=pip-test-package' ) <NEW_LINE> result = script.pip( 'list', '-f', data.find...
Test the behavior of --outdated flag in the list command
625941e9566aa707497f4a1c
def _populate_contact_labels(account_id, transactions, contacts): <NEW_LINE> <INDENT> app.logger.debug('Populating contact labels.') <NEW_LINE> if account_id is None or transactions is None or contacts is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> contact_map = {c['account_num']: c.get('label') for c in conta...
Populate contact labels for the passed transactions. Side effect: Take each transaction and set the 'accountLabel' field with the label of the contact each transaction was associated with. If there was no associated contact, set 'accountLabel' to None. If any parameter is None, nothing happens. Params...
625941e9435de62698dfe107
def get_config(): <NEW_LINE> <INDENT> cfg = VersioneerConfig() <NEW_LINE> cfg.VCS = "git" <NEW_LINE> cfg.style = "pep440" <NEW_LINE> cfg.tag_prefix = "" <NEW_LINE> cfg.parentdir_prefix = "None" <NEW_LINE> cfg.versionfile_source = "src/metadata/_version.py" <NEW_LINE> cfg.verbose = False <NEW_LINE> return cfg
Create, populate and return the VersioneerConfig() object.
625941e9d18da76e23532996
def findAveragePosition(self, *boids): <NEW_LINE> <INDENT> if not boids: <NEW_LINE> <INDENT> return (0, 0) <NEW_LINE> <DEDENT> num_n = float(len(boids)) or 1 <NEW_LINE> avg_x = sum((getX(n) for n in boids))/num_n <NEW_LINE> avg_y = sum((getY(n) for n in boids))/num_n <NEW_LINE> return avg_x, avg_y
Return the average position of the given boids. @rtype: C{tuple} of C{(x, y)}.
625941e982261d6c526ab961
def extract(self, output_file): <NEW_LINE> <INDENT> br = BitReader(self.file) <NEW_LINE> root = self._read_trie(br) <NEW_LINE> length = int(br.readbits(8)) <NEW_LINE> bw = BitWriter(output_file) <NEW_LINE> for i in xrange(length): <NEW_LINE> <INDENT> node = root <NEW_LINE> while not node.is_leaf: <NEW_LINE> <INDENT> bi...
Restore the compressed data
625941e9d4950a0f3b08c802
def test_item_bad_tag(self): <NEW_LINE> <INDENT> bytestream = b'\xFE\xFF\x00\xE0' b'\x04\x00\x00\x00' b'\x01\x00\x00\x00' b'\x10\x00\x10\x00' b'\x04\x00\x00\x00' b'\xFF\x00\xFF\x00' b'\xFE\xFF\x00\xE0...
Test item is read if it has an unexpected tag
625941e916aa5153ce362932
def sgvb(log_joint, observed, latent, axis=None): <NEW_LINE> <INDENT> warnings.warn("sgvb(): This function will be deprecated in the coming " "version (0.3.1). Variational utilities are moving to " "`zs.variational`. The new sgvb gradient estimator can be " "accessed by first constructing the elbo objective (using " "`...
Implements the stochastic gradient variational bayes (SGVB) algorithm from (Kingma, 2013). This only works for continuous latent `StochasticTensor` s that can be reparameterized (Kingma, 2013). :param log_joint: A function that accepts a dictionary argument of ``(string, Tensor)`` pairs, which are mappings from al...
625941e95fdd1c0f98dc06ef
def __ring_write(self, bytedata: bytes) -> None: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> amount = len(bytedata) <NEW_LINE> if amount == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if amount > (self.ringlength - self.write_pos): <NEW_LINE> <INDENT> amount = self.ringlength - self.write_pos <NEW_LINE> <...
Write bytes into the backref ring. Parameters: byte - A byte to be written at the current write offset
625941e901c39578d7e752f6
def assert_contain_text(self, localtion, element): <NEW_LINE> <INDENT> element_details = self.d(localtion).info <NEW_LINE> assert element == element_details["text"], "断言「{}」位置没有「{}」元素失败!".format(localtion, element) <NEW_LINE> logger.info("断言「{}」位置存在「{}」元素成功!".format(localtion, element))
断言页面的某个位置是否含有该文字 :param localtion: 直接是x,y 坐标 :param element: :return:
625941e91f5feb6acb0c5004
def displace(alpha, n=default_n): <NEW_LINE> <INDENT> if not isscalar(alpha): <NEW_LINE> <INDENT> raise TypeError('alpha must be a scalar.') <NEW_LINE> <DEDENT> a = mat(boson_ladder(n)) <NEW_LINE> return array(expm(alpha * a.H -alpha.conjugate() * a))
Bosonic displacement operator. Returns the n-dimensional approximation for the bosonic displacement operator .. math:: D(\alpha) := \exp\left(\alpha a^\dagger - \alpha^* a\right) = \exp\left( i \sqrt{2} \left(Q \mathrm{Im}(\alpha) -P \mathrm{Re}(\alpha)\right)\right) in the number basis. This yields .. math:...
625941e910dbd63aa1bd305c
def deleteService(self, **kwargs): <NEW_LINE> <INDENT> allParams = ['name', 'namespaces'] <NEW_LINE> params = locals() <NEW_LINE> for (key, val) in params['kwargs'].iteritems(): <NEW_LINE> <INDENT> if key not in allParams: <NEW_LINE> <INDENT> raise TypeError("Got an unexpected keyword argument '%s' to method deleteServ...
delete a Service Args: name, str: name of the Service (required) namespaces, str: object name and auth scope, such as for teams and projects (required) Returns:
625941e9f7d966606f6aa4c4
def zlib_hash(filepath, method, blocksize=16 * 1024 * 1024): <NEW_LINE> <INDENT> hashfunc, seed = zlib_handler(method) <NEW_LINE> with open(filepath, 'rb') as file: <NEW_LINE> <INDENT> for chunk in iter(lambda: file.read(blocksize), b''): <NEW_LINE> <INDENT> seed = hashfunc(chunk, seed) <NEW_LINE> <DEDENT> <DEDENT> fin...
Return zlib-based (i.e. CRC32/Adler32) checksum of a file. :param filepath: File you wish to verify. :type filepath: str :param method: "crc32" or "adler32". :type method: str :param blocksize: How much of file to read at once. Default is 16MB. :type blocksize: int
625941e9236d856c2ad44c9b
def process_blank_line(self): <NEW_LINE> <INDENT> self.is_markup_line = False <NEW_LINE> self.token = None
Update state on a blank line.
625941e94c3428357757c7df
def make_new_with_same_coordinates(self, data=None, var_name=None, standard_name=None, long_name=None, history=None, units=None, flatten=False): <NEW_LINE> <INDENT> if data is None: <NEW_LINE> <INDENT> data = np.zeros(self.shape) <NEW_LINE> <DEDENT> data = GriddedData(data=data, standard_name=standard_name, long_name=l...
Create a new, empty GriddedData object with the same coordinates as this one :param data: Data to use (if None then defaults to all zeros) :param var_name: Variable name :param standard_name: Variable CF standard name :param long_name: Variable long name :param history: Data history string :param units: Variable units ...
625941e960cbc95b062c69fe
def clip(self, B): <NEW_LINE> <INDENT> if ((self.x >= B.x) and (self.x < (B.x + B.w))): <NEW_LINE> <INDENT> x = self.x <NEW_LINE> <DEDENT> elif ((B.x >= self.x) and (B.x < (self.x + self.w))): <NEW_LINE> <INDENT> x = B.x <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Rect(self.x, self.y, 0, 0) <NEW_LINE> <DEDENT>...
Returns a new rectangle that is cropped to be completely inside the argument Rect. If the two rectangles do not overlap to begin with, a Rect with 0 size is returned.
625941e9097d151d1a223311
def test_remote_evb_mode(self): <NEW_LINE> <INDENT> ret = self.pub_lldp.get_remote_evb_mode(self.lldp_tlv_correct_out) <NEW_LINE> self.assertEqual('bridge', ret)
Test the get_remote_evb_mode function.
625941e923849d37ff7b3545
def _balance_tree(self, start_node, bal): <NEW_LINE> <INDENT> if bal > 0: <NEW_LINE> <INDENT> sub_bal = self.find_balance(start_node.left) <NEW_LINE> if sub_bal < 0: <NEW_LINE> <INDENT> self._rotate_left(start_node.left) <NEW_LINE> <DEDENT> self._rotate_right(start_node) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> su...
Balance subtree of start node.
625941e95f7d997b87174f56
def set(self, user_name, value): <NEW_LINE> <INDENT> return self.db.hset(self.name(), user_name, value)
设置新对 :param user_name: :param value: :return:
625941e999fddb7c1c9de849
def GenerateContigLengths(genomes): <NEW_LINE> <INDENT> lengths = [] <NEW_LINE> for genome in glob("{0}/*.fna".format(genomes)): <NEW_LINE> <INDENT> tag = genome.split("/")[2].split(".")[0] <NEW_LINE> gen = [] <NEW_LINE> for seq in SeqIO.parse(genome, "fasta"): <NEW_LINE> <INDENT> gen.append([seq.id, "1", str(len(seq.s...
Parse sequences in original genomes (contigs, chromosomes, &c.) and write their lengths to file.
625941e9be7bc26dc91cdab1
def get_argument( self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: <NEW_LINE> <INDENT> return self._get_argument(name, default, self.request.arguments, strip)
Returns the value of the argument with the given name. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the request more than once, we return the last value. This method searches both the query and body arguments...
625941e93346ee7daa2b322a
def fit(self, X, y): <NEW_LINE> <INDENT> if self.kernel is None: <NEW_LINE> <INDENT> self.kernel_ = C(1.0, constant_value_bounds="fixed") * RBF(1.0, length_scale_bounds="fixed") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.kernel_ = clone(self.kernel) <NEW_LINE> <DEDENT> self.rng = check...
Fit Gaussian process regression model Parameters ---------- X : array-like, shape = (n_samples, n_features) Training data y : array-like, shape = (n_samples, [n_output_dims]) Target values Returns ------- self : returns an instance of self.
625941e95fcc89381b1e1b7d
def _rawget(self, path: str, params: dict = None, retries: int = 3) -> requests.Response: <NEW_LINE> <INDENT> return self._retry_response(self.get, path, params=params, retries=retries, expect_json=False)
Perform a get call to the server, in which we do NOT expect a json response from the server.
625941e98da39b475bd65434
def update_scene_file_path(self): <NEW_LINE> <INDENT> filename, _ = os.path.splitext(self.original_scene_file) <NEW_LINE> filename += '_' + str(self.camera_name) <NEW_LINE> filename = self._scene_path_generator(filename) + '.' <NEW_LINE> self._standalone_scene_file_prefix = filename
Updates the scene and stand-alone scene file paths. The update is necessary to refresh scene file names, because they depend on other fields of the model.
625941e95fdd1c0f98dc06f0
def _resultsEqual(self, df, rc): <NEW_LINE> <INDENT> for d in [ Experiment.PARAMETERS, Experiment.RESULTS ]: <NEW_LINE> <INDENT> for k in rc[d].keys(): <NEW_LINE> <INDENT> df = df[df[k] == rc[d][k]] <NEW_LINE> <DEDENT> <DEDENT> return (len(df) > 0)
Check that the dataframe contains a row with the given results. :param df: the dataframe :param rc: the results dict :returns: True if there's a corresponding row
625941e9a4f1c619b28b04e8
def before_get_object(self, view_kwargs): <NEW_LINE> <INDENT> if view_kwargs.get('event_invoice_identifier'): <NEW_LINE> <INDENT> event_invoice = safe_query_kwargs( EventInvoice, view_kwargs, 'event_invoice_identifier', 'identifier' ) <NEW_LINE> view_kwargs['id'] = event_invoice.id
before get method to get the resource id for fetching details :param view_kwargs: :return:
625941e91f037a2d8b9466b7
def itkInPlaceImageFilterID3IVF33_cast(*args): <NEW_LINE> <INDENT> return _itkInPlaceImageFilterBPython.itkInPlaceImageFilterID3IVF33_cast(*args)
itkInPlaceImageFilterID3IVF33_cast(itkLightObject obj) -> itkInPlaceImageFilterID3IVF33
625941e9ec188e330fd5ac50
def leave(server_name, channel, reason=None): <NEW_LINE> <INDENT> pass
Leave a channel on a server.
625941e9d53ae8145f87a721
def call(self, coordinates, optimum_path): <NEW_LINE> <INDENT> self.distances_matrix = self.calculate_distances(coordinates) <NEW_LINE> self.on_launch(coordinates, optimum_path) <NEW_LINE> population = self.init_population() <NEW_LINE> i = 0 <NEW_LINE> fitnesses = [] <NEW_LINE> while not self.termination(i, fitnesses):...
Performs the actual algorithm taking into account the configuration provided in the initialization and the distances matrix provided here Arguments: distances_matrix {Matrix NxN} -- Matrix containing the distances between cities
625941e94d74a7450ccd4680
def test_good_form_creation(self): <NEW_LINE> <INDENT> user_data = {'username': 'testuser', 'password': 'test123', 'email': 'test@test.com'} <NEW_LINE> user_form = forms.UserForm(data=user_data) <NEW_LINE> user_profile_data = {'website': 'http://www.bing.com', 'picture': tempfile.NamedTemporaryFile(suffix=".jpg").name}...
Tests the functionality of the forms. Creates a UserProfileForm and UserForm, and attempts to save them. Upon completion, we should be able to login with the details supplied.
625941e991af0d3eaac9bed8
def test_capture_exc_info(self): <NEW_LINE> <INDENT> self.handler.capture_exc_info = True <NEW_LINE> try: <NEW_LINE> <INDENT> raise ValueError('I gotta have more cowbell, baby!') <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> self.handler.handle_exception('An exception occurred!', e) <NEW_LINE> self.as...
The handler is configured to capture :py:func:`sys.exc_info` in the event of an exception. This is generally turned off because the filter already captures a formatted traceback in the event of an exception, so there is no need to store the raw traceback object. However, there are a few cases where it is useful to co...
625941e9d164cc617578320a
def __init__(self, path=None): <NEW_LINE> <INDENT> self._settings, self._index, self._templates = self._load(path) <NEW_LINE> self._path = path
Permit to load all settings :param path: the base path where settings is stored :type path: basestring
625941e9a8370b7717052d58
def _populate_pixel(self, pixel): <NEW_LINE> <INDENT> rgb = self.rgb() <NEW_LINE> lib.sanpera_pixel_from_doubles(pixel, rgb._array)
Copy values to a PixelPacket.
625941e96fb2d068a760f560
def test_jmat_32(): <NEW_LINE> <INDENT> spin32 = jmat(3 / 2.) <NEW_LINE> paulix32 = np.array( [[0.0000000 + 0.j, 0.8660254 + 0.j, 0.0000000 + 0.j, 0.0000000 + 0.j], [0.8660254 + 0.j, 0.0000000 + 0.j, 1.0000000 + 0.j, 0.0000000 + 0.j], [0.0000000 + 0.j, 1.0000000 + 0.j, 0.0000000 + 0.j, 0.8660254 + 0.j], [0.0000000 + 0....
Spin 3/2 operators
625941e9a219f33f34628e1d
def ssh(username, password, host, port=22, args = []): <NEW_LINE> <INDENT> print>>sys.stderr, "Connecting to %s@%s" % (username, host) <NEW_LINE> cmd = "/usr/bin/ssh -p%d %s@%s %s" % (port, username, host, ' '.join(args)) <NEW_LINE> child = pexpect.spawn(cmd) <NEW_LINE> (rows, cols) = gettermsize() <NEW_LINE> child.se...
Automate sending password when the server has public key auth disabled
625941e963b5f9789fde75a1
def launch_cmd(command): <NEW_LINE> <INDENT> exec('import anki_vector') <NEW_LINE> exec('robot = anki_vector.Robot()') <NEW_LINE> exec('robot.connect()') <NEW_LINE> exec(command.replace(" ", "")) <NEW_LINE> exec('robot.disconnect()')
Launch command not yet implemented :param command: Any valid command
625941e9a219f33f34628e1e
def get_STC(signal,train,window): <NEW_LINE> <INDENT> if True: <NEW_LINE> <INDENT> raise Exception('TODO: this function was never finished, and I am coding up the math, so it needs to be very well tested') <NEW_LINE> <DEDENT> X = np.empty([len(train),int(window.magnitude)*2,signal.shape[-1]]) <NEW_LINE> for ii,spike in...
Compute the Spike Triggered Covariance for a set of signals. TODO: this function was never finished, and I am coding up the math, so it needs to be very well tested :param signal: :param train: :param window: :return:
625941e98e05c05ec3eea833
def occi_list_actions(self): <NEW_LINE> <INDENT> return self._occi_actions_available.values()
Return a list of Category instances which define the Actions _available_ to this resource instance.
625941e9d486a94d0b98e602
def svm_loss_naive(W, X, y, reg): <NEW_LINE> <INDENT> dW = np.zeros(W.shape) <NEW_LINE> num_classes = W.shape[1] <NEW_LINE> num_train = X.shape[0] <NEW_LINE> loss = 0.0 <NEW_LINE> for i in xrange(num_train): <NEW_LINE> <INDENT> scores = X[i].dot(W) <NEW_LINE> correct_class_score = scores[y[i]] <NEW_LINE> for j in xrang...
Structured SVM loss function, naive implementation (with loops). Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X: A numpy array of shape (N, D) containing a minibatch of data. - y: A numpy array of shape (N,)...
625941e9f548e778e58cda3b
def test_006_Platform_Administrator_delete_ap(self): <NEW_LINE> <INDENT> log.debug("006") <NEW_LINE> tmp = APSBusiness(self.s) <NEW_LINE> tmp.webLogin(data_basic['Cloud_test_user'], data_basic['Cloud_test_pwd']) <NEW_LINE> tmp.delete_ap(data_ap['7610_mac']) <NEW_LINE> time.sleep(360) <NEW_LINE> result = tmp.check_ap_fa...
平台管理员-删除ap
625941e91f037a2d8b9466b8
def validateStackSequences(self, pushed, popped): <NEW_LINE> <INDENT> stk = [] <NEW_LINE> seen = {} <NEW_LINE> pushed_ind = 0 <NEW_LINE> for num in popped: <NEW_LINE> <INDENT> while num not in seen: <NEW_LINE> <INDENT> cur_push = pushed[pushed_ind] <NEW_LINE> stk.append((cur_push)) <NEW_LINE> seen[cur_push] = True <NEW...
:type pushed: List[int] :type popped: List[int] :rtype: bool
625941e9a79ad161976cc600
def relu_activation(x): <NEW_LINE> <INDENT> return x if x > 0.0 else 0.0
Returns x if positive, 0 otherwise.
625941e92eb69b55b151cd71
def __init__(self, radius=1.0): <NEW_LINE> <INDENT> self.rot_quat = [0,0,0,1] <NEW_LINE> self.last_x = None <NEW_LINE> self.last_y = None <NEW_LINE> self.cam_eye = [0.,0.,radius] <NEW_LINE> self.cam_focus = [0.,0.,0.] <NEW_LINE> self.cam_up = [0.,1.,0.] <NEW_LINE> self.RENORMCOUNT = 97 <NEW_LINE> self.count = 0 <N...
initialize the camera, giving a radius from the focal point for the camera eye. Update focal point & up via the update_modelview call.
625941e9e1aae11d1e74a177
@type_limit(set, set) <NEW_LINE> def intersection(source_set, other_set): <NEW_LINE> <INDENT> return source_set.intersection(other_set)
取交集,赋给新值
625941e90fa83653e4657473
def upwind_axis_finite(dt, spatial_change, V, q, axis=0): <NEW_LINE> <INDENT> dx = spatial_change[axis] <NEW_LINE> zeroes = np.zeros(q.shape) * V.units <NEW_LINE> q_p_1 = unit_roll(q, -1, axis) <NEW_LINE> q_m_1 = unit_roll(q, 1, axis) <NEW_LINE> a_plus = unit_maximum(V[axis], zeroes) <NEW_LINE> a_minus = unit_minimum(V...
upwind along a single axis https://en.wikipedia.org/wiki/Upwind_scheme
625941e9ff9c53063f47c6ac
def PIL2Tensor(img): <NEW_LINE> <INDENT> return _add_batch_one(to_tensor(img))
Converts a PIL Image or numpy.ndarray (H, W, C) in the range [0, 255] to a torch.FloatTensor of shape (1, C, H, W) in the range [0.0, 1.0]. :param img: PIL.Image or numpy.ndarray (H, W, C) in the range [0, 255] :return: 4D tensor with size [1, C, H, W] in range [0, 1.]
625941e915baa723493c4434
def get_subcellular_locations(self, entry): <NEW_LINE> <INDENT> subcellular_locations = [] <NEW_LINE> query = './n:comment/n:subcellularLocation/location' <NEW_LINE> sls = {x.text for x in entry.iterfind(query, namespaces=XN)} <NEW_LINE> for sl in sls: <NEW_LINE> <INDENT> if sl not in self.subcellular_locations: <NEW_L...
get list of models.SubcellularLocation object from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.SubcellularLocation` object
625941e9cdde0d52a9e534f2
def _get_classification(self, parsed_elements): <NEW_LINE> <INDENT> for key in parsed_elements.keys(): <NEW_LINE> <INDENT> if key == "Gender": <NEW_LINE> <INDENT> return CLASSIFICATION_PERSON <NEW_LINE> <DEDENT> <DEDENT> return None
Determine if this page should be parsed or skipped. Based on the infobox DOM element.
625941e950812a4eaa59c7d8
def select_and_apply_random_policy_augmix(policies, image, bboxes, mixture_width=3, mixture_depth=-1, alpha=1): <NEW_LINE> <INDENT> policy_to_select = tf.random_uniform([], maxval=len(policies), dtype=tf.int32) <NEW_LINE> import tensorflow_probability as tfp <NEW_LINE> ws = tfp.distributions.Dirichlet([alpha] * mixture...
Select a random policy from `policies` and apply it to `image`.
625941e9ad47b63b2c50a43a
def __init__(self, temboo_session): <NEW_LINE> <INDENT> Choreography.__init__(self, temboo_session, '/Library/Disqus/Users/ListForums')
Create a new instance of the ListForums Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied.
625941e996565a6dacc8fb85
def get_part_names(self): <NEW_LINE> <INDENT> parts = [part for part in self._wordmap] <NEW_LINE> parts.sort() <NEW_LINE> return parts
Return a sorted list of part-of-speech names.
625941e9aad79263cf390f03
def parallel(*processes): <NEW_LINE> <INDENT> for p in processes: <NEW_LINE> <INDENT> spawn(p) <NEW_LINE> <DEDENT> for p in processes: <NEW_LINE> <INDENT> sync(p)
Execute the processes in parallel.
625941e9e8904600ed9f23f0
def write_links( file_name, board_name, file_ext, file_urls ): <NEW_LINE> <INDENT> links_being_written = "webm" if file_ext == FILE_EXTS else "non-webm" <NEW_LINE> print("Writing "+links_being_written+" links to "+file_name+"...") <NEW_LINE> f_u = { board_name:"" } <NEW_LINE> if file_ext == FILE_EXTS: <NEW_LINE> <INDEN...
Writes files of extension type file_ext to a file named file_name. @param file_name the name of file to save file url to. @param board_name the name of the current board where the files are located. @param file_ext the file extension for the files of interest. "" for non-webms. @param file_urls a dictionary of file ext...
625941e94e696a04525c9909
def echo(event, vk_api): <NEW_LINE> <INDENT> url = 'https://api.dialogflow.com/v1/query' <NEW_LINE> token = os.getenv('dialog_flow_client_token') <NEW_LINE> headers = { 'Authorization': f'Bearer {token}', } <NEW_LINE> params = { 'v': 20150910, 'sessionId': event.user_id, 'query': event.text, 'lang': 'ru', } <NEW_LINE> ...
Send a message as DialogFlow reply
625941ea7b25080760e39911
def load_data(): <NEW_LINE> <INDENT> f = gzip.open('mnist.pkl.gz', 'rb') <NEW_LINE> tr_d, va_d, te_d = pickle.load(f, encoding="latin1") <NEW_LINE> f.close() <NEW_LINE> training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]] <NEW_LINE> training_results = [vectorized_result(y) for y in tr_d[1]] <NEW_LINE> training_...
:returns: training_data: a list containing 50,000 2-tuples (x, y). x is a 784-dimensional numpy.ndarray containing the input image (since the size of each image is 28*28d). y is a 10-dimensional numpy.ndarray representing the unit vector corresponding to the correct digit for x. validation_data...
625941eaeab8aa0e5d26e015
def terminate(self, message: str = '') -> None: <NEW_LINE> <INDENT> if not message: <NEW_LINE> <INDENT> message = 'Fatal error' <NEW_LINE> <DEDENT> if not self.silent: <NEW_LINE> <INDENT> print("\n???\n??? '" + self.program + "', terminated due to: '" + message + "'\n???") <NEW_LINE> <DEDENT> if self.has_gui: <NEW_LINE...
- Destructs tree of followers - Sends message to logger - Sends message to TKinter widget if self.has_gui, otherwise to console - Terminates program Args: message: Warning to be written to log file and console
625941ea5e10d32532c5f3e0
def stopInstance(self, label): <NEW_LINE> <INDENT> stop = dictwrapper(self.SHUTDOWN_INFO) <NEW_LINE> if 'debug' not in self.stopProtoKwargs: <NEW_LINE> <INDENT> self.stopProtoKwargs['debug'] = False <NEW_LINE> <DEDENT> if 'timeout' not in self.stopProtoKwargs: <NEW_LINE> <INDENT> self.stopProtoKwargs['timeout'] = self....
Stops an Application Instances based on our models rules @param label: (string) - app instance label @return defer.Deferred - be prepared for Failures()
625941ea9f2886367277ad45
def test_zpl_template_not_set(self): <NEW_LINE> <INDENT> label = ModelLabel() <NEW_LINE> test_model = TestModelFactory() <NEW_LINE> request = None <NEW_LINE> self.assertRaises(TypeError, label.print_label, request, test_model, update_messages=False, client_addr='127.0.0.1')
Assert fails if template not set.
625941ea377c676e91272662
def test_add_available_with_package(self): <NEW_LINE> <INDENT> paster(" ".join(self.options)) <NEW_LINE> os.chdir(os.path.sep.join(['plone.example', 'src'])) <NEW_LINE> cmd_pattern = r"^\s*add" <NEW_LINE> help_text = read_sh(self.cmd + ' help') <NEW_LINE> matches = re.search(cmd_pattern, help_text, re.I|re.M) <NEW_LINE...
verify that within a supporting package, add is available
625941ea26238365f5f0f331
def load_file(self, filename, target=None): <NEW_LINE> <INDENT> formulas = compile.parse_file( filename, theories=self.theory) <NEW_LINE> try: <NEW_LINE> <INDENT> self.policy_object(target) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self.create_policy(target) <NEW_LINE> <DEDENT> return self.update( [Event...
Load content from file. Compile the given FILENAME and insert each of the statements into the runtime. Assumes that FILENAME includes no modals.
625941eae76e3b2f99f3acc0
def render(self, template_name="view", values=None, options=None): <NEW_LINE> <INDENT> values = {'title': self.title} <NEW_LINE> if self.args is not None and self.args['content'] is not None: <NEW_LINE> <INDENT> values['content'] = self.args['content'] <NEW_LINE> <DEDENT> return super().render("home_view", values, opti...
Rendering our title view template
625941eae76e3b2f99f3acbf
def wordPatternMatch(self, pattern, str): <NEW_LINE> <INDENT> hmap = dict() <NEW_LINE> usedString = set() <NEW_LINE> def dfs(pattern, string, usedString): <NEW_LINE> <INDENT> if not pattern: <NEW_LINE> <INDENT> return not string <NEW_LINE> <DEDENT> currPattern = pattern[0] <NEW_LINE> if currPattern in hmap: <NEW_LINE> ...
:type pattern: str :type str: str :rtype: bool
625941ea5166f23b2e1a5615
def is_datapath_ready(self): <NEW_LINE> <INDENT> return self["dpenter"] and (self["vs"].port != 0 or self["no_vs"])
Check if vs,dp port associated.
625941eab7558d58953c53c6
def test_update_user_profile(self): <NEW_LINE> <INDENT> payload = {'name': 'New Name', 'password': 'newpass'} <NEW_LINE> res = self.client.patch(ME_URL, payload) <NEW_LINE> self.user.refresh_from_db() <NEW_LINE> self.assertEqual(self.user.name, payload['name']) <NEW_LINE> self.assertTrue(self.user.check_password(payloa...
test update user profile for authenticated user
625941ea442bda511e8be8cd
def fill_database(self, kind, lines=None): <NEW_LINE> <INDENT> method = getattr(self, kind) <NEW_LINE> if os.path.isfile(self.path): <NEW_LINE> <INDENT> if kind == 'full_table': <NEW_LINE> <INDENT> method(self.path, lines=lines) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> method(self.path) <NEW_LINE> <DEDENT> <DEDENT...
Filling table by type kind kind : <string> :: ['full_table', 'total_logs_table', 'types_logs_table', 'top_10_by_size_table', 'top_10_client_error_by_number_with_ip_table', 'top_10_client_error_by_size_with_ip_table']
625941ea4e4d5625662d488d
def get_gateway_info(self): <NEW_LINE> <INDENT> def process_result(result): <NEW_LINE> <INDENT> return GatewayInfo(result) <NEW_LINE> <DEDENT> return Command('get', PATH_GATEWAY_INFO, process_result=process_result)
Return the gateway info. Returns a Command.
625941ea287bf620b61d3f1c
def max_dmg(self): <NEW_LINE> <INDENT> return sum(self.dies)
Returns the highest possible damage this can deal.
625941eaadb09d7d5db6cc48
def set_harddisk_sleep(minutes): <NEW_LINE> <INDENT> value = _validate_sleep(minutes) <NEW_LINE> cmd = 'systemsetup -setharddisksleep {0}'.format(value) <NEW_LINE> salt.utils.mac_utils.execute_return_success(cmd) <NEW_LINE> return str(value) in get_harddisk_sleep()
Set the amount of idle time until the harddisk sleeps. Pass "Never" of "Off" to never sleep. :param minutes: Can be an integer between 1 and 180 or "Never" or "Off" :ptype: int, str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' power.set_harddisk_sleep 120 ...
625941ea379a373c97cfb003
def configure_extensions(app): <NEW_LINE> <INDENT> plugin_manager.init_app(app) <NEW_LINE> db.init_app(app) <NEW_LINE> migrate.init_app(app, db) <NEW_LINE> mail.init_app(app) <NEW_LINE> cache.init_app(app) <NEW_LINE> themes.init_themes(app, app_identifier="flaskbb") <NEW_LINE> redis_store.init_app(app) <NEW_LINE> login...
Configures the extensions
625941ea8a43f66fc4b5451c
def create_default_service_role(): <NEW_LINE> <INDENT> io.log_info('Creating service role {} with default permissions.' .format(DEFAULT_SERVICE_ROLE_NAME)) <NEW_LINE> trust_document = _get_default_service_trust_document() <NEW_LINE> json_policy = _get_default_service_role_policy() <NEW_LINE> role_name = DEFAULT_SERVICE...
Create the default service role
625941ea15baa723493c4435
def testSharePictureInGridViewWithBluetooth(self): <NEW_LINE> <INDENT> u.holdTheCenter() <NEW_LINE> u.shareItem('Bluetooth') <NEW_LINE> assert d(text = 'Choose Bluetooth device').wait.exists(timeout = 2000)
1.Launch gallery activity 2.Enter Grid view 3.Long touch a pic or a video to select 4.Tap share icon 5.Tap Bluetooth option
625941ea2eb69b55b151cd72
def test_getMergeProposals_correct_merged_revno(self): <NEW_LINE> <INDENT> bmp1 = make_proposal_and_branch_revision(self.factory, 4, 'rev-id') <NEW_LINE> bmp2 = make_proposal_and_branch_revision(self.factory, 5, 'other') <NEW_LINE> result = self.branch_set.getMergeProposals(merged_revision='rev-id') <NEW_LINE> self.ass...
Only proposals with the correct merged_revno match.
625941ead53ae8145f87a722
def __slice_subtree(self, tree): <NEW_LINE> <INDENT> ret = {} <NEW_LINE> ws = stack() <NEW_LINE> ws.push(self.root) <NEW_LINE> while not ws.isEmpty(): <NEW_LINE> <INDENT> cur = ws.pop() <NEW_LINE> ret[cur] = list(tree[cur]) <NEW_LINE> ws.extend(tree[cur]) <NEW_LINE> <DEDENT> return ret
Slices all entries of the tree dict, that are below root
625941ea1b99ca400220af6f
def __init__(self, element_type, size=None): <NEW_LINE> <INDENT> self.type = element_type <NEW_LINE> self.size = size <NEW_LINE> super().__init__( None, unary_ops={"*", "&"}, rel_ops={"==", "!="}, assign_ops = {"="}, )
type: Any of the uCTypes can be used as the array's type. This means that there's support for nested types, like matrices. size: Integer with the length of the array.
625941eafff4ab517eb2f8fb
@pytest.hookimpl(hookwrapper=True) <NEW_LINE> def pytest_fixture_setup(fixturedef, request): <NEW_LINE> <INDENT> outcome = yield <NEW_LINE> res = None <NEW_LINE> if request.config.getoption("rst_dir"): <NEW_LINE> <INDENT> if request.config.getoption("rst_fixture_results", None) or getattr( fixturedef.func, "_doc_result...
We can use this pytest hook to add in fixture doc info into each NodeDocCollector
625941ea55399d3f05588b73
def to_json(self): <NEW_LINE> <INDENT> return self.__dict__
retrieves the dict
625941ea01c39578d7e752f7
def remove_sun(self): <NEW_LINE> <INDENT> if not isinstance(self.angle_array, collections.Iterable): <NEW_LINE> <INDENT> self.create_angle_array() <NEW_LINE> <DEDENT> x_sol_cen, y_sol_cen = self.ele_azi_to_pixel(self.sun_azimuth,self.sun_elevation) <NEW_LINE> Radius_sol = 100 <NEW_LINE> Radius_sol_center = 0 <NEW_LINE>...
Calculates the center of the sun inside the image and draws a circle around it.
625941ea16aa5153ce362934
def reachable_points_from_ellipsis(center, a, b, velocity): <NEW_LINE> <INDENT> moves = set(filter(lambda p: p[0] <= 0 and p[1] <= 0, radial_moves(velocity))) <NEW_LINE> dead_points = set() <NEW_LINE> for x in range(center[0] - b, center[0] + 1): <NEW_LINE> <INDENT> for y in range(center[1] - a, center[1] + 1): <NEW_LI...
Creates a set of reachable points outside of the ellipsis from any which lies inside in one step. :param center: (x, y) ellipsis's center tuple :param a: ellipsis's vertical small radius. Must be not greater than b. :param b: ellipsis's horizontal big radius. Must be not less than a. :param velocity: distance in points...
625941eaeab8aa0e5d26e016
def get_lists_for_record(self, riid): <NEW_LINE> <INDENT> all_lists = [list_name["name"] for list_name in self.get_profile_lists()] <NEW_LINE> member_of = [] <NEW_LINE> for profile_list in all_lists: <NEW_LINE> <INDENT> response = self.get_member_of_list_by_riid( self, profile_list, riid) <NEW_LINE> if "recordData" in ...
Find what lists a record is in by RIID.
625941ea8e71fb1e9831dc63
def mapObjects(channel): <NEW_LINE> <INDENT> global _zzhelpers_object_maps_ <NEW_LINE> try: <NEW_LINE> <INDENT> return _zzhelpers_object_maps_[channel] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> nObjects = {} <NEW_LINE> objects = [] <NEW_LINE> for obj in channel: <NEW_LINE> <INDENT> if obj not in nObjects...
Return a list of objects of the form ['e1','e2','m1','m2'] or ['e1','e2','m'] Objects are in alphabetical/numerical order order
625941ea293b9510aa2c374d
def read_sequences(filename, directory="data/sequences"): <NEW_LINE> <INDENT> path = os.path.join(directory, filename) <NEW_LINE> if os.path.exists(path): <NEW_LINE> <INDENT> sequences = pd.read_csv( path, sep=";", index_col=["timeindex"], parse_dates=True ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sequences = pd....
Reads sequence resources from the datapackage Parameters ---------- filename: string Name of the sequences to be read, for example `load_profile.csv` directory: string Directory from where the file should be read. Default: `data/sequences`
625941ead268445f265b532b
def _root_element_name(self): <NEW_LINE> <INDENT> return 'root'
Return the name of the xml root element. By default returns 'root'. Override to return something else.
625941ea1f5feb6acb0c5005
def set_type(a, typeInt): <NEW_LINE> <INDENT> pass
__NATIVE__ PmReturn_t retval = PM_RET_OK; pPmObj_t po = C_NULL; pPmObj_t newType = C_NULL; /* If wrong number of args, raise TypeError */ if (NATIVE_GET_NUM_ARGS() != 2) { PM_RAISE(retval, PM_RET_EX_TYPE); return retval; } /* Get arg */ po = NATIVE_GET_LOCAL(0); newType = NATIVE_GET_LOCAL(1); /* ensure newTy...
625941ea4e696a04525c990a
def create_input(path): <NEW_LINE> <INDENT> folder = path <NEW_LINE> files = os.listdir(folder) <NEW_LINE> x = [] <NEW_LINE> y = [] <NEW_LINE> image_paths = [] <NEW_LINE> scaler = MinMaxScaler(feature_range=(-0.1, 1.175)) <NEW_LINE> for i, images in sorted(enumerate(files)): <NEW_LINE> <INDENT> label = images[0:2] <NE...
Create Lenet's input with appropiate structure given a path (e.g. './images/train' or './images/test')
625941ea26068e7796caf1a3