code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def set_extension(self, extension, real=True): <NEW_LINE> <INDENT> extension = self.extension_map(extension, extension) <NEW_LINE> if real: <NEW_LINE> <INDENT> self.extension = extension <NEW_LINE> <DEDENT> self.kwdict["extension"] = self.prefix + extension <NEW_LINE> self.build_path()
Set filename extension
625941b124f1403a926008de
def restore_instance_snapshot(self, context, instance, snapshot_id=None): <NEW_LINE> <INDENT> LOG.debug("Restore to a snapshot of instance", instance=instance) <NEW_LINE> vm_ref = vm_util.get_vm_ref(self._session, instance) <NEW_LINE> if snapshot_id is not None: <NEW_LINE> <INDENT> snapshot_ref = vm_util.get_snapshot_r...
Restore snapshot of the instance.
625941b1627d3e7fe0d68bb9
def CreateDBInstanceHour(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("CreateDBInstanceHour", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.CreateDBInstanceHou...
本接口(CreateDBInstanceHour)用于创建按量计费的MongoDB云数据库实例(包括主实例、灾备实例和只读实例),可通过传入实例规格、实例类型、MongoDB版本、购买时长和数量等信息创建云数据库实例。 :param request: 调用CreateDBInstanceHour所需参数的结构体。 :type request: :class:`tencentcloud.mongodb.v20180408.models.CreateDBInstanceHourRequest` :rtype: :class:`tencentcloud.mongodb.v20180408.models.CreateDBInstanceH...
625941b10383005118ecf355
def enroll_dl0_replica(installer, fstore, remote_api, debug=False): <NEW_LINE> <INDENT> logger.info("Enrolling host to IPA domain") <NEW_LINE> config = installer._config <NEW_LINE> hostname = config.host_name <NEW_LINE> try: <NEW_LINE> <INDENT> installer._enrollment_performed = True <NEW_LINE> host_result = remote_api....
Do partial host enrollment in DL0: * add host entry to remote master * request host keytab from remote master * configure client-like /etc/krb5.conf to enable GSSAPI auth further down the replica installation
625941b182261d6c526ab20f
def run_ES(self): <NEW_LINE> <INDENT> self.logger.info('started running (μ + λ)-ES') <NEW_LINE> self.create_initial_population(); <NEW_LINE> self.evaluate_population(self.population) <NEW_LINE> current_gen = 0 <NEW_LINE> self.successful_individuals = 0 <NEW_LINE> self.total_individuals = 0 <NEW_LINE> while current_gen ...
Run the (μ + λ)-ES using Rechenberg's 1/5th Success Rule
625941b1d486a94d0b98debc
def main(): <NEW_LINE> <INDENT> args = argument_parser().parse_args() <NEW_LINE> random.seed(args.seed) <NEW_LINE> args.checkpoint_dir = CHECKPOINT_DIR <NEW_LINE> os.environ['CUDA_VISIBLE_DEVICES'] = args.gpus <NEW_LINE> data_source = SinusoidDataSource(amp_range=[0.1, 5.0], phase_range=[0.1, np.pi], input_range=[-5.0,...
Load data and train a model on it.
625941b1be7bc26dc91cd37a
def summary(self, kind='raw'): <NEW_LINE> <INDENT> if kind=='raw': <NEW_LINE> <INDENT> return self._raw_data['summary'].copy() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError
Summary statistics
625941b16fece00bbac2d4a6
def findMedianSortedArrays(self, nums1, nums2): <NEW_LINE> <INDENT> len1, len2 = len(nums1), len(nums2) <NEW_LINE> n_elems = len1 + len2 <NEW_LINE> if n_elems & 1: <NEW_LINE> <INDENT> k_elem_ind = (n_elems // 2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> k_elem_ind = (n_elems - 1) // 2 <NEW_LINE> <DEDENT> k_val, k_v...
:type nums1: List[int] :type nums2: List[int] :rtype: float
625941b18a43f66fc4b53ddf
def get_agent(self): <NEW_LINE> <INDENT> return self.request("self", method="get").json()
Query the state of the target agent. https://www.nomadproject.io/docs/http/agent-self.html returns: dict raises: - nomad.api.exceptions.BaseNomadException - nomad.api.exceptions.URLNotFoundNomadException
625941b145492302aab5e034
def t_instring(t): <NEW_LINE> <INDENT> t.lexer.value_buffer = [] <NEW_LINE> t.lexer.string_startpos = t.lexpos <NEW_LINE> t.lexer.level = 1 <NEW_LINE> t.lexer.begin('instring')
\(
625941b1d8ef3951e32432ae
def clear_tasks(self): <NEW_LINE> <INDENT> self.logger.debug('Clearing {0} tasks'.format(len(self.tasks))) <NEW_LINE> self.tasks = {}
Empty the task dictionary.
625941b1293b9510aa2c3007
def result_metadata(self, handle): <NEW_LINE> <INDENT> req = TCLIService.TGetResultSetMetadataReq() <NEW_LINE> req.operationHandle = handle <NEW_LINE> resp = self.hs2_client.GetResultSetMetadata(req) <NEW_LINE> HS2TestSuite.check_response(resp) <NEW_LINE> return resp
Gets the schema for the query identified by the handle
625941b1925a0f43d2549be7
def propagate(self, input, save_path=False): <NEW_LINE> <INDENT> output = [] <NEW_LINE> raw_input, net_input = [], [] <NEW_LINE> for i in input: <NEW_LINE> <INDENT> into_layer = np.array([i]).T <NEW_LINE> for j in xrange(self.num_layer): <NEW_LINE> <INDENT> n = np.dot(self.weight[j], into_layer) + self.bias[j] <NEW_LIN...
Input: array of arrays.
625941b1187af65679ca4e93
def test_add_vip_card(self): <NEW_LINE> <INDENT> with open("D:\\mzmy\\add_csv\\add_vipcard.csv") as avc: <NEW_LINE> <INDENT> avc = csv.reader(avc) <NEW_LINE> for a in avc: <NEW_LINE> <INDENT> if a[0] == "会员卡编号": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.driver.get(self.url) <NEW_LI...
添加会员卡
625941b197e22403b379cd0d
def days_remaining(start_dt1, start_dt2, end_dt): <NEW_LINE> <INDENT> if start_dt1 <= start_dt2: <NEW_LINE> <INDENT> start_dt = start_dt1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> start_dt = start_dt2 <NEW_LINE> <DEDENT> days_remng = (end_dt - start_dt).total_seconds()/86400 <NEW_LINE> return days_remng
Calc time delta between end_dt and min(start_dt1, start_dt2) All three inputs are expected to be datetimes.
625941b1507cdc57c6306a3e
def parse_labels(response): <NEW_LINE> <INDENT> return {label['Name']: round(label['Confidence'], 2) for label in response['Labels']}
Parse the response and return labels data.
625941b14a966d76dd550d7f
def delete_item_list(self, itemlist_id): <NEW_LINE> <INDENT> os.remove(os.path.join(self.basedir, "%s.n3" % self.get_item_list_name(itemlist_id))) <NEW_LINE> self.graph.remove((URIRef(itemlist_id), None, None)) <NEW_LINE> self.graph.remove((None, None, URIRef(itemlist_id)))
Delete a given item list
625941b1627d3e7fe0d68bbb
def load_rprocess_yields(self): <NEW_LINE> <INDENT> self.rprocess_yields = pickle_read(join(self.path_rprocess, 'cescutti06_yields.pck'))
Load r-process element yields. Cescutti et al. (2006) r-process Ba & Eu yields for M = 12, 15, 30 Msun that are metallicity independent.
625941b18e05c05ec3eea0e5
def _rel_dist(self, tree): <NEW_LINE> <INDENT> self._avg_descendant_rate(tree) <NEW_LINE> for node in tree.preorder_node_iter(): <NEW_LINE> <INDENT> if node == tree.seed_node: <NEW_LINE> <INDENT> node.rel_dist = 0.0 <NEW_LINE> <DEDENT> elif node.is_leaf(): <NEW_LINE> <INDENT> node.rel_dist = 1.0 <NEW_LINE> <DEDENT> els...
Calculate relative distance to each internal node. Parameters ---------- tree : Dendropy Tree Phylogenetic tree. Returns ------- The following attributes are added to each node: mean_dist: mean distance to tips num_taxa: number of terminal taxa rel_dists: relative distance of node between root and extant or...
625941b13539df3088e2e0ba
def get_details(self, model_uid): <NEW_LINE> <INDENT> model_uid = str_type_conv(model_uid) <NEW_LINE> self._validate_type(model_uid, u'model_uid', STR_TYPE, True) <NEW_LINE> response = requests.get( self._href_definitions.get_published_model_href(model_uid), headers=self._client._get_headers() ) <NEW_LINE> details = se...
Get details of learning system. :param model_uid: ID of model for this learning system :type model_uid: str :returns: learning system details :rtype: dict **Example**: >>> learning_system_details = client.learning_system.get_details(model_uid)
625941b10a50d4780f666c03
def insert_doc(d, a): <NEW_LINE> <INDENT> client = py.MongoClient('mongo') <NEW_LINE> db = client['docs'] <NEW_LINE> col = db['aug_meta'] <NEW_LINE> doc, file_stream = get_tika_content(d, a) <NEW_LINE> raw_file = create_temp_file(d['latest_version']['download_url'], a) <NEW_LINE> doc['raw_file'] = import_to_gridfs(db, ...
Insert TIKA extracted metadata and content.
625941b116aa5153ce3621ee
def _getDataLayerId(self): <NEW_LINE> <INDENT> return self.qgs_layer.id()
Get name tag content from xml :return: return QGIS layerID :rtype: str
625941b1b57a9660fec335ec
def singular_points(self, F=None): <NEW_LINE> <INDENT> if F is None: <NEW_LINE> <INDENT> if not self.base_ring() in Fields(): <NEW_LINE> <INDENT> raise TypeError("curve must be defined over a field") <NEW_LINE> <DEDENT> <DEDENT> elif not F in Fields(): <NEW_LINE> <INDENT> raise TypeError("(=%s) must be a field"%F) <NEW...
Return the set of singular points of this curve. INPUT: - ``F`` -- (default: None) field over which to find the singular points. If not given, the base ring of this curve is used. OUTPUT: - a list of points in the ambient space of this curve. EXAMPLES:: sage: A.<x,y,z> = AffineSpace(QQ, 3) sage: C = Cur...
625941b16fece00bbac2d4a8
def contour(self, z=0): <NEW_LINE> <INDENT> raise NotImplementedError
Contour of surface in the xy (or any parallel) plane. Parameters ---------- z : float The z-level of the plane the contour is taken at. Returns ------- : surface. A symbolic A contour line or lines, type and format are dependent on the subclass.
625941b16aa9bd52df036b0f
def __init__( self, log_path=None, config_path=None, logger=None, printer=None ): <NEW_LINE> <INDENT> self.logger = logger or logging.getLogger(__name__) <NEW_LINE> self.printer = printer or pprint.PrettyPrinter() <NEW_LINE> self.log_path = log_path or (os.getcwd() + "/report.log") <NEW_LINE> self._bar_fmt = "{l_bar}{b...
Initialize the reporter Attributes ---------- log_path : str (default is :code:`None`) Sets the default log path (overriden when :code:`path` is given to :code:`_setup_logger()`) config_path : str (default is :code:`None`) Sets the configuration path for custom loggers logger : logging.Logger (default is :...
625941b18a349b6b435e7eea
def get_manifest_key(self): <NEW_LINE> <INDENT> return self._generate_path("manifest_relpath")
Return the path to the readme file.
625941b123849d37ff7b2e08
def lagder(c, m=1, scl=1, axis=0) : <NEW_LINE> <INDENT> c = np.array(c, ndmin=1, copy=1) <NEW_LINE> if c.dtype.char in '?bBhHiIlLqQpP': <NEW_LINE> <INDENT> c = c.astype(np.double) <NEW_LINE> <DEDENT> cnt, iaxis = [int(t) for t in [m, axis]] <NEW_LINE> if cnt != m: <NEW_LINE> <INDENT> raise ValueError("The order of deri...
Differentiate a Laguerre series. Returns the Laguerre series coefficients `c` differentiated `m` times along `axis`. At each iteration the result is multiplied by `scl` (the scaling factor is for use in a linear change of variable). The argument `c` is an array of coefficients from low to high degree along each axis,...
625941b163b5f9789fde6e5a
def original_url(self, fieldname): <NEW_LINE> <INDENT> url = self.context.absolute_url() <NEW_LINE> return '{0}/images/{1}'.format(url, fieldname)
Returns the url to the unscaled image
625941b145492302aab5e036
def DeleteAllEntities(kind): <NEW_LINE> <INDENT> if not kind: <NEW_LINE> <INDENT> raise ValueError('"kind" cannot be empty') <NEW_LINE> <DEDENT> keys, _, more = ndb.Query(kind=kind).fetch_page( QUERY_PAGE_LIMIT, keys_only=True) <NEW_LINE> logging.info('Fetched %d keys; more=%r', len(keys), more) <NEW_LINE> ndb.delete_m...
DELETES ALL ENTITIES OF KIND |kind|. Args: kind: Required string name of model.
625941b1bf627c535bc12f46
def get_associations(self, ontology=None): <NEW_LINE> <INDENT> if ontology is not None and ontology not in ("P", "F", "C"): <NEW_LINE> <INDENT> raise GeneOntologyError(f"Not a valid ontology: {ontology}") <NEW_LINE> <DEDENT> if not hasattr(self, "all_associations"): <NEW_LINE> <INDENT> self.all_associations = read_gaf(...
Get associations of gene IDs to GO terms. Ontologies: P = biological process, F = molecular function, C = cellular component # Arguments ontology: str (optional), one of {"P", "F", "C"} # Returns dict: maps gene IDs to the GO terms it is annotated them # Raises GeneOntologyError: if `ontology` is no...
625941b1293b9510aa2c3009
def calcmeplzsenpai(inputx): <NEW_LINE> <INDENT> return (145 * (inputx**4)) + (349 * (inputx**3)) - (914 * (inputx**2)) - (112 * inputx) - 444
WOW Notice me Senpai!
625941b167a9b606de4a7c33
def get_load_balancer_pool_statistics_with_http_info(self, service_id, pool_id, **kwargs): <NEW_LINE> <INDENT> all_params = ['service_id', 'pool_id', 'source'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all...
Get the statistics of load balancer pool # noqa: E501 Returns the statistics of the given load balancer pool by given load balancer serives id and load balancer pool id. Currently, only realtime mode is supported. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP req...
625941b16fece00bbac2d4a9
def convertSessionsToJSON(session): <NEW_LINE> <INDENT> if len(session) < 10: <NEW_LINE> <INDENT> return errorMessage("passed wrong amount of values to convertSessionsToJSON, it needs all elements in session table") <NEW_LINE> <DEDENT> result = { 'sessionID' : session[0], 'userID' : session[1], 'moduleID' : session[2],...
Converts the session object into a JSON object and returns the latter. A session record has 10 fields. If the passed in object has less than 10 fields, it is assumed to be just a regular session object, and so it is converted into a JSON object those the keys are the respective field names. But if the passed in object...
625941b1e64d504609d745b6
def load_configs(cfile): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(cfile, "r") as conf_file: <NEW_LINE> <INDENT> conf = yaml.load(conf_file) <NEW_LINE> <DEDENT> <DEDENT> except : <NEW_LINE> <INDENT> e = sys.exc_info()[0] <NEW_LINE> print("Could not load: {}".format(e)) <NEW_LINE> conf = dict() <NEW_LINE> <...
Load the config from the given absolute path file name
625941b121a7993f00bc7a5d
def create_ws_lex(*lex_list): <NEW_LINE> <INDENT> f_lex = _tempfile.NamedTemporaryFile(mode='w') <NEW_LINE> lex_file = f_lex.name <NEW_LINE> for lex in lex_list: <NEW_LINE> <INDENT> print('\t'.join(lex), file=f_lex) <NEW_LINE> <DEDENT> f_lex.flush() <NEW_LINE> return lex_file, f_lex
Generate CKIP word segmentation lexicon file. Parameters ---------- *lex_list : Tuple[str, str] the lexicon word and its POS-tag. Returns ------- lex_file : str the name of the lexicon file. f_lex : TextIO the file object. .. attention:: Remember to close **f_lex** manually.
625941b1d164cc6175782abd
def import_txt_files(self, path): <NEW_LINE> <INDENT> print("Importing text files...") <NEW_LINE> txt_files = glob.glob(os.path.join(os.getcwd(), path, "*.txt")) <NEW_LINE> corpus = [] <NEW_LINE> try: <NEW_LINE> <INDENT> for individual_file in txt_files: <NEW_LINE> <INDENT> with open(individual_file) as f_input: <NEW_L...
Loads a series of text files into Python. Input ----------------------------------------- path : string This is the directory path to your folder of text files. Note that the path must be in single ('') or double ("") quotations. To avoid confusion during processing, this directory should only contain the ...
625941b1e5267d203edcda18
def compute_ncc_fast(gray_left, gray_right, mask_halfwidth): <NEW_LINE> <INDENT> m_height, m_width = gray_left.shape <NEW_LINE> patches_left = np.zeros((m_height, m_width, (2 * mask_halfwidth + 1) ** 2)) <NEW_LINE> patches_right = np.zeros((m_height, m_width, (2 * mask_halfwidth + 1) ** 2)) <NEW_LINE> corr = np.zeros((...
Faster version of compute_ncc(). Args: gray_left (np.array of shape (num_rows, num_cols)): left grayscale image gray_right (np.array of shape (num_rows, num_cols)): right grayscale image mask_halfwidth (int): Half-size of the square neighbourhood used for computing NCC. Thus a patch of size ...
625941b124f1403a926008e2
def text2num( s: str, search_fraction: bool = True, ) -> Optional[Decimal]: <NEW_LINE> <INDENT> n: Decimal = Decimal(0) <NEW_LINE> prefix: Decimal = Decimal(0) <NEW_LINE> s: str = cleanup(s) <NEW_LINE> if s in ('k', 'm', 'b'): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if NON_WRIT_RE.fullmatch(s): <NEW_LINE> <...
Convert written amount into Decimal. :param s: written number :param search_fraction: extract fraction :return: Decimal or None
625941b191af0d3eaac9b789
def test_initial(self): <NEW_LINE> <INDENT> while (True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> conn['test']['test'].remove(safe=True) <NEW_LINE> break <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> s.delete(q='*:*') <NEW_LINE> self.assertEqual(conn['test']['test'].find().c...
Tests search and assures that the databases are clear.
625941b1460517430c393f09
def merge(self, other_distro): <NEW_LINE> <INDENT> if TRACE: logger.debug(f'merge: {self!r} with: {other_distro!r}') <NEW_LINE> existing = self.to_dict() <NEW_LINE> if other_distro: <NEW_LINE> <INDENT> other_non_empty = { k: v for k, v in other_distro.to_dict().items() if v } <NEW_LINE> existing.update(other_non_empty)...
Return a new distro based on this Distro data updated with non-empty values from the ``other_distro`` Distro object.
625941b182261d6c526ab213
def on_new(self, evt): <NEW_LINE> <INDENT> dlg = wx.MessageDialog(None, "Unsaved data will be lost", style=wx.OK | wx.CENTRE | wx.CANCEL | wx.ICON_WARNING) <NEW_LINE> dlg.SetOKCancelLabels("OK", "Cancel") <NEW_LINE> result = dlg.ShowModal() <NEW_LINE> if result == wx.ID_CANCEL: <NEW_LINE> <INDENT> return <NEW_LINE> <DE...
loads saved serialized data back to program
625941b13539df3088e2e0bb
def test_list(self): <NEW_LINE> <INDENT> view = SnippetViewSet.as_view({'get': 'list'}) <NEW_LINE> request = self.factory.get('/snippets') <NEW_LINE> response = view(request) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertEqual(response.data['count'], 1)
Snippet list may be retrieved without logging in
625941b10a50d4780f666c05
def var_handle_op(dtype, shape, container="", shared_name="", name=None): <NEW_LINE> <INDENT> _ctx = _context._context or _context.context() <NEW_LINE> if _ctx is not None and _ctx._thread_local_data.is_eager: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._contex...
Creates a handle to a Variable resource. Args: dtype: A `tf.DType`. the type of this variable. Must agree with the dtypes of all ops using this variable. shape: A `tf.TensorShape` or list of `ints`. The (possibly partially specified) shape of this variable. container: An optional `string`. Defaults to `"...
625941b1d7e4931a7ee9dc93
def run(self): <NEW_LINE> <INDENT> while (self.percepts['current_position'] != self.percepts['target']).any() and self.frontier: <NEW_LINE> <INDENT> self.act() <NEW_LINE> <DEDENT> print(self.percepts['current_position']) <NEW_LINE> print(self.path)
Keeps the agent acting until it finds the target
625941b1046cf37aa974cac2
def __init__(__self__, *, ip: str, description: Optional[str] = None, ports: Optional[Sequence[int]] = None, services: Optional[Sequence[str]] = None): <NEW_LINE> <INDENT> pulumi.set(__self__, "ip", ip) <NEW_LINE> if description is not None: <NEW_LINE> <INDENT> pulumi.set(__self__, "description", description) <NEW_LINE...
:param str ip: Source ip and netmask for the rule. (e.g. 10.56.72.0/24) :param str description: Description name of the rule. e.g. Default. :param Sequence[int] ports: Custom ports to be opened :param Sequence[str] services: Pre-defined service ports, see table below
625941b17b180e01f3dc4580
def cost(self, coefs): <NEW_LINE> <INDENT> A = self.feed_forward(self.X, coefs) <NEW_LINE> J = (1 / (2 * len(self.y))) * np.sum((A - self.y_hot) ** 2) <NEW_LINE> regularization = np.dot(coefs ** 2, self.regularization_mask) <NEW_LINE> return J + (self.alpha / 2) * regularization
Calculates the cost of the weights. :param coefs: :return:
625941b16aa9bd52df036b12
def get_shuffle_mode(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.__read_property('Shuffle') <NEW_LINE> <DEDENT> except dbus.exceptions.DBusException as err: <NEW_LINE> <INDENT> raise
Check if shuffle mode is enabled or disabled. :returns: 1 if shuffle is enabled, 0 if not
625941b1adb09d7d5db6c50c
def sections(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sections = self.read(self.file_spec) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> raise ConfigError("No initiation file named: %s" % (self.file_spec)) <NEW_LINE> <DEDENT> return [section for section in sections]
Return a list of section names for the given file.
625941b18a43f66fc4b53de3
def tracked_kickstart_elements_get_refs_kickstart_test(self): <NEW_LINE> <INDENT> appended_elements = [self._element1, self._element2, self._element3, self._element4, self._element5, self._element6, self._element7] <NEW_LINE> elements = TrackedKickstartElements() <NEW_LINE> for element in appended_elements: <NEW_LINE> ...
Test getting of element references.
625941b1b57a9660fec335ef
def _choose_split_index(self, X, y): <NEW_LINE> <INDENT> y_entropy = self.impurity_criterion(y) <NEW_LINE> lst_splits = [] <NEW_LINE> for coln in xrange(1, len(X[0])): <NEW_LINE> <INDENT> for value in xrange(len(X)): <NEW_LINE> <INDENT> X1, y1, X2, y2 = self._make_split( X, y, coln, X[value, coln] ) <NEW_LINE> rst = se...
INPUT: - X: 2d numpy array - y: 1d numpy array OUTPUT: - index: int (index of feature) - value: int/float/bool/str (value of feature) - splits: (2d array, 1d array, 2d array, 1d array) Determine which feature and value to split on. Return the index and value of the optimal split along with the spli...
625941b173bcbd0ca4b2bded
def testIncidentViewModel(self): <NEW_LINE> <INDENT> pass
Test IncidentViewModel
625941b163b5f9789fde6e5c
def __getitem__(self, key: Union[slice, int]) -> Observable[_T]: <NEW_LINE> <INDENT> if isinstance(key, slice): <NEW_LINE> <INDENT> start, stop, step = key.start, key.stop, key.step <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> start, stop, step = key, key + 1, 1 <NEW_LINE> <DEDENT> from ..operators._slice import slice...
Pythonic version of :func:`slice <reactivex.operators.slice>`. Slices the given observable using Python slice notation. The arguments to slice are `start`, `stop` and `step` given within brackets `[]` and separated by the colons `:`. It is basically a wrapper around the operators :func:`skip <reactivex.operators.skip...
625941b13c8af77a43ae3518
def swipe_to_right(self): <NEW_LINE> <INDENT> window_size = self.get_size() <NEW_LINE> width = window_size.get("width") <NEW_LINE> height = window_size.get("height") <NEW_LINE> self.driver.swipe(width * 4 / 5, height / 2, width / 5, height / 2, 500)
向右移动 :return:
625941b1e1aae11d1e749a2b
def new_entity(self, attributes): <NEW_LINE> <INDENT> entity = self.model.lookup(attributes['email']) <NEW_LINE> if entity: <NEW_LINE> <INDENT> raise BadValueError('user already exists') <NEW_LINE> <DEDENT> attributes['email'] = [attributes['email']] <NEW_LINE> entity = self.model.from_dict(attributes) <NEW_LINE> retur...
Creates a new entity with given attributes. :param attributes: (dictionary) default values loaded on object instantiation :return: entity with loaded attributes
625941b1187af65679ca4e97
def _update(self, start, end): <NEW_LINE> <INDENT> means = self._moving_mean[start:end] <NEW_LINE> tail_runner = self._moving_mean.tail_runner <NEW_LINE> tail_size = tail_runner.tail_size <NEW_LINE> n = tail_size <NEW_LINE> if self._with_unbiased_correction: <NEW_LINE> <INDENT> n -= 1 <NEW_LINE> <DEDENT> variance = emp...
Adds calculation of the variance and/or :param start: The start index to update. :param end: The end index to update. :return:
625941b1e64d504609d745b8
def on_child_end(self, child_state): <NEW_LINE> <INDENT> logger.warning('Probably missing implementation for ' '%r.on_child_end(%r): ', self, child_state)
B{May} be implemented in every subclass. If implemented, should contain the code which is called whenever any child transaction (i.e. a transaction executed from inside the C{self} one) is completed. At the moment o @note: if overriding in a subclass, you may ignore calling the C{super} method (i.e. this one). A...
625941b1507cdc57c6306a42
def delete_ref(refname, oldvalue=None): <NEW_LINE> <INDENT> assert refname.startswith(b'refs/') <NEW_LINE> oldvalue = [] if not oldvalue else [oldvalue] <NEW_LINE> p = subprocess.Popen([b'git', b'update-ref', b'-d', refname] + oldvalue, env=_gitenv()) <NEW_LINE> _git_wait('git update-ref', p)
Delete a repository reference (see git update-ref(1)).
625941b10a366e3fb873e589
def get(self, request, **kwargs): <NEW_LINE> <INDENT> slug = kwargs.get("article_slug") <NEW_LINE> comment_id = kwargs.get("comment_pk") <NEW_LINE> response = UpdateDestroyCommentsAPIView.check_exists(slug, comment_id) <NEW_LINE> if not isinstance(response, list): <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT>...
Get a single comment
625941b11d351010ab855897
def test_pharmaceutical_list(self): <NEW_LINE> <INDENT> test_response = self.client.get('/parameter/pharmaceutical') <NEW_LINE> self.assertEqual(test_response.status_code, 200) <NEW_LINE> self.assertTrue('pharmaceutical_list' in test_response.context) <NEW_LINE> self.assertTemplateUsed(test_response, 'pharmaceutical_li...
This tests the pharmaceutical-list view, ensuring that templates are loaded correctly. This view uses a user with superuser permissions so does not test the permission levels for this view.
625941b132920d7e50b27f45
def apply_variable_template_tags(line): <NEW_LINE> <INDENT> return re.sub(r'\${\s*(\w+)\s*}', TEMPLATE_VARIABLE_OPENING_TAG + r"\1" + TEMPLATE_VARIABLE_CLOSING_TAG, line, flags=re.UNICODE)
Replaces variable indicators ${ and } with tags, so subsequent formatting is easier.
625941b18e05c05ec3eea0e9
def test_find_mssm_decay_groups(self): <NEW_LINE> <INDENT> mssm = import_ufo.import_model('mssm') <NEW_LINE> decay_mssm = decay_objects.DecayModel(mssm, True) <NEW_LINE> decay_mssm.find_decay_groups() <NEW_LINE> goal_groups = [[25, 35, 36, 37], [1000001, 1000002, 1000003, 1000004, 1000005, 1000006, 1000011, 1000012, 10...
Test finding the decay groups of the MSSM
625941b1d486a94d0b98dec2
def generate_filename_and_macs(items): <NEW_LINE> <INDENT> hw_items = list(items) <NEW_LINE> sysvars = {} <NEW_LINE> sysvars['sysname'] = '' <NEW_LINE> match_spec(('system', 'product', 'vendor', '$sysprodvendor'), hw_items, sysvars) <NEW_LINE> if 'sysprodvendor' in sysvars: <NEW_LINE> <INDENT> sysvars['sysname'] += (re...
Generate a file name for a hardware using DMI information. (product name and version) then if the DMI serial number is available we use it unless we lookup the first mac address. As a result, we do have a filename like : <dmi_product_name>-<dmi_product_version>-{dmi_serial_num|mac_address}
625941b1596a89723608983d
def _check_event_type(self, et): <NEW_LINE> <INDENT> if et not in EVENT_TYPE_CONFIG.keys(): <NEW_LINE> <INDENT> raise MetadataPostException('{0} is not a valid event type'.format(et))
Validate user supplied event type strings.
625941b16fece00bbac2d4ac
def __init__(self, token): <NEW_LINE> <INDENT> self.session = requests.Session() <NEW_LINE> self.token = token <NEW_LINE> self.session.headers.update({"Authorization": f"bearer {token}"}) <NEW_LINE> self.session.headers.update({"User-Agent": f"thoth_sesheta_topic_checker/{sesheta.__version__}"})
Init with some sane defaults.
625941b13317a56b869399dd
def __after(self, location: str) -> tuple: <NEW_LINE> <INDENT> result_dict = WeatherSearcher().naver_search(location) <NEW_LINE> result, josa = WeatherEditor().edit_after(result_dict) <NEW_LINE> return WeatherAnswerer().morning_afternoon_form(location, "모레", result, josa), result_dict
모네 날씨를 검색하고 조합합니다. :param location: 지역 :return: 모레 날씨
625941b176d4e153a657e8a5
def create_from_data(self, repository, diff_file_name, diff_file_contents, parent_diff_file_name, parent_diff_file_contents, diffset_history, basedir, request, base_commit_id=None, save=True): <NEW_LINE> <INDENT> from reviewboard.diffviewer.diffutils import convert_to_unicode <NEW_LINE> from reviewboard.diffviewer.mode...
Create a DiffSet from raw diff data. The diff_file_contents and parent_diff_file_contents parameters are strings with the actual diff contents.
625941b1287bf620b61d37e5
def store(self, guid): <NEW_LINE> <INDENT> if guid == 'public': <NEW_LINE> <INDENT> if not self.public_store: <NEW_LINE> <INDENT> raise NotFoundError( "no public store for company '%s'" % self.name ) <NEW_LINE> <DEDENT> return self.public_store <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.server.store(guid...
Store for the given GUID :param guid: store guid :return: :class:`store <Store>` with given GUID.
625941b1bf627c535bc12f4a
def copy(self, cr, uid, id, default=None, context=None): <NEW_LINE> <INDENT> default.update({ 'name': self.pool.get('ir.sequence').get(cr, uid, 'credit.sj.guarantee.application'), 'submit_time': False, 'guarantee_user': False, 'guarantee_result': False, 'guarantee_result_note':False, 'route_line':False }) <NEW_LINE> re...
复制方法重写
625941b16fece00bbac2d4ad
def gateway(): <NEW_LINE> <INDENT> if settings.CAS_GATEWAY == False: <NEW_LINE> <INDENT> raise ImproperlyConfigured('CAS_GATEWAY must be set to True') <NEW_LINE> <DEDENT> def wrap(func): <NEW_LINE> <INDENT> def wrapped_f(*args): <NEW_LINE> <INDENT> from django_cas.views import login <NEW_LINE> request = args[0] <NEW_LI...
Authenticates single sign on session if ticket is available, but doesn't redirect to sign in url otherwise.
625941b13c8af77a43ae351a
def write_contents(lang_fd_map, lang_limit_map, category): <NEW_LINE> <INDENT> catQ = Queue() <NEW_LINE> catQ.put(category) <NEW_LINE> while not catQ.empty(): <NEW_LINE> <INDENT> cat = catQ.get() <NEW_LINE> printTitle(cat, prefix="category: ") <NEW_LINE> pages, sub_cats = retrieve_contents(cat) <NEW_LINE> [catQ.put(cat...
Starts from the given category and in top-down way, using BFS, parse the content of all pages under the given category and its sub-categories at all levels. Then writing the sentences in the related files up to the given limit. :param: lang_fd_map - dictionary between language prefix and the fd which stores the sentenc...
625941b1187af65679ca4e99
def test_import_record_with_invalid_backup(self): <NEW_LINE> <INDENT> export = self._create_exported_record_entry() <NEW_LINE> backup_driver = self.backup_mgr.service.get_backup_driver(self.ctxt) <NEW_LINE> _mock_record_import_class = ('%s.%s.%s' % (backup_driver.__module__, backup_driver.__class__.__name__, 'import_re...
Test error handling when attempting an import of a backup record where the backup driver returns an exception.
625941b130bbd722463cbb3d
def notationDecl(self, QString, QString_1, QString_2): <NEW_LINE> <INDENT> return False
QXmlDefaultHandler.notationDecl(QString, QString, QString) -> bool
625941b166673b3332b91e09
def childEq(self, node, other): <NEW_LINE> <INDENT> raise NotImplementedError()
Returns equality of `node` and an `other` node as children. ``True`` if the child features of the two nodes are equal without considering the root. Subclasses must override this.
625941b191af0d3eaac9b78d
def stest_03(self): <NEW_LINE> <INDENT> self.new.lineEdit(self.new.news_time_loc, '20117--12-12') <NEW_LINE> self.new.buttonClick(self.new.news_author_loc) <NEW_LINE> sleep(1) <NEW_LINE> self.assertEqual(self.new.switch_to_alert().text, '不合法的日期格式或者日期超出限定范围,需要撤销吗?') <NEW_LINE> self.new.switch_to_alert().accept() <NEW_LI...
发布新闻-时间输入错误的格式
625941b14a966d76dd550d85
def deserialize(self, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.joint is None: <NEW_LINE> <INDENT> self.joint = None <NEW_LINE> <DEDENT> end = 0 <NEW_LINE> start = end <NEW_LINE> end += 4 <NEW_LINE> (length,) = _struct_I.unpack(str[start:end]) <NEW_LINE> self.joint = [] <NEW_LINE> for i in range(0, len...
unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str``
625941b182261d6c526ab217
def project_redundancies_and_constraints(self, fq, H): <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> Nint = self.num_intcos <NEW_LINE> G = self.Gmat() <NEW_LINE> G_inv = symm_mat_inv(G, redundant=True) <NEW_LINE> Pprime = np.dot(G, G_inv) <NEW_LINE> C = self.constraint_matrix(fq) <NEW_LINE> if C i...
Project redundancies and constraints out of forces and Hessian
625941b13346ee7daa2b2adb
def test_empty(self): <NEW_LINE> <INDENT> self.assertEqual(1, solution([]))
Empty array
625941b1b57a9660fec335f2
def testPrepaymentRechargeResponse(self): <NEW_LINE> <INDENT> model = kinow_client.models.prepayment_recharge_response.PrepaymentRechargeResponse()
Test PrepaymentRechargeResponse
625941b10a50d4780f666c09
def create_superuser(self,email,name,password): <NEW_LINE> <INDENT> user = self.create_user(email,name,password) <NEW_LINE> user.is_superuser = True <NEW_LINE> user.is_staff = True <NEW_LINE> user.save(using=self._db)
creates and saves a new superuser with given details.
625941b17b180e01f3dc4584
def clDummy(*args, **kw): <NEW_LINE> <INDENT> pass
Dummy do-nothing function
625941b1711fe17d825420f1
def get(self, name_or_klass): <NEW_LINE> <INDENT> if not isinstance(name_or_klass, str): <NEW_LINE> <INDENT> name_or_klass = name_or_klass.__name__ <NEW_LINE> <DEDENT> for zone in range(4): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> panel = self._panels[zone][name_or_klass] <NEW_LINE> <DEDENT> except KeyError: <NEW_L...
Gets a specific panel instance. :param name_or_klass: Name or class of the panel to retrieve. :return: The specified panel instance.
625941b13317a56b869399e0
def beginPage(self, nextpos): <NEW_LINE> <INDENT> self.pagecount += 1 <NEW_LINE> mediatypelabel = "Plain" <NEW_LINE> mediasourcelabel = "Main" <NEW_LINE> mediasizelabel = "Default" <NEW_LINE> orientationlabel = "Portrait" <NEW_LINE> duplexmode = None <NEW_LINE> minfile = self.minfile <NEW_LINE> pos = nextpos - 2 <NEW_L...
Indicates the beginning of a new page, and extracts media information.
625941b15166f23b2e1a4ed4
def DCT(mspec, nceps): <NEW_LINE> <INDENT> ceps = scipy.fftpack.realtransforms.dct(mspec, type=2, norm="ortho", axis=-1) <NEW_LINE> return ceps[:nceps]
離散コサイン変換
625941b15e10d32532c5eca5
def to_dict(self): <NEW_LINE> <INDENT> return self._instance_document
Render this object as a dictionary.
625941b18a349b6b435e7ef1
def test_annotate(self): <NEW_LINE> <INDENT> sentences, mentions = annotate_document(self._doc, self._client) <NEW_LINE> self.assertEqual(3, len(sentences)) <NEW_LINE> self.assertEqual(21, len(mentions)) <NEW_LINE> m_he = mentions[0] <NEW_LINE> m_barack = mentions[6] <NEW_LINE> self.assertEqual(sentences[0], m_barack.s...
Verify that, after processing the annotated document, the mentions should correctly identify:
625941b18a43f66fc4b53de7
def ueber3morgen_request(bot, update): <NEW_LINE> <INDENT> wanted_date = plusdays_date(4) <NEW_LINE> essens,status=get_food(wanted_date) <NEW_LINE> if status: <NEW_LINE> <INDENT> food_string= make_pretty_string(essens,wanted_date,update.message.from_user.first_name) <NEW_LINE> bot.send_message(chat_id=update.message.ch...
args == plusdays
625941b1bf627c535bc12f4c
def assign_streaming_edge_service(self, cdn_region, pop=None): <NEW_LINE> <INDENT> assert type(cdn_region) is str <NEW_LINE> assert pop is None or type(pop) is str <NEW_LINE> cdn_region = self.cdn_region_map[cdn_region] <NEW_LINE> if pop is not None: <NEW_LINE> <INDENT> pop = pop.encode('utf-8') <NEW_LINE> <DEDENT> ass...
Assign streaming edge service from a given region and POP (if given).
625941b1d8ef3951e32432b2
def is_now(self) -> bool: <NEW_LINE> <INDENT> return type(self) == Now
Returns: bool: True if `self` is instance of `Now`, False otherwise
625941b16fece00bbac2d4af
def p_spdx_version_1(self, p): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if six.PY2: <NEW_LINE> <INDENT> value = p[2].decode(encoding='utf-8') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = p[2] <NEW_LINE> <DEDENT> self.builder.set_doc_version(self.document, value) <NEW_LINE> <DEDENT> except CardinalityError:...
spdx_version : DOC_VERSION LINE
625941b1d268445f265b4be9
def id(self): <NEW_LINE> <INDENT> return self.data.id
Returns the id of the proc @rtype: str @return: Proc uuid
625941b1de87d2750b85fb04
def _echelon_matrix_richcmp(self, other, op): <NEW_LINE> <INDENT> if self is other: <NEW_LINE> <INDENT> return rich_to_bool(op, 0) <NEW_LINE> <DEDENT> if not isinstance(other, FreeModule_generic): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> lx = self.ambient_vector_space() <NEW_LINE> rx = other.ambien...
Compare the free module ``self`` with other. Modules are ordered by their ambient spaces, then by dimension, then in order by their echelon matrices. .. NOTE:: Use :meth:`is_submodule` to determine if one module is a submodule of another. EXAMPLES: First we compare two equal vector spaces. :: sage: fro...
625941b1462c4b4f79d1d44b
def __call__(self, uid, fname, value): <NEW_LINE> <INDENT> res = {'errmsg': ''} <NEW_LINE> rc = getToolByName(aq_inner(self.context), 'reference_catalog') <NEW_LINE> instance = rc.lookupObject(uid) <NEW_LINE> if instance is None: <NEW_LINE> <INDENT> instance = self.context <NEW_LINE> <DEDENT> field = instance.getField(...
Validate a given field. Return any error messages.
625941b13539df3088e2e0c0
def test_unicode_sockopts(self): <NEW_LINE> <INDENT> topic = "tést" <NEW_LINE> if str is not unicode: <NEW_LINE> <INDENT> topic = topic.decode('utf8') <NEW_LINE> <DEDENT> p,s = self.create_bound_pair(zmq.PUB, zmq.SUB) <NEW_LINE> self.assertEqual(s.send_unicode, s.send_unicode) <NEW_LINE> self.assertEqual(p.recv_unicode...
test setting/getting sockopts with unicode strings
625941b11d351010ab85589b
def test_password_too_short(self): <NEW_LINE> <INDENT> payload = { 'email': 'test@londonappdev.com', 'password': 'pw', 'name': 'Test', } <NEW_LINE> res = self.client.post(CREATE_USER_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> user_exists = get_user_model().objects...
Test that the password must be more then 5 characters
625941b132920d7e50b27f49
def get_word(html): <NEW_LINE> <INDENT> Chinese_list = [] <NEW_LINE> Chinese_list_plus = [] <NEW_LINE> soup = BeautifulSoup(html, 'lxml') <NEW_LINE> [s.extract() for s in soup(['style', 'script', '[document]', 'head', 'title'])] <NEW_LINE> visible_text = soup.getText() <NEW_LINE> visible_text_001 = visible_text.replace...
Args: html crawled by request Returns: Return the plain text of the page
625941b1d8ef3951e32432b3
def GoToUserTwitterProfile(self): <NEW_LINE> <INDENT> self.driver.find_element_by_xpath(XPATH_USER_PROFILE).click() <NEW_LINE> time.sleep(LOAD_TIME * 2)
Navigates to the user's Twitter profile.
625941b1627d3e7fe0d68bc4
@api_view(['GET','PUT']) <NEW_LINE> def object_upload(request, container, format=None): <NEW_LINE> <INDENT> url = 'http://10.129.103.86:5000/v3/auth/tokens' <NEW_LINE> headers = {'content-type': 'application/json'} <NEW_LINE> data = '\n{ "auth": {\n "identity": {\n "methods": ["password"],\n "password": {\...
Generating Token each time
625941b10383005118ecf35b
def lex_prefixed_str(self, prefix): <NEW_LINE> <INDENT> s = self.match(re.compile('[a-z]+[\'"]')) <NEW_LINE> if s.endswith("'"): <NEW_LINE> <INDENT> re1 = self.str_exp_single <NEW_LINE> re2 = self.str_exp_single_multi <NEW_LINE> if 'r' in prefix: <NEW_LINE> <INDENT> re1 = self.str_exp_raw_single <NEW_LINE> re2 = self.s...
Analyse a string literal with a prefix, such as r'...'.
625941b13317a56b869399e2
def sort(self, tags): <NEW_LINE> <INDENT> if not isinstance(tags, tuple): <NEW_LINE> <INDENT> tags = (tags,) <NEW_LINE> <DEDENT> ascend_descend = [SSort(abs(tag), TABLE_SORT_DESCEND if tag < 0 else TABLE_SORT_ASCEND) for tag in tags] <NEW_LINE> self.mapitable.SortTable(SSortOrderSet(ascend_descend, 0, 0), 0)
Sort table. :param tags: Tag(s) on which to sort.
625941b18a43f66fc4b53de8
def set_device(self, gpus, device): <NEW_LINE> <INDENT> self.device = device <NEW_LINE> if len(gpus) > 1: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.model_with_loss = self.model_with_loss.to(self.device) <NEW_LINE> <DEDENT> for state in self.optimizer.state.values(): <NEW_LINE> <INDENT>...
将model_with_loss与优化器, 放置到合适的设备上(cpu或gpus) :param gpus: 可以使用的gpu索引列表, 例如使用3个GPU [0, 1, 2] :param device: 使用的设备: 'cpu'/'cuda' :return: 无
625941b14f6381625f1147bd