code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def register(self, connection): <NEW_LINE> <INDENT> self.connections.add(connection)
Register new connection.
625941e4167d2b6e31218f91
def cast(value): <NEW_LINE> <INDENT> numeric_value = value[(1 if value.startswith('-') else 0):] <NEW_LINE> if numeric_value.isdigit(): <NEW_LINE> <INDENT> return int(value) <NEW_LINE> <DEDENT> if all(v.isdigit() for v in numeric_value.split('.', 1)): <NEW_LINE> <INDENT> return float(value) <NEW_LINE> <DEDENT> matches ...
Cast the values
625941e4cad5886f8bd273d5
def _stochastic_gradient_descent(self, data: ndarray, label: ndarray, learning_rate: float, epochs: int, sample_rate: float, random_state): <NEW_LINE> <INDENT> if random_state is not None: <NEW_LINE> <INDENT> seed(random_state) <NEW_LINE> <DEDENT> n_rows, n_cols = data.shape <NEW_LINE> self.bias = 0 <NEW_LINE> self.wei...
Update the gradient by the random sample of dataset. b = b - learning_rate * b_sample_grad_i, b_sample_grad_i <- sample_grad W = W - learning_rate * w_sample_grad_i, w_sample_grad_i <- sample_grad Arguments: data {ndarray} -- Training data. label {ndarray} -- Target values. learning_rate {float} -- Learnin...
625941e4e8904600ed9f232e
@receiver(post_save, sender=User) <NEW_LINE> def save_user_profile(sender, instance, **kwargs): <NEW_LINE> <INDENT> instance.profile.save()
When a new user is created, saves their profile.
625941e430bbd722463cc1c3
def runJob(self, rdd, partitionFunc, partitions=None, allowLocal=False): <NEW_LINE> <INDENT> if partitions is None: <NEW_LINE> <INDENT> partitions = range(rdd._jrdd.partitions().size()) <NEW_LINE> <DEDENT> javaPartitions = ListConverter().convert(partitions, self._gateway._gateway_client) <NEW_LINE> mappedRDD = rdd.map...
Executes the given partitionFunc on the specified set of partitions, returning the result as an array of elements. If 'partitions' is not specified, this will run over all partitions. >>> myRDD = sc.parallelize(range(6), 3) >>> sc.runJob(myRDD, lambda part: [x * x for x in part]) [0, 1, 4, 9, 16, 25] >>> myRDD = sc....
625941e43617ad0b5ed682f2
def min(self, vname): <NEW_LINE> <INDENT> vmin = self.data[vname].min() <NEW_LINE> time_index = list(self.data[vname]).index(vmin) <NEW_LINE> return vmin,time_index
vmin,time_index = self.min(vname) *vname is in self.data.keys() * vmin=self.data[vname].min() * self.data[vname][time_index]=vmin
625941e421bff66bcd684d4a
def results(self): <NEW_LINE> <INDENT> self.log.info("Generating results from {0.policy}".format(self)) <NEW_LINE> self.log.debug("Address: {0.addr!r}, overlap: {0.addr_overlap}, " "subset: {0.addr_subset}, superset: {0.addr_superset}, " "proper: {0.addr_proper}".format(self)) <NEW_LINE> self._match_context_debug(self....
Generator which yields all matching iomemcons.
625941e4e64d504609d74c3c
def select_empty_box(wait): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> locator = (By.CSS_SELECTOR, '.square') <NEW_LINE> elements = wait.until(EC.visibility_of_all_elements_located(locator)) <NEW_LINE> empty = [] <NEW_LINE> for box in elements: <NEW_LINE> <INDENT> box: WebElement <NEW_LINE> cell = box.find_element_by...
Select an empty box
625941e430dc7b7665901d5e
def __init__(self, n_electrodes, radius, x_center, y_center): <NEW_LINE> <INDENT> self._electrodes = coll.OrderedDict() <NEW_LINE> for n in range(n_electrodes): <NEW_LINE> <INDENT> ang = 2.0 * np.pi / n_electrodes * n <NEW_LINE> electrode = DiskElectrode(x_center + np.cos(ang) * radius, y_center + np.sin(ang) * radius,...
Electrodes arranged in a circle Electrodes will be named 'A0', 'A1', ... Parameters ---------- n_electrodes : int how many electrodes to arrange in a circle radius : float the radius of the circle (microns) x_center, y_center : float the x,y coordinates of the center of the circle (microns), where (0,...
625941e4d7e4931a7ee9e31b
def validate_xml(self, xmlfile, xsdfile): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> xsdfileText = open(xsdfile, 'r') <NEW_LINE> xsdFileInput = xsdfileText.read() <NEW_LINE> filteredXMLText = re.sub("&", "&amp;", xmlfile) <NEW_LINE> xsv.parseAndValidateString(filteredXMLText, xsdFileInput, xmlIfClass=xsv.XMLIF_ELEMEN...
This method will be used on a server side to validate and process the xml file with an existing xsd schema. If xml is not well-formed or doesn't match the schema, false is returned
625941e4498bea3a759b9eaa
def augmentator(labels, images): <NEW_LINE> <INDENT> seq_det = seq.to_deterministic() <NEW_LINE> images = seq_det.augment_images(images) <NEW_LINE> k_imgs = [] <NEW_LINE> for idx in range(len(labels)): <NEW_LINE> <INDENT> anno = labels[idx] <NEW_LINE> image = images[idx] <NEW_LINE> ks = anno["keypoint_annotations"] <NE...
Augment batch label and image, format: BL and NHWC :param labels: :param images: :return: augmented labels and images
625941e43539df3088e2e747
def read_image_list(pathToList): <NEW_LINE> <INDENT> f = open(pathToList, 'r') <NEW_LINE> filenames = [] <NEW_LINE> for line in f: <NEW_LINE> <INDENT> if line[-1] == '\n': <NEW_LINE> <INDENT> filenames.append(line[:-1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> filenames.append(line) <NEW_LINE> <DEDENT> <DEDENT> f....
Reads a .txt file containing paths to the images Args: image_list_file: a .txt file with one /path/to/image per line label: optionally, if set label will be pasted after each line Returns: List with all filenames in file image_list_file
625941e4b5575c28eb68e3ff
def run_periodic_tasks(self, context, raise_on_error=False): <NEW_LINE> <INDENT> for task_name, task in self._periodic_tasks: <NEW_LINE> <INDENT> full_task_name = '.'.join([self.__class__.__name__, task_name]) <NEW_LINE> ticks_to_skip = self._ticks_to_skip[task_name] <NEW_LINE> if ticks_to_skip > 0: <NEW_LINE> <INDENT>...
Tasks to be run at a periodic interval.
625941e4d53ae8145f87a664
def language(self): <NEW_LINE> <INDENT> if isinstance(self.lexer, QsciLexer): <NEW_LINE> <INDENT> return self.lexerName <NEW_LINE> <DEDENT> return 'None'
Getter for language.
625941e49b70327d1c4e11d3
def extract_sdk(d): <NEW_LINE> <INDENT> export_dir = os.path.dirname(os.path.realpath(__file__)) <NEW_LINE> tools_dir = d.getVar("TEST_EXPORT_SDK_DIR") <NEW_LINE> tarball_name = "%s.sh" % d.getVar("TEST_EXPORT_SDK_NAME") <NEW_LINE> tarball_path = os.path.join(export_dir, tools_dir, tarball_name) <NEW_LINE> extract_path...
Extract SDK if needed
625941e4627d3e7fe0d6924d
def new_to_db(self): <NEW_LINE> <INDENT> table_main = to_db_obj_name(self.table_main) <NEW_LINE> user = (self.name, self.password_hash, self.is_admin) <NEW_LINE> self.db.c.execute(f'INSERT INTO "{table_main}" (name, password_hash, is_admin) ' 'VALUES (?, ?, ?)', user) <NEW_LINE> new_row_id = (self.db.c.lastrowid,) <NEW...
Write a new user to the DB. Return id assigned by the DB.
625941e407d97122c4178c90
def setup(hass, config): <NEW_LINE> <INDENT> for url_name, info in config[DOMAIN].items(): <NEW_LINE> <INDENT> register_built_in_panel( hass, 'iframe', info.get(CONF_TITLE), info.get(CONF_ICON), url_name, {'url': info[CONF_URL]}) <NEW_LINE> <DEDENT> return True
Setup iframe frontend panels.
625941e4566aa707497f495f
def receive_input(self, ch): <NEW_LINE> <INDENT> self.input_buffer.append(ch) <NEW_LINE> index = 0 <NEW_LINE> pointer = self.RAM[0x9010] <NEW_LINE> while not self.RAM[pointer]: <NEW_LINE> <INDENT> self.RAM[pointer] = self.input_buffer[index] <NEW_LINE> index += 1 <NEW_LINE> pointer += 1 <NEW_LINE> if pointer <= 0x9010:...
Handle some input from the terminal.
625941e4507cdc57c63070e0
def _find_userfolder(self, userid): <NEW_LINE> <INDENT> uf_parent = aq_inner(self.context) <NEW_LINE> info = None <NEW_LINE> while not info: <NEW_LINE> <INDENT> uf = getToolByName(uf_parent, "acl_users") <NEW_LINE> if uf: <NEW_LINE> <INDENT> info = uf._verifyUser(uf.plugins, login=userid) <NEW_LINE> <DEDENT> if uf_pare...
Try to find a user folder that contains a user with the given userid.
625941e476e4537e8c351a71
def survey_vecs(s): <NEW_LINE> <INDENT> freqlen_lst = [] <NEW_LINE> chanlen_lst = [] <NEW_LINE> freqlen_dict = {} <NEW_LINE> chanlen_dict = {} <NEW_LINE> for fp in s.pointer_lst: <NEW_LINE> <INDENT> f_vec = handle_parse(fp, 'opt/f_vec_ds', 'array') <NEW_LINE> chans = handle_parse(fp, 'opt/elec_array', 'text_array') <NE...
survey all .mat's for their frequency and channel vectors, and create data structures to keep track of them for later steps
625941e4cc40096d61595d4b
def isValidBST(self, root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> pre = None <NEW_LINE> cur = root <NEW_LINE> nodeStack = [] <NEW_LINE> while cur or nodeStack: <NEW_LINE> <INDENT> while cur: <NEW_LINE> <INDENT> nodeStack.append(cur) <NEW_LINE> cur = cur.left <NEW_LINE> <DE...
:type root: TreeNode :rtype: bool
625941e4c4546d3d9de72e33
def udunits_error_messages(flag): <NEW_LINE> <INDENT> if flag: <NEW_LINE> <INDENT> _ut_set_error_message_handler(_udunits.ut_write_to_stderr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _ut_set_error_message_handler(_udunits.ut_ignore)
Controls the printing of error messages from Udunits. Error messages are turned off by default in Udunits. :Parameters: flag: `bool` Set to True to print Udunits error messages and False to not print Udunits error messages. :Returns: `None` **Examples:** >>> udunits_error_messages(True) >...
625941e45e10d32532c5f321
def model_building(df_train, df_test,model,title): <NEW_LINE> <INDENT> X_train,y_train = df_train.drop(drop_un,axis = 1), df_train['PrepayFlag_6'] <NEW_LINE> X_test, y_test = df_test.drop(drop_un,axis = 1), df_test['PrepayFlag_6'] <NEW_LINE> y_testProba = model.predict_proba(X_test)[:,1] <NEW_LINE> y_trainProba = mo...
Function to 1.Predict Probabilities of Train and Test Data 2.to Plot roc_auc curve df_train = train data, df_test = test data, model = pass trained model, title = title of roc curve
625941e494891a1f4081bea7
def create_header_cells(self, *content): <NEW_LINE> <INDENT> return [self.create_header_cell(cell) for cell in content]
Create multiple TableHeaderCells and return them. >>> row = TableRow() >>> cells = row.create_header_cells("Cell 1", "Cell 2") >>> cells[0].id = "my-cell" >>> str(row) '<tr><th id="my-cell">Cell 1</th><th>Cell 2</th></tr>'
625941e491f36d47f21ac8f3
@manager.command <NEW_LINE> def cov(): <NEW_LINE> <INDENT> tests = unittest.TestLoader().discover('test/server') <NEW_LINE> result = unittest.TextTestRunner(verbosity=2).run(tests) <NEW_LINE> if result.wasSuccessful(): <NEW_LINE> <INDENT> COV.stop() <NEW_LINE> COV.save() <NEW_LINE> print('Coverage Summary:') <NEW_LINE>...
Runs the unit tests with coverage.
625941e476d4e153a657ef2e
def __addSysTopic(self, scmd): <NEW_LINE> <INDENT> jsTopic = json.loads(scmd.stringVal, "UTF8") <NEW_LINE> tsysTopic = TSysTopic() <NEW_LINE> tsysTopic._fromJson(jsTopic) <NEW_LINE> tsysTopic.topicId = MyUuid.getUuid() <NEW_LINE> tb = MongoDatabase.findTableByMessageType(TSysTopic) <NEW_LINE> if not tb: <NEW_LINE> <IND...
:type scmd: message.db.mongodb.utiltables.TSystemCommand :rtype: bool
625941e4e8904600ed9f232f
def create_max_heap(arr): <NEW_LINE> <INDENT> n = len(arr) <NEW_LINE> for i in range(int(n/2), -1, -1): <NEW_LINE> <INDENT> max_heapify(i, arr, n)
Converts a given array into a max heap :param arr: input array of numbers :return: output max heap
625941e4baa26c4b54cb1518
def TryGetEllipse(self,*__args): <NEW_LINE> <INDENT> pass
TryGetEllipse(self: Curve,plane: Plane) -> (bool,Ellipse) Try to convert this curve into an Ellipse within RhinoMath.ZeroTolerance. plane: Plane in which the comparison is performed. Returns: true if the curve could be converted into an Ellipse within the given plane. TryGetEllipse(self: Curve,plane: Plane,t...
625941e4b830903b967e9d03
def emit(filepath, errors, warnings, summaries): <NEW_LINE> <INDENT> log_emit(filepath, summaries=summaries) <NEW_LINE> return html_emit(filepath, errors=errors, warnings=warnings, summaries=summaries)
Generate HTML results. Main entry point to this module.
625941e41f5feb6acb0c4f45
def _bonds_from_distance(graph, nodes=None, non_edges=None, fudge=1.2): <NEW_LINE> <INDENT> if not nodes: <NEW_LINE> <INDENT> nodes = graph.nodes <NEW_LINE> <DEDENT> if not non_edges: <NEW_LINE> <INDENT> non_edges = set() <NEW_LINE> <DEDENT> idx_to_nodenum = dict(enumerate( subn for subn in graph if subn in nodes and g...
Add edges to `graph` between `nodes` based on distance. Adds edges to `graph` between nodes in `nodes`, but will never add an edge that is in `non_edges`, nor between H atoms. It will also not create edges where H atoms bridge separate residues. Residues are defined by the '_res_serial' attribute of nodes. Edges are a...
625941e44c3428357757c722
def test_dynamic(self): <NEW_LINE> <INDENT> tests = [self.sci.zeros, self.sci.ones, self.sci.plot] <NEW_LINE> for item in tests: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.assertEqual(repr(type(item)), "<type 'function'>") <NEW_LINE> <DEDENT> except AssertionError: <NEW_LINE> <INDENT> self.assertEqual(repr(type(...
Test the creation of a dynamic function
625941e4099cdd3c635f1055
def test_is_not_git_directory(self): <NEW_LINE> <INDENT> self.assertFalse(is_git_repo(mkdtemp()))
Detects a non-git initialized directory.
625941e42ae34c7f2600d52d
@pytest.fixture <NEW_LINE> def null_config(): <NEW_LINE> <INDENT> return LocalConfig.find(CONFIG_FILE_PATHS, env="null_driver")
Provides a :class:`LocalConfig` configured with suitable config file paths. .. seealso:: The :func:`integration_config_paths` fixture sets up the config files.
625941e4be383301e01b587a
def newClump(clumpDict): <NEW_LINE> <INDENT> nt = len(clumpDict['pos']) <NEW_LINE> if 'v' in clumpDict: <NEW_LINE> <INDENT> clumpDict['vel'] = clumpDict.pop('v') <NEW_LINE> <DEDENT> if 'm' in clumpDict: <NEW_LINE> <INDENT> clumpDict['mass'] = clumpDict.pop('m') <NEW_LINE> <DEDENT> if 'N' in clumpDict: <NEW_LINE> <INDEN...
Generates a new clump object from a clump dictionary (see clumps.blank_clump and clumps.build_clumps).
625941e40a366e3fb873ec1a
def get_type_name(self): <NEW_LINE> <INDENT> return "node_em_gmm"
returns the type name for this node emission object. This is used for setting the precomputed emissions matrix.
625941e467a9b606de4a82b3
def len(self): <NEW_LINE> <INDENT> return self.end - self.start
Get the length of the tract (in Morgans)
625941e482261d6c526ab8a2
def _format_paths(paths): <NEW_LINE> <INDENT> message = "" <NEW_LINE> for path in paths: <NEW_LINE> <INDENT> message += "{0}\n".format(path) <NEW_LINE> <DEDENT> return message[:-1]
Return paths at one new each
625941e423e79379d52ee95b
def __call__(self, inputs, state, scope='convLSTM'): <NEW_LINE> <INDENT> with tf.variable_scope(scope or type(self).__name__): <NEW_LINE> <INDENT> if self._state_is_tuple: <NEW_LINE> <INDENT> c, h = state <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> c, h = tf.split(state, 2, 3) <NEW_LINE> <DEDENT> concat = _conv_linea...
Long short-term memory cell (LSTM).
625941e41f5feb6acb0c4f46
def all(self, *args, **kwargs): <NEW_LINE> <INDENT> path_only = kwargs.pop('path_only', False) <NEW_LINE> class_only = kwargs.pop('class_only', False) <NEW_LINE> all_matches = [] <NEW_LINE> found_in_cache = True <NEW_LINE> for i in self._get_paths(): <NEW_LINE> <INDENT> all_matches.extend(glob.glob(os.path.join(i, "*.p...
instantiates all plugins with the same arguments
625941e41d351010ab855f17
def make_secure_val(value): <NEW_LINE> <INDENT> return '%s|%s' % (value, hmac.new(secret, value).hexdigest())
Create a secure value
625941e497e22403b379d398
def get_unread_message_nums(self): <NEW_LINE> <INDENT> from operation.models import UserMessage <NEW_LINE> messages = UserMessage.objects.filter(user=self.id).count() <NEW_LINE> return messages
获取用户未读消息个数
625941e416aa5153ce362874
def __str__(self, detail=0, width=79): <NEW_LINE> <INDENT> height = 1 if detail <= 0 else 8 * detail <NEW_LINE> tcode = '%i%s' % (self.count * int(self.dtype[0]), self.dtype[1]) <NEW_LINE> if self.name == str(self.code): <NEW_LINE> <INDENT> codename = self.name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> codename = '...
Return string containing information about tag.
625941e401c39578d7e75238
def __init__(self): <NEW_LINE> <INDENT> super(self.__class__, self).__init__('EliteTorrent') <NEW_LINE> self.url = 'http://www.elitetorrent.net' <NEW_LINE> self.urls = { 'base_url': self.url, 'search': urljoin(self.url, 'torrents.php') } <NEW_LINE> self.onlyspasearch = None <NEW_LINE> self.minseed = None <NEW_LINE> sel...
Initialize the class.
625941e4a4f1c619b28b042c
def __map_map_to_resource(self, geomap: dict, create_file: bool = True) -> Resource: <NEW_LINE> <INDENT> uuid: str = geomap['uuid'] <NEW_LINE> if create_file: <NEW_LINE> <INDENT> datafile: Datafile = Datafile() <NEW_LINE> file_data: dict = { 'uuid': uuid, 'site_url': self.service_url, 'detail_url': geomap['detail_url']...
Maps geonode map to Resource object :param geomap: dict to map to Resource :type geomap: dict :param create_file: define create file or not :type create_file: bool :return: Resource representing geonode map
625941e43617ad0b5ed682f3
def removeNumericType(*args, **kwargs): <NEW_LINE> <INDENT> pass
Removes the specified numeric type from the list of those accepted by the attribute.
625941e4004d5f362079a72d
def load_models(model_folder='.'): <NEW_LINE> <INDENT> generative_model_path = os.path.join(model_folder, 'gen.pt') <NEW_LINE> inference_network_path = os.path.join(model_folder, 'inf.pt') <NEW_LINE> pcfg_path_path = os.path.join(model_folder, 'pcfg_path.txt') <NEW_LINE> with open(pcfg_path_path) as f: <NEW_LINE> <INDE...
Returns: generative_model, inference network
625941e430c21e258bdfa89d
def similar_output(self): <NEW_LINE> <INDENT> self.buffer_out = copy.deepcopy(self.buffer_in) <NEW_LINE> self.buffer_out.update_pipeline_metadata(self) <NEW_LINE> self.buffer_out.update_pipeline_metadata(self.buffer_out)
Called in `__init__` when `buffer_out` has same form as `buffer_in`.
625941e41f037a2d8b9465fa
def set_xmargin(self, m): <NEW_LINE> <INDENT> if m < 0 or m > 1: <NEW_LINE> <INDENT> raise ValueError("margin must be in range 0 to 1") <NEW_LINE> <DEDENT> self._xmargin = m
Set padding of X data limits prior to autoscaling. *m* times the data interval will be added to each end of that interval before it is used in autoscaling. accepts: float in range 0 to 1
625941e4dc8b845886cb5933
def input_to_hidden(self, x): <NEW_LINE> <INDENT> return self.convE(x)
Get [hidden_rep]s (inputs to final fully-connected layers) for images [x].
625941e43eb6a72ae02ec8e4
def to_png(dfa, filename, **kwargs): <NEW_LINE> <INDENT> tmp_file = filename + ".tmp" <NEW_LINE> with open(tmp_file, "w") as file: <NEW_LINE> <INDENT> file.write(to_dot(dfa, **kwargs)) <NEW_LINE> <DEDENT> call(("dot -Tpng " + tmp_file + " -o " + filename).split(" ")) <NEW_LINE> call(("rm " + tmp_file).split(" "))
Create the PNG image corresponding to the representation of the specified DFA in a file. The automaton is converted in DOT format and the command dot is called in order to generate the PNG. @param_opt name the name of the automaton for the DOT file. ("Graph01") by default. @param_opt group if True, the trans...
625941e47b25080760e39854
def _decompose(self): <NEW_LINE> <INDENT> if self.is_empty: <NEW_LINE> <INDENT> coefs = {key: None for key in self.PARTS.keys()} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> coefs = dwtn(self.data, self.wavelet, self.mode, axes=self.axes) <NEW_LINE> <DEDENT> for key, data in coefs.items(): <NEW_LINE> <INDENT> self._cr...
See also -------- dwt2 : for 2D Discrete Wavelet Transform output coefficients.
625941e4de87d2750b860193
def __init__( self, generator_syncer_type: Type[BaseSyncer] = SimpleSyncer, **kwargs ): <NEW_LINE> <INDENT> self.generator_syncer = generator_syncer_type(**kwargs) <NEW_LINE> self.generator_id = self.generator_syncer.generator_id <NEW_LINE> self.EPOCH_START_MS = int(self.generator_syncer.epoch_start_ms * 1000) <NEW_LIN...
A Snowfall object that generates GUIDs. :param generator_syncer_type: Specify a IDSyncer class. An IDSyncer instance will be created to coordinate the generator_id and epoch_start across multiple Snowfall instances.
625941e4187af65679ca551d
def candy(self, ratings): <NEW_LINE> <INDENT> if len(ratings) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> givenCandy = [1] <NEW_LINE> for i in range(1, len(ratings)): <NEW_LINE> <INDENT> if ratings[i] > ratings[i - 1]: <NEW_LINE> <INDENT> givenCandy.append(givenCandy[-1] + 1) <NEW_LINE> <DEDENT> elif ratings...
:type ratings: List[int] :rtype: int
625941e430c21e258bdfa89e
def _parse(self, out): <NEW_LINE> <INDENT> source = None <NEW_LINE> self._uptodate = False <NEW_LINE> for row in out.split("\n"): <NEW_LINE> <INDENT> m = re.match(r"<target>(.*)</target>", row) <NEW_LINE> if m: <NEW_LINE> <INDENT> source = '../%s' % m.group(1) <NEW_LINE> break <NEW_LINE> <DEDENT> elif row.startswith('<...
Parse the uscan output return and update the object's properties @param out: uscan output @type out: string >>> u = Uscan('http://example.com/') >>> u._parse('<target>virt-viewer_0.4.0.orig.tar.gz</target>') >>> u.tarball '../virt-viewer_0.4.0.orig.tar.gz' >>> u.uptodate False >>> u._parse('') Traceback (most recent ...
625941e4d53ae8145f87a665
@pytest.mark.tier4 <NEW_LINE> def test_positive_synchronize_custom_product_future_sync_date(module_org): <NEW_LINE> <INDENT> delay = 2 * 60 <NEW_LINE> product = entities.Product(organization=module_org).create() <NEW_LINE> repo = entities.Repository(product=product).create() <NEW_LINE> with pytest.raises(AssertionError...
Create a sync plan with sync date in a future and sync one custom product with it automatically. :id: b70a0c50-7335-4285-b24c-edfc1187f034 :expectedresults: Product is synchronized successfully. :CaseLevel: System :BZ: 1655595, 1695733
625941e4d4950a0f3b08c746
def to_html(self): <NEW_LINE> <INDENT> self.html = [] <NEW_LINE> self.html.append(DOCUMENT_HEADER) <NEW_LINE> for qp in self.question_pages: <NEW_LINE> <INDENT> self.html.append(qp.to_html(self.question_limit)) <NEW_LINE> self.html.append(INSTRUCTIONS) <NEW_LINE> self.html.append(PAGE_BREAK) <NEW_LINE> <DEDENT> return(...
Convert the form document to HTML.
625941e42c8b7c6e89b35bbb
def config(path='/etc/butter/kvm'): <NEW_LINE> <INDENT> opts = {'images': '/srv/vm/images', 'instances': '/srv/vm/instances', 'local_path': '/mnt/local/vm', 'salt_pki': '/etc/salt/pki', 'storage_type': 'local', 'distro': 'arch', 'network': {'br0', 'eth0'}, 'graphics': 'vnc', 'udev': '/etc/udev/rules.d/70-persistent-net...
Load up the configuration for butter kvm
625941e42eb69b55b151ccb2
def test_create_album_view_has_correct_fields(self): <NEW_LINE> <INDENT> user = User.objects.all()[0] <NEW_LINE> self.client.force_login(user) <NEW_LINE> response = self.client.get(reverse('album_add')) <NEW_LINE> html = soup(response.content, "html.parser") <NEW_LINE> field = html.findAll('input', {'name': 'title'}) <...
Test create album view has correct fields for adding new.
625941e47cff6e4e81117d83
def pip_kwargs(config_dir: Optional[str]) -> Dict[str, Any]: <NEW_LINE> <INDENT> kwargs = { 'constraints': os.path.join(os.path.dirname(__file__), CONSTRAINT_FILE) } <NEW_LINE> if not (config_dir is None or pkg_util.is_virtual_env()): <NEW_LINE> <INDENT> kwargs['target'] = os.path.join(config_dir, 'deps') <NEW_LINE> <D...
Return keyword arguments for PIP install.
625941e4b830903b967e9d04
def minDistance(self, word1, word2): <NEW_LINE> <INDENT> m = len(word1) <NEW_LINE> n = len(word2) <NEW_LINE> table = [[0] * (n + 1) for _ in range(m + 1)] <NEW_LINE> for i in range(m + 1): <NEW_LINE> <INDENT> table[i][0] = i <NEW_LINE> <DEDENT> for j in range(n + 1): <NEW_LINE> <INDENT> table[0][j] = j <NEW_LINE> <DEDE...
Dynamic programming solution
625941e4fb3f5b602dac3a95
def csvReadWrite(argv): <NEW_LINE> <INDENT> li = [] <NEW_LINE> with open(argv[0], 'r') as csvfile: <NEW_LINE> <INDENT> dataReader = csv.reader(csvfile) <NEW_LINE> for row in dataReader: <NEW_LINE> <INDENT> li.append(row) <NEW_LINE> <DEDENT> <DEDENT> myArray = np.array(li) <NEW_LINE> print(myArray) <NEW_LINE> print(myAr...
Read in data from a CSV file and compute discriptive statistics. Write a CSV file from a 2D array.
625941e44e696a04525c984a
def _any_fnmatch(name, patterns): <NEW_LINE> <INDENT> return any(fnmatch(name, pattern) for pattern in patterns)
Returns True if any element in the patterns iterable fnmatches name.
625941e4cb5e8a47e48b7ea1
def sniffer_on(self, channel=None): <NEW_LINE> <INDENT> self.capabilities.require(KBCapabilities.SNIFF) <NEW_LINE> self.handle.RF_promiscuity(1) <NEW_LINE> self.handle.RF_autocrc(0) <NEW_LINE> if channel != None: <NEW_LINE> <INDENT> self.set_channel(channel) <NEW_LINE> <DEDENT> self.handle.CC_RFST_RX() <NEW_LINE> self....
Turns the sniffer on such that pnext() will start returning observed data. Will set the command mode to Air Capture if it is not already set. @type channel: Integer @param channel: Sets the channel, optional @rtype: None
625941e4d8ef3951e324393b
def collided_with(self, obj): <NEW_LINE> <INDENT> pass
Event: contact with our tank shell
625941e456b00c62f0f14a59
def OnExitPage(self, event=None): <NEW_LINE> <INDENT> if event.GetDirection(): <NEW_LINE> <INDENT> self.SetNext(self.drawsampleunitspage) <NEW_LINE> self.SetPrev(self.samplingareapage)
Function during exiting
625941e429b78933be1e5aa4
def test_arq_bird_tg_md(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.blackbox_method_int('arq_bird_tg_md') <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return
Integration test for trex.arq_bird_tg_md
625941e4a219f33f34628d62
def generateMatrix(self, n): <NEW_LINE> <INDENT> if n <= 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> result = [[0] * n for _ in range(n)] <NEW_LINE> start_row, end_row, start_col, end_col = 0, n-1, 0, n-1 <NEW_LINE> number = 1 <NEW_LINE> while start_row <= end_row and start_col <= end_col: <NEW_LINE> <INDENT> ...
:type n: int :rtype: List[List[int]]
625941e4b7558d58953c5309
def is_turbo_boost_enabled(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if os.path.exists(_TURBO_BOOST_FILE): <NEW_LINE> <INDENT> boost_enabled = int(util.read_file(_TURBO_BOOST_FILE)) <NEW_LINE> if not (0 <= boost_enabled <= 1): <NEW_LINE> <INDENT> raise ValueError( "Invalid value {} for turbo boost activation".for...
Check whether Turbo Boost (scaling CPU frequency beyond nominal frequency) is active on this system. @return: A bool, or None if Turbo Boost is not supported.
625941e4e64d504609d74c3d
def point_algebra_comptable(): <NEW_LINE> <INDENT> point_algebra_ct = dict() <NEW_LINE> point_algebra_ct["< <"] = frozenset( [ '<' ] ) <NEW_LINE> point_algebra_ct["< ="] = frozenset( [ '<' ] ) <NEW_LINE> point_algebra_ct["< >"] = frozenset( [ '<', '=', '>' ] ) <NEW_LINE> point_algebra_ct["= <"] = frozenset( [ '<' ] ) <...
Return composition table of the point algebra.
625941e4e1aae11d1e74a0b8
def search(self, query, repository='All Repositories', applicable=False, upgradable=False): <NEW_LINE> <INDENT> view = self.navigate_to(self, 'All') <NEW_LINE> return view.search( query, repository=repository, applicable=applicable, upgradable=upgradable )
Search for package in the indicated repository :param str query: search query to type into search field. E.g. ``name = "bar"``. :param str repository: repository name to select when searching for the package. :param bool applicable: To show only applicable packages. :param bool upgradable: To show only upgrada...
625941e4293b9510aa2c368f
def __init__(self, appname=None): <NEW_LINE> <INDENT> self.appname = appname
Args: appname: Not required - it is added automatically by :class:`.Registry`, and used by :meth:`.__str__`` for easier debugging / prettier output.
625941e426068e7796caf0e2
def remove(name): <NEW_LINE> <INDENT> run(["remove", name])
`git remote rm name`
625941e4ad47b63b2c50a37c
def _get_status_id(self, status_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> r = self.s.get('{0}/{1}/transitions'.format(self.rest_url, self.ticket_id)) <NEW_LINE> logger.debug("Get status id: status code: {0}".format(r.status_code)) <NEW_LINE> r.raise_for_status() <NEW_LINE> <DEDENT> except requests.RequestExce...
Gets status id corresponding to status name. :param status_name: The name of the status. :return: status_id: The id of the status.
625941e42ae34c7f2600d52e
def capitalize(word): <NEW_LINE> <INDENT> capitalized_word = word.capitalize() <NEW_LINE> return capitalized_word
Return the supplied word capitalized.
625941e43eb6a72ae02ec8e5
def _create_or_update_secret(self, secret_path, payload): <NEW_LINE> <INDENT> checked_secret_path = self._secret_path_validator(secret_path) <NEW_LINE> if not checked_secret_path: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> secret_path = checked_secret_path <NEW_LINE> <DEDENT> checked...
Internal function for creating or updating secret by given path and payload. It also checks if given args are correct, and everything is goes like it should be. >: secret path as string >: payload as dict{"data":{"key":"value"}, {"key":"value"}} <T: returns true if action done <F: returns false if not, or some error oc...
625941e4fbf16365ca6f65c9
def random_point(self): <NEW_LINE> <INDENT> from random import randint <NEW_LINE> lower, upper = -2**32 - 1, 2**32 <NEW_LINE> if self.slope is S.Infinity: <NEW_LINE> <INDENT> if isinstance(self, Ray): <NEW_LINE> <INDENT> if self.ydirection is S.Infinity: <NEW_LINE> <INDENT> lower = self.p1.y <NEW_LINE> <DEDENT> else: <...
A random point on a LinearEntity. Returns ======= point : Point See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(5, 3) >>> l1 = Line(p1, p2) >>> p3 = l1.random_point() >>> # random point - don't know its coords in advance >>> p3 # doc...
625941e44e696a04525c984b
def test_can_view_own_profile(self): <NEW_LINE> <INDENT> response = self.client.get(reverse('self_profile')) <NEW_LINE> self.assertEqual(200, response.status_code) <NEW_LINE> self.assertContains(response, 'Joe') <NEW_LINE> self.assertContains(response, 'Bill') <NEW_LINE> self.assertContains(response, 'some_user')
Test that the user can view their own profile when they are logged in
625941e46aa9bd52df0371a4
def validate_enum(self, x, fieldname, schema, path, options=None): <NEW_LINE> <INDENT> value = x.get(fieldname) <NEW_LINE> if value is not None: <NEW_LINE> <INDENT> if callable(options): <NEW_LINE> <INDENT> options = options(x) <NEW_LINE> <DEDENT> if not isinstance(options, Container): <NEW_LINE> <INDENT> raise SchemaE...
Validates that the value of the field is equal to one of the specified option values
625941e43c8af77a43ae3ba2
def train(self, train_iter, epoch, report_func=None): <NEW_LINE> <INDENT> self.model.train() <NEW_LINE> total_stats = Statistics(loss=0, n_sample=0, n_correct=0, scores=[], pos_neg_num=10) <NEW_LINE> report_stats = Statistics(loss=0, n_sample=0, n_correct=0, scores=[], pos_neg_num=10) <NEW_LINE> for sub_dataset in trai...
Train next epoch. Args: train_iter: training data iterator epoch(int): the epoch number report_func(fn): function for logging Returns: stats (:obj:`onmt.Statistics`): epoch loss statistics
625941e4a8ecb033257d34c9
def __init__(self): <NEW_LINE> <INDENT> self._consumer = consumer.Consumer() <NEW_LINE> queue_class = utils.class_import_from_path(settings.QUEUE_CLASS) <NEW_LINE> q_info = queue_info.QueueInfo( config_file=settings.QUEUE_CONFIG, sqs_talk=self._consumer, queue_cls=queue_class) <NEW_LINE> queue_selector_class = utils.cl...
Initialize a worker instance.
625941e4442bda511e8be810
def listen(self, client): <NEW_LINE> <INDENT> connection, client_address = client <NEW_LINE> while self.running: <NEW_LINE> <INDENT> info = "" <NEW_LINE> try: <NEW_LINE> <INDENT> data = connection.recv() <NEW_LINE> info = data.decode("utf-8") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if l...
Manages a connection's input forwards it into the input queue :param client: :return:
625941e4711fe17d82542760
def acquiresingle(self): <NEW_LINE> <INDENT> self.write(':DIG')
Run single shot acquisition.
625941e43539df3088e2e749
def _add_header_func(self, row, before, unused_user_data): <NEW_LINE> <INDENT> current_type = PluginManager.get_plugin_type(row.plugin_info) <NEW_LINE> if before is not None: <NEW_LINE> <INDENT> previous_type = PluginManager.get_plugin_type(before.plugin_info) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> previous_type...
Adds a header for a new section in the model.
625941e4eab8aa0e5d26df57
@generic <NEW_LINE> def intercept_center(A, B): <NEW_LINE> <INDENT> raise NotImplementedError
Return the center point of the intercept between A and B.
625941e4090684286d50f0e9
def expand_raster_values(rast_in=None,XY=None,nfilt=3, ncell_pad=50,extrapolate_values=True, nan_val = 0): <NEW_LINE> <INDENT> if isinstance(rast_in,str): <NEW_LINE> <INDENT> X,Y,rast_in = read_griddata(rast_in) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> X,Y = XY <NEW_LINE> <DEDENT> rast_in_temp = rast_in.copy() <NE...
Assign missing value cells in raster to nearby values.
625941e45fc7496912cc3d7b
def load_multi_dataset( datasets_config: List[Dict[str, Union[int, str, Sequence[str]]]], name_to_features: Dict[str, Any], preprocess_fn: Callable[[Dict[str, tf.Tensor]], Dict[str, tf.Tensor]], collater_fn: Callable[[Dict[str, tf.Tensor]], Dict[str, tf.Tensor]], is_training: bool, per_device_batch_size: int, local_dev...
Create TF dataset from different data sources. Args: datasets_config: a list of datasets to load. name_to_features: features to decode from a record in binary format. preprocess_fn: performs preprocessing on examples. collater_fn: performs preprocessing on the whole batch. is_training: if true, shuffles pe...
625941e4b5575c28eb68e402
def chore_delete(self, chore_id): <NEW_LINE> <INDENT> rows = self.mysql.session.query(nandy.store.mysql.Chore).filter_by(chore_id=chore_id).delete() <NEW_LINE> self.mysql.session.commit() <NEW_LINE> return rows
Deletes Chore based on id
625941e45510c4643540f7d8
def _encode_color_grb(c): <NEW_LINE> <INDENT> return _byte_lookup[int(c[1] * brightness)] + _byte_lookup[int(c[0] * brightness)] + _byte_lookup[int(c[2] * brightness)]
Encode an RGB tuple into NeoPixel GRB 24 byte SPI bit stream.
625941e4a934411ee3751a92
def get_info(self): <NEW_LINE> <INDENT> return {"path":self.path, "config":self.config}
Return a dictionary representing the information about this image.
625941e4956e5f7376d7126a
def to_quadratic_program(self) -> QuadraticProgram: <NEW_LINE> <INDENT> mdl = Model(name="Number partitioning") <NEW_LINE> x = {i: mdl.binary_var(name=f"x_{i}") for i in range(len(self._number_set))} <NEW_LINE> mdl.add_constraint( mdl.sum(num * (-2 * x[i] + 1) for i, num in enumerate(self._number_set)) == 0 ) <NEW_LINE...
Convert a number partitioning problem instance into a :class:`~qiskit_optimization.problems.QuadraticProgram` Returns: The :class:`~qiskit_optimization.problems.QuadraticProgram` created from the number partitioning problem instance.
625941e432920d7e50b285d1
def setUp(self): <NEW_LINE> <INDENT> slicer.mrmlScene.Clear(0)
Do whatever is needed to reset the state - typically a scene clear will be enough.
625941e4adb09d7d5db6cb8b
def getSliderValues(self): <NEW_LINE> <INDENT> values = dict() <NEW_LINE> for slider in self.sliders: <NEW_LINE> <INDENT> values[slider] = cv2.getTrackbarPos(slider, "Settings") <NEW_LINE> <DEDENT> return values
Retrieve values for all registered sliders Returns dict slider_name -> value
625941e4d268445f265b526c
def teardown(self, wait=False): <NEW_LINE> <INDENT> self.__teardown_event.set() <NEW_LINE> if wait: <NEW_LINE> <INDENT> self.__mustdraw_isdone_event.set() <NEW_LINE> self.__step_lock.acquire() <NEW_LINE> self.__step_lock.release()
Makes sure we can quit the world, ie if no other thread is working on it.
625941e491f36d47f21ac8f4
def model_test(inputs, batch_size, n_his, n_pred, inf_mode, load_path='./output/models/'): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> model_path = tf.train.get_checkpoint_state(load_path).model_checkpoint_path <NEW_LINE> test_graph = tf.Graph() <NEW_LINE> with test_graph.as_default(): <NEW_LINE> <INDENT> s...
Load and test saved model from the checkpoint. :param inputs: instance of class Dataset, data source for test. :param batch_size: int, the size of batch. :param n_his: int, the length of historical records for training. :param n_pred: int, the length of prediction. :param inf_mode: str, test mode - 'merge / multi-step ...
625941e4fbf16365ca6f65ca
def refresh_window(self): <NEW_LINE> <INDENT> nocursor = curses.curs_set(0) <NEW_LINE> self.current_tab().state = 'current' <NEW_LINE> self.current_tab().refresh() <NEW_LINE> self.doupdate() <NEW_LINE> curses.curs_set(nocursor)
Refresh everything
625941e47b180e01f3dc4bf3
def UploadFile(self, request_iterator, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
Upload files to the storage
625941e4ac7a0e7691ed44c3
def denseblock(x, concat_axis, nb_layers, nb_filter, growth_rate, dropout_rate=None, weight_decay=1E-4): <NEW_LINE> <INDENT> list_feat = [x] <NEW_LINE> for i in range(nb_layers): <NEW_LINE> <INDENT> x = conv_factory(x, concat_axis, growth_rate, dropout_rate, weight_decay) <NEW_LINE> list_feat.append(x) <NEW_LINE> x = C...
Build a denseblock where the output of each conv_factory is fed to subsequent ones :param x: keras model :param concat_axis: int -- index of contatenate axis :param nb_layers: int -- the number of layers of conv_ factory to append to the model. :param nb_filter: int -- number of filters :param drop...
625941e44e4d5625662d47d0
def get_polybius_decoded_letters(key: str, letter_pair: str) -> str: <NEW_LINE> <INDENT> row = "adfgvx".find(letter_pair[0]) <NEW_LINE> col = "adfgvx".find(letter_pair[1]) <NEW_LINE> return key[(6 * row + col) % 36]
>>> get_polybius_decoded_letters('7yvorqhkdbmp12g90n3z8tcfws6uexj4l5ai', 'xv') 'a'
625941e415baa723493c4376
def set_create_logfile(self, flag): <NEW_LINE> <INDENT> self.should_create_logfile = flag <NEW_LINE> if flag: <NEW_LINE> <INDENT> self.enable_logfile()
Create Logfile Setter
625941e491f36d47f21ac8f5
def noisy(image,noise_typ): <NEW_LINE> <INDENT> if noise_typ == "gauss": <NEW_LINE> <INDENT> row,col,ch= image.shape <NEW_LINE> mean = 0 <NEW_LINE> var = 0.1 <NEW_LINE> sigma = var**0.5 <NEW_LINE> gauss = np.random.normal(mean,sigma,(row,col,ch)) <NEW_LINE> gauss = gauss.reshape(row,col,ch) <NEW_LINE> noisy = image + g...
Parameters ---------- image : ndarray Input image data. Will be converted to float. mode : str One of the following strings, selecting the type of noise to add: 'gauss' Gaussian-distributed additive noise. 'poisson' Poisson-distributed noise generated from the data. 's&p' Replaces rando...
625941e410dbd63aa1bd2fa0