code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def __download( self, symbols, request_limit = True, in_memory = True, **kwargs): <NEW_LINE> <INDENT> download_result = {} <NEW_LINE> symbols = symbols if isinstance(symbols, list) else [symbols] <NEW_LINE> start_time = time() <NEW_LINE> errors = 0 <NEW_LINE> for i, symbol in enumerate(symbols): <NEW_LINE> <INDENT> print("Downloading {0}/{1}...".format(i + 1, len(symbols)), "\r", end = "") <NEW_LINE> start_time_request = time() <NEW_LINE> data = self.alpha_vantage(symbol, **kwargs) <NEW_LINE> if (data == None): <NEW_LINE> <INDENT> errors += 1 <NEW_LINE> <DEDENT> elif(in_memory): <NEW_LINE> <INDENT> download_result[symbol] = data <NEW_LINE> <DEDENT> if request_limit and len(symbols) >= 5 and i < len(symbols) - 1: <NEW_LINE> <INDENT> self.__api_request_delay(start_time_request, request_delay) <NEW_LINE> <DEDENT> <DEDENT> print("Download complete in {0}!" .format(timedelta(seconds = time() - start_time))) <NEW_LINE> if errors > 0: <NEW_LINE> <INDENT> print("{0} / {1} symbols errored.".format(errors, len(symbols))) <NEW_LINE> <DEDENT> if(not in_memory): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> return download_result
Download interface.
625941c301c39578d7e74df5
def stacksize(since=0.0): <NEW_LINE> <INDENT> return _VmB('VmStk:') - since
Return stack size in bytes.
625941c37047854f462a13c6
def mean_rrank_at_k_batch(train_data, vad_data, test_data, Et, Eb, user_idx, k=5): <NEW_LINE> <INDENT> batch_users = user_idx.stop - user_idx.start <NEW_LINE> X_pred = _make_prediction(train_data, vad_data, Et, Eb, user_idx, batch_users) <NEW_LINE> all_rrank = 1. / (np.argsort(np.argsort(-X_pred, axis=1), axis=1) + 1) <NEW_LINE> X_true_binary = (test_data[user_idx] > 0).toarray() <NEW_LINE> test_rrank = X_true_binary * all_rrank <NEW_LINE> top_k = bn.partsort(-test_rrank, k, axis=1) <NEW_LINE> return -top_k[:, :k].mean(axis=1)
mean reciprocal rank@k: For each user, make predictions and rank for all the items. Then calculate the mean reciprocal rank for the top K that are in the held-out test set.
625941c37cff6e4e81117940
def ListItemsInFolder(self, path='/', types_to_fetch=EntryType.FILES_AND_FOLDERS, include_dates=False): <NEW_LINE> <INDENT> items = [] <NEW_LINE> if path[-1] != '/': <NEW_LINE> <INDENT> path += '/' <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> info = self.zip_file.getinfo(path[1:]) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> log.error(f'Folder {path} not present in archive') <NEW_LINE> return items <NEW_LINE> <DEDENT> dir = self._ListFilesInZipFolder(path) <NEW_LINE> for entry in dir: <NEW_LINE> <INDENT> info = self.zip_file.getinfo(entry[1:]) <NEW_LINE> entry_type = EntryType.FOLDERS if (entry[-1] == '/') else EntryType.FILES <NEW_LINE> if entry[-1] == '/': <NEW_LINE> <INDENT> name = os.path.basename(entry[0:-1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = os.path.basename(entry) <NEW_LINE> <DEDENT> item = { 'name':name, 'type':entry_type, 'size':info.file_size} <NEW_LINE> if include_dates: <NEW_LINE> <INDENT> item['dates'] = self.GetFileMACTimes(entry, info) <NEW_LINE> <DEDENT> if types_to_fetch == EntryType.FILES_AND_FOLDERS: <NEW_LINE> <INDENT> items.append( item ) <NEW_LINE> <DEDENT> elif types_to_fetch == EntryType.FILES and entry_type == EntryType.FILES: <NEW_LINE> <INDENT> items.append( item ) <NEW_LINE> <DEDENT> elif types_to_fetch == EntryType.FOLDERS and entry_type == EntryType.FOLDERS: <NEW_LINE> <INDENT> items.append( item ) <NEW_LINE> <DEDENT> <DEDENT> return items
Returns a list of files and/or folders in a list Format of list = [ {'name':'got.txt', 'type':EntryType.FILES, 'size':10}, .. ] 'path' should be linux style using forward-slash like '/var/db/xxyy/file.tdc' and starting at root /
625941c34f88993c3716c023
def close_ssh(self): <NEW_LINE> <INDENT> self.client.close() <NEW_LINE> logging.debug('## {} - {}.close_ssh()'.format(__name__, self))
Closes the SSH connection to the target server.
625941c39b70327d1c4e0d8e
def setAmplitude(self, amplitude): <NEW_LINE> <INDENT> self.arcradius = amplitude <NEW_LINE> return self
Set the size of the oscillation.
625941c331939e2706e4ce26
def _init_unit_combo(self, combo_box): <NEW_LINE> <INDENT> store = Gtk.ListStore(str) <NEW_LINE> combo_box.set_model(store) <NEW_LINE> for label in (x.label for x in gaupol.length_units): <NEW_LINE> <INDENT> store.append((label,)) <NEW_LINE> <DEDENT> renderer = Gtk.CellRendererText() <NEW_LINE> combo_box.pack_start(renderer, expand=True) <NEW_LINE> combo_box.add_attribute(renderer, "text", 0)
Initialize line length unit `combo_box`.
625941c363b5f9789fde709f
def commit(*args): <NEW_LINE> <INDENT> cmd = ['git', 'commit'] + list(args) <NEW_LINE> return _exec(cmd)
Performs `git commit`.
625941c321a7993f00bc7ca6
def test_check_for_export_with_some_volume_missing(self): <NEW_LINE> <INDENT> volume_id_list = self._attach_volume() <NEW_LINE> instance_uuid = '12345678-1234-5678-1234-567812345678' <NEW_LINE> tid = db.volume_get_iscsi_target_num(self.context, volume_id_list[0]) <NEW_LINE> self.mox.StubOutWithMock(self.volume.driver.tgtadm, 'show_target') <NEW_LINE> self.volume.driver.tgtadm.show_target(tid).AndRaise( exception.ProcessExecutionError()) <NEW_LINE> self.mox.ReplayAll() <NEW_LINE> self.assertRaises(exception.ProcessExecutionError, self.volume.check_for_export, self.context, instance_uuid) <NEW_LINE> self.mox.UnsetStubs() <NEW_LINE> self._detach_volume(volume_id_list)
Output a warning message when some volumes are not recognied by ietd.
625941c36aa9bd52df036d5d
@pytest.fixture() <NEW_LINE> def insert_parent_task( repo: Repository, ) -> Tuple[RecurrentTask, Task]: <NEW_LINE> <INDENT> parent_task = factories.RecurrentTaskFactory.create(state="backlog") <NEW_LINE> child_task = parent_task.breed_children() <NEW_LINE> repo.add(parent_task) <NEW_LINE> repo.add(child_task) <NEW_LINE> repo.commit() <NEW_LINE> return parent_task, child_task
Insert a RecurrentTask and it's children Task in the FakeRepository.
625941c3187af65679ca50d8
def compute_autocorr(precip,model_dict): <NEW_LINE> <INDENT> print('---> Computing auto-correlations') <NEW_LINE> nlon=len(precip.coord('longitude').points) <NEW_LINE> nlat=len(precip.coord('latitude').points) <NEW_LINE> autocorr_length = model_dict['autocorr_length'] <NEW_LINE> max_box_distance,max_boxes,max_timesteps = parameters() <NEW_LINE> autocorr_nt = np.int(autocorr_length//(model_dict['dt']))+1 <NEW_LINE> time_max = autocorr_nt <NEW_LINE> time_correlations = np.zeros(max_timesteps) <NEW_LINE> print('----> Info: Computing auto-correlations for '+str(autocorr_nt)+' lags.') <NEW_LINE> if autocorr_nt > max_timesteps: <NEW_LINE> <INDENT> raise Exception('Error: Number of lags for auto-correlation exceeds maximum ('+str(max_timesteps)+'). Increase parameter max_timesteps in code or reduce autocorrelation length.') <NEW_LINE> <DEDENT> for lon in range(nlon): <NEW_LINE> <INDENT> for lat in range(nlat): <NEW_LINE> <INDENT> for lag in range(autocorr_nt): <NEW_LINE> <INDENT> this_precip = precip.data[:,lat,lon] <NEW_LINE> time_correlations[lag] = time_correlations[lag] + np.corrcoef(this_precip,np.roll(this_precip,lag,0))[1,0] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> time_correlations = time_correlations / (nlon*nlat) <NEW_LINE> return(time_correlations,time_max)
Compute the lagged auto-correlation of precipitatio across all points in the analysis domain. Arguments: * precip: An iris cube of precipitation to analyse * model_dict: The dictionary of information about this dataset Returns: * time_correlations (max_timesteps): Composite lagged auto-correlations across all points * time_max (max_timesteps): The maximum valid lag in the time_correlation array (can be used as a subscript).
625941c323e79379d52ee520
def fit_transform(self, raw_inputs): <NEW_LINE> <INDENT> return self.fit(raw_inputs).transform(raw_inputs)
Fit to `raw_inputs`, then transform `raw_inputs`.
625941c373bcbd0ca4b2c030
def write_to_file(correct_tweets, path): <NEW_LINE> <INDENT> with open(path, 'w+') as outfile: <NEW_LINE> <INDENT> for l_tweet in correct_tweets: <NEW_LINE> <INDENT> json.dump(l_tweet, outfile) <NEW_LINE> outfile.write('\n')
Write labeled tweets to a file
625941c307f4c71912b1143b
def __init__( self, face: Face, face_basis: Basis, face_reference_frame_transformation_matrix: Mat, displacement: List[Callable], ): <NEW_LINE> <INDENT> displacement_vector = Integration.get_face_pressure_vector_in_face( face, face_basis, face_reference_frame_transformation_matrix, displacement ) <NEW_LINE> self.displacement_vector = displacement_vector
================================================================================================================ Class : ================================================================================================================ ================================================================================================================ Parameters : ================================================================================================================ ================================================================================================================ Attributes : ================================================================================================================
625941c34527f215b584c413
def __init__(self, keyword_list): <NEW_LINE> <INDENT> self.keywords = keyword_list <NEW_LINE> logging.Filter.__init__(self)
Acquires a list of keywords to check records with
625941c321bff66bcd68490f
def white_code_words(language_id: str) -> Dict[str, List[str]]: <NEW_LINE> <INDENT> assert language_id is not None <NEW_LINE> assert language_id.islower() <NEW_LINE> return _LANGUAGE_TO_WHITE_WORDS_MAP.get(language_id, set())
Words that do not count as code if it is the only word in a line.
625941c3b830903b967e98c7
def __processSSI(self, txt, filename, root): <NEW_LINE> <INDENT> if not filename: <NEW_LINE> <INDENT> return txt <NEW_LINE> <DEDENT> incRe = re.compile( r"""<!--#include[ \t]+(virtual|file)=[\"']([^\"']+)[\"']\s*-->""", re.IGNORECASE) <NEW_LINE> baseDir = os.path.dirname(os.path.abspath(filename)) <NEW_LINE> docRoot = root if root != "" else baseDir <NEW_LINE> while True: <NEW_LINE> <INDENT> incMatch = incRe.search(txt) <NEW_LINE> if incMatch is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if incMatch.group(1) == "virtual": <NEW_LINE> <INDENT> incFile = Utilities.normjoinpath(docRoot, incMatch.group(2)) <NEW_LINE> <DEDENT> elif incMatch.group(1) == "file": <NEW_LINE> <INDENT> incFile = Utilities.normjoinpath(baseDir, incMatch.group(2)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> incFile = "" <NEW_LINE> <DEDENT> if os.path.exists(incFile): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> f = open(incFile, "r") <NEW_LINE> incTxt = f.read() <NEW_LINE> f.close() <NEW_LINE> <DEDENT> except (IOError, OSError): <NEW_LINE> <INDENT> incTxt = "" <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> incTxt = "" <NEW_LINE> <DEDENT> txt = txt[:incMatch.start(0)] + incTxt + txt[incMatch.end(0):] <NEW_LINE> <DEDENT> return txt
Private method to process the given text for SSI statements. Note: Only a limited subset of SSI statements are supported. @param txt text to be processed (string) @param filename name of the file associated with the given text (string) @param root directory of the document root (string) @return processed HTML (string)
625941c37b180e01f3dc47bb
def get_status(self): <NEW_LINE> <INDENT> return GetStatus(*self.ipcon.send_request(self, BrickletGPS.FUNCTION_GET_STATUS, (), '', 'B B B'))
Returns the current fix status, the number of satellites that are in view and the number of satellites that are currently used. Possible fix status values can be: .. csv-table:: :header: "Value", "Description" :widths: 10, 100 "1", "No Fix, :func:`GetCoordinates`, :func:`GetAltitude` and :func:`GetMotion` return invalid data" "2", "2D Fix, only :func:`GetCoordinates` and :func:`GetMotion` return valid data" "3", "3D Fix, :func:`GetCoordinates`, :func:`GetAltitude` and :func:`GetMotion` return valid data" There is also a :ref:`blue LED <gps_bricklet_fix_led>` on the Bricklet that indicates the fix status.
625941c392d797404e304144
def solo(*args, **kwargs): <NEW_LINE> <INDENT> args += ('chef-solo',) <NEW_LINE> return __exec_cmd(*args, **kwargs)
Execute a chef solo run and return a dict with the stderr, stdout, return code, etc. CLI Example: .. code-block:: bash salt '*' chef.solo config=/etc/chef/solo.rb -l debug
625941c3f548e778e58cd537
def add_commentor(self, lang, *args, **kwargs): <NEW_LINE> <INDENT> commentor_cls = kwargs.get('commentor_cls', Commentor) <NEW_LINE> if lang not in self.__registry: <NEW_LINE> <INDENT> self.set_commentor(lang, *args, commentor_cls=commentor_cls)
check if a commentor exists and call set_commentor if necessary
625941c376e4537e8c35162b
def activate(self, X): <NEW_LINE> <INDENT> X = self._transform(X, fit=False) <NEW_LINE> return self.Activation(X)
Activates NN on particular dataset :param numpy.array X: of shape [n_samples, n_features] :return: numpy.array with results of shape [n_samples]
625941c356b00c62f0f14613
def _oauth2_callback(self): <NEW_LINE> <INDENT> code = self.request.get('code', None) <NEW_LINE> logging.info('code is: %s' % code) <NEW_LINE> error = self.request.get('error', None) <NEW_LINE> callback_url = self._callback_uri() <NEW_LINE> access_token_url = URLS[1] <NEW_LINE> consumer_key, consumer_secret = self._get_consumer_info() <NEW_LINE> if error: <NEW_LINE> <INDENT> raise Exception(error) <NEW_LINE> <DEDENT> payload = { 'code': code, 'client_id': consumer_key, 'client_secret': consumer_secret, 'redirect_uri': callback_url, 'grant_type': 'authorization_code' } <NEW_LINE> resp = urlfetch.fetch( url=access_token_url, payload=urlencode(payload), method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'} ) <NEW_LINE> auth_info = self._json_parser(resp.content) <NEW_LINE> logging.info('auth_info is %s' % auth_info) <NEW_LINE> uid = self._get_user_id(auth_info) <NEW_LINE> user_data = getattr(self, '_get_weibo_user_info')(auth_info, uid=uid) <NEW_LINE> logging.info('user_data is %s' % user_data) <NEW_LINE> followers = getattr(self, '_get_followers')(auth_info, uid=uid) <NEW_LINE> logging.info('followers are %s' % followers) <NEW_LINE> self._on_sign_in(auth_info, user_data) <NEW_LINE> self._list_followers(followers)
Step 2 of OAuth 2.0, whenever the user accepts or denies access.
625941c330bbd722463cbd7f
def test_composition_all_3(): <NEW_LINE> <INDENT> add1 = Add1() <NEW_LINE> sum_all = list_x.All(actions=[add1, add1, list_x.Success(), add1, add1]).execute( rez=Rez(result=10.1) ) <NEW_LINE> assert sum_all.result == 14.1
Show that introduction of Success does not impact the result.
625941c3379a373c97cfaaff
def get_pair_dict(path, t, user=None, haploscores=False, nomask=False, merge_len=-1): <NEW_LINE> <INDENT> s_list = read_matchfile(path, haploscores) <NEW_LINE> pair_dict = {} <NEW_LINE> for seg in s_list: <NEW_LINE> <INDENT> assert isinstance(seg, SharedSegment) <NEW_LINE> assert seg.lengthUnit == "cM" <NEW_LINE> if seg.length < t: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if user and seg.indivID1 != user and seg.indivID2 != user: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> pair_id = seg.indivID1 <NEW_LINE> if seg.indivID1 < seg.indivID2: <NEW_LINE> <INDENT> pair_id += ":" + seg.indivID2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pair_id = seg.indivID2 + ":" + pair_id <NEW_LINE> <DEDENT> if pair_dict.get(pair_id): <NEW_LINE> <INDENT> pair_dict[pair_id].append(seg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pair_dict[pair_id] = [seg] <NEW_LINE> <DEDENT> <DEDENT> remove = [] <NEW_LINE> for pair, segs in pair_dict.items(): <NEW_LINE> <INDENT> if merge_len > 0: <NEW_LINE> <INDENT> segs = merge_segments(segs, merge_len) <NEW_LINE> pair_dict[pair] = segs <NEW_LINE> <DEDENT> if not nomask: <NEW_LINE> <INDENT> segs = mask_input_segs(segs, t) <NEW_LINE> pair_dict[pair] = segs <NEW_LINE> <DEDENT> segs.sort() <NEW_LINE> if len(segs) == 0: <NEW_LINE> <INDENT> remove.append(pair) <NEW_LINE> <DEDENT> <DEDENT> for pair in remove: <NEW_LINE> <INDENT> del pair_dict[pair] <NEW_LINE> <DEDENT> return pair_dict
Reads from path and collapses the input data into a dictionary mapping pairs to SharedSegments. Parameters ---------- path : str t : float Filter out results less than t (in cM) user : str | None filter input by user identification haploscores : bool True if the input matchfile contains haploscores in an extra column at the end of each line. nomask : bool Use to enable/disable masking of likely false positive Germline regions merge_len : int If merge > 0, then call merging subroutine to merge segments that are close on each chromosome. Thus, the default -1 means no merging. Returns ------- pair_dict: dict[str: list[SharedSegments]] Each list of SharedSegments is sorted for processing by ersa_LL.estimate_relation()
625941c330dc7b7665901923
def inverse_mask(self): <NEW_LINE> <INDENT> return self.invert_mask()
Alias for :func:`invert_mask` See Also: :func:`invert_mask` Returns:
625941c360cbc95b062c64fd
def goodTree(length, level): <NEW_LINE> <INDENT> angle = 17 <NEW_LINE> width = 4 <NEW_LINE> turtle.width(width) <NEW_LINE> turtle.left(90) <NEW_LINE> turtle.forward(length) <NEW_LINE> def treeHelp(length, level): <NEW_LINE> <INDENT> width = turtle.width() <NEW_LINE> turtle.width(3 / 4 * width) <NEW_LINE> length = length * 3 / 4 <NEW_LINE> turtle.left(angle) <NEW_LINE> turtle.forward(length) <NEW_LINE> if level < width: <NEW_LINE> <INDENT> treeHelp(length * 3 / 4, level + 1) <NEW_LINE> <DEDENT> turtle.backward(length) <NEW_LINE> turtle.right(2 * angle) <NEW_LINE> turtle.forward(length) <NEW_LINE> if level < width: <NEW_LINE> <INDENT> treeHelp(length * 3 / 4, level + 1) <NEW_LINE> <DEDENT> turtle.backward(length) <NEW_LINE> turtle.left(angle) <NEW_LINE> turtle.width(width) <NEW_LINE> <DEDENT> treeHelp(length, 4-level)
a better fractal tree with turtle for extra credit
625941c3d10714528d5ffc9c
def getKeyboardButtonPoll(text: str, request_poll={}) -> Dict: <NEW_LINE> <INDENT> return {'text': text, 'request_poll': request_poll}
This object represents poll button of the reply keyboard Notes: For more info -> https://github.com/xSklero/python-telegram-api/wiki/KeyboardButton Args: text (str): Text of the button. request_poll (Dict, optional): If specified, the user will be asked to create a poll and send it to the bot when the button is pressed. Defaults to {}. Returns: Dict: KeyboardButton object.
625941c324f1403a92600b23
def sync(self, importer, state, log=None, max_changes=None, window=None, begin=None, end=None, stats=None): <NEW_LINE> <INDENT> importer.store = None <NEW_LINE> return _ics.sync(self, self.mapistore, importer, state, log or self.log, max_changes, window=window, begin=begin, end=end, stats=stats)
Perform synchronization against server node. :param importer: importer instance with callbacks to process changes :param state: start from this state (has to be given) :log: logger instance to receive important warnings/errors
625941c35fcc89381b1e1678
def twovec(axdef, indexa, plndef, indexp): <NEW_LINE> <INDENT> axdef = stypes.toDoubleVector(axdef) <NEW_LINE> indexa = ctypes.c_int(indexa) <NEW_LINE> plndef = stypes.toDoubleVector(plndef) <NEW_LINE> indexp = ctypes.c_int(indexp) <NEW_LINE> mout = stypes.emptyDoubleMatrix() <NEW_LINE> libspice.twovec_c(axdef, indexa, plndef, indexp, mout) <NEW_LINE> return stypes.matrixToList(mout)
Find the transformation to the right-handed frame having a given vector as a specified axis and having a second given vector lying in a specified coordinate plane. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/twovec_c.html :param axdef: Vector defining a principal axis. :type axdef: 3-Element Array of floats. :param indexa: Principal axis number of axdef (X=1, Y=2, Z=3). :type indexa: int :param plndef: Vector defining (with axdef) a principal plane. :type plndef: 3-Element Array of floats. :param indexp: Second axis number (with indexa) of principal plane. :type indexp: int :return: Output rotation matrix. :rtype: 3x3-Element Array of floats.
625941c35fdd1c0f98dc01ed
def topological_sort(graph, depth_first=False): <NEW_LINE> <INDENT> import networkx as nx <NEW_LINE> nodesort = list(nx.topological_sort(graph)) <NEW_LINE> if not depth_first: <NEW_LINE> <INDENT> return nodesort, None <NEW_LINE> <DEDENT> logger.debug("Performing depth first search") <NEW_LINE> nodes = [] <NEW_LINE> groups = [] <NEW_LINE> group = 0 <NEW_LINE> G = nx.Graph() <NEW_LINE> G.add_nodes_from(graph.nodes()) <NEW_LINE> G.add_edges_from(graph.edges()) <NEW_LINE> components = nx.connected_components(G) <NEW_LINE> for desc in components: <NEW_LINE> <INDENT> group += 1 <NEW_LINE> indices = [] <NEW_LINE> for node in desc: <NEW_LINE> <INDENT> indices.append(nodesort.index(node)) <NEW_LINE> <DEDENT> nodes.extend( np.array(nodesort)[np.array(indices)[np.argsort(indices)]] .tolist()) <NEW_LINE> for node in desc: <NEW_LINE> <INDENT> nodesort.remove(node) <NEW_LINE> <DEDENT> groups.extend([group] * len(desc)) <NEW_LINE> <DEDENT> return nodes, groups
Returns a depth first sorted order if depth_first is True
625941c33d592f4c4ed1d02d
def unmuted(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_pwr_squelch_ff_sptr_unmuted(self)
unmuted(self) -> bool
625941c326068e7796caec97
def submit_delete_problem_state_for_all_students(request, usage_key): <NEW_LINE> <INDENT> modulestore().get_item(usage_key) <NEW_LINE> task_type = 'delete_problem_state' <NEW_LINE> task_class = delete_problem_state <NEW_LINE> task_input, task_key = encode_problem_and_student_input(usage_key) <NEW_LINE> return submit_task(request, task_type, task_class, usage_key.course_key, task_input, task_key)
Request to have state deleted for a problem as a background task. The problem's state will be deleted for all students who have accessed the particular problem in a course. Parameters are the `course_id` and the `usage_key`, which must be a :class:`Location`. ItemNotFoundException is raised if the problem doesn't exist, or AlreadyRunningError if the particular problem's state is already being deleted.
625941c3596a897236089a7d
def run_from_copy(server_name, user_id, user_password, local_file, remote_file) : <NEW_LINE> <INDENT> sf = paramiko.Transport((server_name,22)) <NEW_LINE> sf.connect(username = user_id, password = user_password) <NEW_LINE> sftp = paramiko.SFTPClient.from_transport(sf) <NEW_LINE> return sftp.get(remote_file,local_file )
Copy file from remote to local. Remark: No handing of any kind of exeception. Args: server_name(string): Name of the host to connect. user_id(string): User to connect with. user_password(string): User password. local_file(string): Absolute path of file in local. remote_file(string): Absolute path of file in remote. Returns:
625941c3236d856c2ad44793
def test_urgency_set(self): <NEW_LINE> <INDENT> self.launcher.set_urgent() <NEW_LINE> self.assertTrue( self.launcher.entry.props.urgent, "The launcher should be set to urgent.") <NEW_LINE> self.launcher.set_urgent(False) <NEW_LINE> self.assertFalse( self.launcher.entry.props.urgent, "The launcher should not be set to urgent.")
The urgency of the launcher is set.
625941c3435de62698dfdc07
def expand_unit_rules(rules, lhs_fn, rhs_fn, rule_init_fn, nonterminal_prefix): <NEW_LINE> <INDENT> unit_tuples = set() <NEW_LINE> other_rules = [] <NEW_LINE> for rule in rules: <NEW_LINE> <INDENT> tokens = rhs_fn(rule).split(" ") <NEW_LINE> if len(tokens) == 1 and tokens[0].startswith(nonterminal_prefix): <NEW_LINE> <INDENT> unit_rhs = tokens[0][len(nonterminal_prefix):] <NEW_LINE> unit_tuples.add((lhs_fn(rule), unit_rhs)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> other_rules.append(rule) <NEW_LINE> <DEDENT> <DEDENT> unit_lhs_to_rhs_set = collections.defaultdict(set) <NEW_LINE> for unit_lhs, unit_rhs in unit_tuples: <NEW_LINE> <INDENT> unit_lhs_to_rhs_set[unit_lhs].add(unit_rhs) <NEW_LINE> <DEDENT> derived_unit_tuples = set() <NEW_LINE> for unit_lhs_start in unit_lhs_to_rhs_set.keys(): <NEW_LINE> <INDENT> stack = [unit_lhs_start] <NEW_LINE> visited_lhs = [] <NEW_LINE> while stack: <NEW_LINE> <INDENT> unit_lhs = stack.pop() <NEW_LINE> if unit_lhs in visited_lhs: <NEW_LINE> <INDENT> raise ValueError("There exists an unallowed cycle in unit rules: %s" % visited_lhs) <NEW_LINE> <DEDENT> visited_lhs.append(unit_lhs) <NEW_LINE> for unit_rhs in unit_lhs_to_rhs_set.get(unit_lhs, {}): <NEW_LINE> <INDENT> stack.append(unit_rhs) <NEW_LINE> <DEDENT> derived_unit_tuples.add((unit_lhs_start, unit_rhs)) <NEW_LINE> <DEDENT> <DEDENT> unit_tuples |= derived_unit_tuples <NEW_LINE> new_rules = [] <NEW_LINE> for unit_lhs, unit_rhs in unit_tuples: <NEW_LINE> <INDENT> for rule in other_rules: <NEW_LINE> <INDENT> if lhs_fn(rule) == unit_rhs: <NEW_LINE> <INDENT> new_rules.append(rule_init_fn(unit_lhs, rule)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return other_rules + new_rules
Removes unit rules, i.e. X -> Y where X and Y are non-terminals. Args: rules: List of rule objects. lhs_fn: Returns `lhs` of a rule. rhs_fn: Returns `rhs` of a rule. rule_init_fn: Function that takes (lhs, rule) and returns a copy of `rule` but with the lhs symbol set to `lhs`. nonterminal_prefix: String prefix for nonterminal symbols in `rhs`. Returns: Set of tuples of (lhs, rhs, original rule_idx of rhs) to add.
625941c316aa5153ce362433
def plot_2d_rint(_df,_column_interv, _column_x, _column_y, _title = 'example', _filename = ''): <NEW_LINE> <INDENT> for value in _df[_column_interv].value_counts().index.tolist(): <NEW_LINE> <INDENT> df_sub = _df[_df[_column_interv] == value] <NEW_LINE> fig = plt.figure(figsize=(20, 10)) <NEW_LINE> ax = fig.add_subplot() <NEW_LINE> ax.scatter(df_sub[_column_x], df_sub[_column_y], c='green', alpha=0.2, marker="s") <NEW_LINE> plt.title('Plot {}, {} con valore {}'.format(_title,_column_interv, str(value))) <NEW_LINE> plt.xlabel(_column_x) <NEW_LINE> plt.ylabel(_column_y) <NEW_LINE> plt.grid() <NEW_LINE> plt.savefig(_filename + '_{}_{}.png'.format(_column_interv, str(value)))
Creazione di molteplici plot per ogni valore distinto di un attributo di un Dataframe. Analisi bidimensionale. :param _df: Dataframe Dataframe da analizzare :param _column_interv: str colonna del Dataframe su cui partizionare i plot. Per ogni suo valore univoco verrà creato un plot e un subset. :param _column_x: str colonna del Dataframe da analizzare lungo a x :param _column_y: str colonna del Dataframe da analizzare lungo a y :param _title: str nome del grafico :param _filename: str percorso o nome del file png da salvare
625941c34d74a7450ccd417e
def control_q(self): <NEW_LINE> <INDENT> if self.success_rate == None: <NEW_LINE> <INDENT> print("Error, first compute success rate") <NEW_LINE> exit(-1) <NEW_LINE> <DEDENT> self.q = self.evaluate_map('q', self.success_rate)
Use population success rate to update Xi
625941c382261d6c526ab457
def seal_is_valid(self): <NEW_LINE> <INDENT> if self.seal_data == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> signature = binascii.unhexlify(hex(self.seal_data)[2:].zfill(96)) <NEW_LINE> pk = VerifyingKey.from_string(self.get_public_key()) <NEW_LINE> try: <NEW_LINE> <INDENT> return pk.verify(signature, self.unsealed_header().encode("utf-8")) <NEW_LINE> <DEDENT> except ecdsa.keys.BadSignatureError: <NEW_LINE> <INDENT> return False
Checks whether a block's seal_data forms a valid seal. In PoA, this means that Verif(PK, [block, sig]) = accept. (aka the unsealed block header is validly signed under the authority's public key) Returns: bool: True only if a block's seal data forms a valid seal according to PoA.
625941c3ad47b63b2c509f3a
def on_uiButtonBox_clicked(self, button): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from gns3.main_window import MainWindow <NEW_LINE> if button == self.uiButtonBox.button(QtGui.QDialogButtonBox.Apply): <NEW_LINE> <INDENT> self.applySettings() <NEW_LINE> <DEDENT> elif button == self.uiButtonBox.button(QtGui.QDialogButtonBox.Reset): <NEW_LINE> <INDENT> self.resetSettings() <NEW_LINE> <DEDENT> elif button == self.uiButtonBox.button(QtGui.QDialogButtonBox.Cancel): <NEW_LINE> <INDENT> HTTPClient.setProgressCallback(Progress(MainWindow.instance())) <NEW_LINE> QtGui.QDialog.reject(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.applySettings() <NEW_LINE> HTTPClient.setProgressCallback(Progress(MainWindow.instance())) <NEW_LINE> QtGui.QDialog.accept(self) <NEW_LINE> <DEDENT> <DEDENT> except ConfigurationError: <NEW_LINE> <INDENT> pass
Slot called when a button of the uiButtonBox is clicked. :param button: button that was clicked (QAbstractButton)
625941c315fb5d323cde0ac8
def read_bitcoin_config(dbdir): <NEW_LINE> <INDENT> from ConfigParser import SafeConfigParser <NEW_LINE> class FakeSecHead(object): <NEW_LINE> <INDENT> def __init__(self, fp): <NEW_LINE> <INDENT> self.fp = fp <NEW_LINE> self.sechead = '[all]\n' <NEW_LINE> <DEDENT> def readline(self): <NEW_LINE> <INDENT> if self.sechead: <NEW_LINE> <INDENT> try: return self.sechead <NEW_LINE> finally: self.sechead = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = self.fp.readline() <NEW_LINE> if s.find('#') != -1: <NEW_LINE> <INDENT> s = s[0:s.find('#')].strip() +"\n" <NEW_LINE> <DEDENT> return s <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> config_parser = SafeConfigParser() <NEW_LINE> config_parser.readfp(FakeSecHead(open(os.path.join(dbdir, "insurance.conf")))) <NEW_LINE> return dict(config_parser.items("all"))
Read the insurance.conf file from dbdir, returns dictionary of settings
625941c399cbb53fe6792ba2
def __add__(self, val): <NEW_LINE> <INDENT> v = val if isinstance(val, Variable) else IndependentVariable(val) <NEW_LINE> return Sum(self, v)
Addition of two variables, or of a variable and a scalar.
625941c3d268445f265b4e29
def get_game_config_val_int(key): <NEW_LINE> <INDENT> _game_config = client_configs['game_config'] <NEW_LINE> for item in _game_config: <NEW_LINE> <INDENT> if item['key'] == key: <NEW_LINE> <INDENT> return int(item['val']) <NEW_LINE> <DEDENT> <DEDENT> return 0
获取游戏数据表值 BattleSpeedLineTime 111 BattleEnemyScale 1 BattleModuleLevelScale 0.000 PlayerCreateMonster 1,4,7 PlayerStaminaRecover 10 PlayerMaxStamina 120 UpgradeStarCard 3,3,3,6 UpgradeStarGold 10000,20000,500000,1000000 TeamOpenLevel 1,3,5,8,12 LevelOpenTeamNum 1,12,30 VIPLevelOpenTeamNum 5,10 MaxBattleSpeed 5 PlayerMonsterSkillOpen 1,5,1000,1000,1000 Red [ff0000] Green [00ff00] MonsterMaxLevel 100 MaxStorageNum 200 BattleResultRank 5,12,30
625941c36e29344779a625cf
def __init__(self, version, response, solution): <NEW_LINE> <INDENT> super(BrandedCallPage, self).__init__(version, response) <NEW_LINE> self._solution = solution
Initialize the BrandedCallPage :param Version version: Version that contains the resource :param Response response: Response from the API :returns: twilio.rest.preview.trusted_comms.branded_call.BrandedCallPage :rtype: twilio.rest.preview.trusted_comms.branded_call.BrandedCallPage
625941c3f8510a7c17cf96b6
def test_remove_from_error(self, client): <NEW_LINE> <INDENT> vm = mfactory.VirtualMachineFactory(operstate='ERROR') <NEW_LINE> mfactory.NetworkInterfaceFactory(machine=vm) <NEW_LINE> msg = self.create_msg(operation='OP_INSTANCE_REMOVE', instance=vm.backend_vm_id) <NEW_LINE> with mocked_quotaholder(): <NEW_LINE> <INDENT> update_db(client, msg) <NEW_LINE> <DEDENT> client.basic_ack.assert_called_once() <NEW_LINE> db_vm = VirtualMachine.objects.get(id=vm.id) <NEW_LINE> self.assertEqual(db_vm.operstate, 'DESTROYED') <NEW_LINE> self.assertTrue(db_vm.deleted) <NEW_LINE> self.assertFalse(db_vm.nics.all())
Test that error removes delete error builds
625941c3a8370b771705285b
def exit_config_mode(self, exit_config: str = "return", pattern: str = r">") -> str: <NEW_LINE> <INDENT> return super().exit_config_mode(exit_config=exit_config, pattern=pattern)
Exit configuration mode.
625941c371ff763f4b549643
def update(self, grid): <NEW_LINE> <INDENT> nid = grid.nid <NEW_LINE> add_grid = self.check_if_current(nid, self.nid) <NEW_LINE> if add_grid: <NEW_LINE> <INDENT> self.add(nid, grid.xyz, cp=grid.cp, cd=grid.cd, ps=grid.ps, seid=grid.seid, comment=grid.comment) <NEW_LINE> self.is_current = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> inid = np.where(nid == self.nid)[0] <NEW_LINE> self.nid[inid] = grid.nid <NEW_LINE> self.xyz[inid] = grid.xyz <NEW_LINE> self.cp[inid] = grid.cp <NEW_LINE> self.cd[inid] = grid.cd <NEW_LINE> self.ps[inid] = grid.ps <NEW_LINE> self.seid[inid] = grid.seid
functions like a dictionary
625941c345492302aab5e27c
def detect_faces(self, *args, **kwargs): <NEW_LINE> <INDENT> super().detect_faces(*args, **kwargs) <NEW_LINE> self.rotate_queue = queue_manager.get_queue("s3fd_rotate", 8, False) <NEW_LINE> prediction_queue = queue_manager.get_queue("s3fd_pred", 8, False) <NEW_LINE> post_queue = queue_manager.get_queue("s3fd_post", 8, False) <NEW_LINE> worker = FSThread( target=self.prediction_thread, args=(prediction_queue, post_queue) ) <NEW_LINE> post_worker = FSThread( target=self.post_processing_thread, args=(post_queue, self.rotate_queue) ) <NEW_LINE> worker.start() <NEW_LINE> post_worker.start() <NEW_LINE> got_first_eof = False <NEW_LINE> while True: <NEW_LINE> <INDENT> worker.check_and_raise_error() <NEW_LINE> post_worker.check_and_raise_error() <NEW_LINE> got_eof, in_batch = self.get_batch() <NEW_LINE> batch = list() <NEW_LINE> for item in in_batch: <NEW_LINE> <INDENT> s3fd_opts = item.setdefault("_s3fd", {}) <NEW_LINE> if "scaled_img" not in s3fd_opts: <NEW_LINE> <INDENT> logger.trace("Resizing %s" % basename(item["filename"])) <NEW_LINE> detect_image, scale, pads = self.compile_detection_image( item["image"], is_square=True, pad_to=self.target ) <NEW_LINE> s3fd_opts["scale"] = scale <NEW_LINE> s3fd_opts["pads"] = pads <NEW_LINE> s3fd_opts["rotations"] = list(self.rotation) <NEW_LINE> s3fd_opts["rotmatrix"] = None <NEW_LINE> img = s3fd_opts["scaled_img"] = detect_image <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.trace("Rotating %s" % basename(item["filename"])) <NEW_LINE> angle = s3fd_opts["rotations"][0] <NEW_LINE> img, rotmat = self.rotate_image_by_angle( s3fd_opts["scaled_img"], angle, *self.target ) <NEW_LINE> s3fd_opts["rotmatrix"] = rotmat <NEW_LINE> <DEDENT> batch.append((img, item)) <NEW_LINE> <DEDENT> if batch: <NEW_LINE> <INDENT> batch_data = np.array([x[0] for x in batch], dtype="float32") <NEW_LINE> batch_data = self.model.prepare_batch(batch_data) <NEW_LINE> batch_items = [x[1] for x in batch] <NEW_LINE> prediction_queue.put((batch_data, batch_items)) <NEW_LINE> <DEDENT> if got_eof: <NEW_LINE> <INDENT> logger.debug("S3fd-amd main worker got EOF") <NEW_LINE> prediction_queue.put("EOF") <NEW_LINE> self.batch_size = 1 <NEW_LINE> if got_first_eof: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> got_first_eof = True <NEW_LINE> <DEDENT> <DEDENT> logger.debug("Joining s3fd-amd worker") <NEW_LINE> worker.join() <NEW_LINE> post_worker.join() <NEW_LINE> for qname in (): <NEW_LINE> <INDENT> queue_manager.del_queue(qname) <NEW_LINE> <DEDENT> logger.debug("Detecting Faces complete")
Detect faces in rgb image
625941c3004d5f362079a2ef
def send_mouse_event(self, mouse_event): <NEW_LINE> <INDENT> if mouse_event: <NEW_LINE> <INDENT> self.mouse_pos[0] = mouse_event.pos[0] <NEW_LINE> self.mouse_pos[1] = mouse_event.pos[1] <NEW_LINE> self.language_engine.global_symbol_table['mouse.x'] = self.mouse_pos[0] <NEW_LINE> self.language_engine.global_symbol_table['mouse.y'] = self.mouse_pos[1] <NEW_LINE> if mouse_event.type == pygame.MOUSEMOTION: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> event_names = [] <NEW_LINE> if mouse_event: <NEW_LINE> <INDENT> mouse_button = mouse_event.button <NEW_LINE> if len(self.MOUSE_EVENT_TABLE) > mouse_button: <NEW_LINE> <INDENT> ev_table_entry = self.MOUSE_EVENT_TABLE[mouse_button] <NEW_LINE> self.event_engine.queue_event( event.MouseEvent( ev_table_entry["instance_event_name"], {"position": mouse_event.pos} ) ) <NEW_LINE> event_names.append(ev_table_entry["instance_event_name"]) <NEW_LINE> self.event_engine.queue_event( event.MouseEvent( ev_table_entry["global_event_name"], {"position": mouse_event.pos} ) ) <NEW_LINE> event_names.append(ev_table_entry["global_event_name"]) <NEW_LINE> if mouse_event.type == pygame.MOUSEBUTTONDOWN: <NEW_LINE> <INDENT> if 'instance_pressed_name' in ev_table_entry: <NEW_LINE> <INDENT> self.event_engine.queue_event( event.MouseEvent( ev_table_entry["instance_pressed_name"], {"position": mouse_event.pos} ) ) <NEW_LINE> event_names.append(ev_table_entry["instance_pressed_name"]) <NEW_LINE> self.event_engine.queue_event( event.MouseEvent( ev_table_entry["global_pressed_name"], {"position": mouse_event.pos} ) ) <NEW_LINE> event_names.append(ev_table_entry["global_pressed_name"]) <NEW_LINE> <DEDENT> <DEDENT> if mouse_event.type == pygame.MOUSEBUTTONUP: <NEW_LINE> <INDENT> if 'instance_released_name' in ev_table_entry: <NEW_LINE> <INDENT> self.event_engine.queue_event( event.MouseEvent( ev_table_entry["instance_released_name"], {"position": mouse_event.pos} ) ) <NEW_LINE> event_names.append(ev_table_entry["instance_released_name"]) <NEW_LINE> self.event_engine.queue_event( event.MouseEvent( ev_table_entry["global_released_name"], {"position": mouse_event.pos} ) ) <NEW_LINE> event_names.append(ev_table_entry["global_released_name"]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.event_engine.queue_event( event.MouseEvent("mouse_nobutton", {"position": self.mouse_pos}) ) <NEW_LINE> event_names.append("mouse_nobutton") <NEW_LINE> self.event_engine.queue_event( event.MouseEvent("mouse_global_nobutton", {"position": self.mouse_pos}) ) <NEW_LINE> event_names.append("mouse_global_nobutton") <NEW_LINE> <DEDENT> for ev_name in event_names: <NEW_LINE> <INDENT> self.event_engine.transmit_event(ev_name)
Translate pygame mouse events (including no buttons pressed) to appropriate pygame_maker mouse events.
625941c34c3428357757c2e5
def reGenChain(self): <NEW_LINE> <INDENT> self.m_rigElement.clear() <NEW_LINE> self.genChain()
Method: reGenChain A method to regenerate the chain based on a new set of parameters
625941c33c8af77a43ae3759
def move_up(): <NEW_LINE> <INDENT> return move('up')
Move straight up. Convenience function for user facing portion. :return: result of move(direction)
625941c32ae34c7f2600d0ed
def get_manuals(): <NEW_LINE> <INDENT> docs = glob.glob(os.path.join("doc", "manual", "*.html")) <NEW_LINE> docs.append(os.path.join("doc", "manual", "manual.css")) <NEW_LINE> if get_command() == "sdist": <NEW_LINE> <INDENT> docs.append(os.path.join("doc", "manual.tex")) <NEW_LINE> docs.append(os.path.join("doc", ".latex2html-init")) <NEW_LINE> <DEDENT> return docs
Returns a list of all manual files
625941c3d4950a0f3b08c30b
def unindex_object(self): <NEW_LINE> <INDENT> pass
No action. Unindex of subdevices will happen in manage_deleteAdministrativeRole
625941c382261d6c526ab458
@pytest.fixture <NEW_LINE> def backend_with_a_poll(backend_with_a_round): <NEW_LINE> <INDENT> backend_with_a_round.add_poll(GAME_ID, ROUND_NAME) <NEW_LINE> return backend_with_a_round
Return a persistence backend holding one game with one round.
625941c3287bf620b61d3a20
def is_server(self, location): <NEW_LINE> <INDENT> return location in self.servers
Return True if 'location' is an index server.
625941c30a50d4780f666e4c
def publish_status_information(): <NEW_LINE> <INDENT> if cf.has_option("defaults", "status_publish") and cf.status_publish: <NEW_LINE> <INDENT> status_topic = cf.g("defaults", "status_topic", "mqttwarn/$SYS") <NEW_LINE> logger.info(f"Publishing status information to {status_topic}") <NEW_LINE> publications = [ ("version", __version__), ("platform", sys.platform), ("python/version", platform.python_version()), ] <NEW_LINE> try: <NEW_LINE> <INDENT> for publication in publications: <NEW_LINE> <INDENT> subtopic, message = publication <NEW_LINE> mqttc.publish(status_topic + "/" + subtopic, message, retain=True) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> logger.exception("Unable to publish status information")
Implement `$SYS` topic, like Mosquitto's "Broker Status". https://mosquitto.org/man/mosquitto-8.html#idm289 Idea from Mosquitto:: $ mosquitto_sub -t '$SYS/broker/version' -v $SYS/broker/version mosquitto version 2.0.10 Synopsis:: $ mosquitto_sub -t 'mqttwarn/$SYS/#' -v mqttwarn/$SYS/version 0.26.2 mqttwarn/$SYS/platform darwin mqttwarn/$SYS/python/version 3.9.7
625941c3be7bc26dc91cd5be
def facts(self, name=None, value=None, **kwargs): <NEW_LINE> <INDENT> if name is not None and value is not None: <NEW_LINE> <INDENT> path = '{0}/{1}'.format(name, value) <NEW_LINE> <DEDENT> elif name is not None and value is None: <NEW_LINE> <INDENT> path = name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> path = None <NEW_LINE> <DEDENT> facts = self._query('facts', path=path, **kwargs) <NEW_LINE> for fact in facts: <NEW_LINE> <INDENT> yield Fact.create_from_dict(fact)
Query for facts limited by either name, value and/or query. :param name: (Optional) Only return facts that match this name. :type name: :obj:`string` :param value: (Optional) Only return facts of `name` that\ match this value. Use of this parameter requires the `name`\ parameter be set. :type value: :obj:`string` :param \**kwargs: The rest of the keyword arguments are passed to the _query function :returns: A generator yielding Facts. :rtype: :class:`pypuppetdb.types.Fact`
625941c3baa26c4b54cb10dc
def default_view(self, **kwargs): <NEW_LINE> <INDENT> v = ColorTranslationDiagnostic(op = self) <NEW_LINE> v.trait_set(**kwargs) <NEW_LINE> return v
Returns a diagnostic plot to see if the bleedthrough spline estimation is working. Returns ------- IView A diagnostic view, call `ColorTranslationDiagnostic.plot` to see the diagnostic plots
625941c394891a1f4081ba64
def write_org_ratios_to_database(self, org_type): <NEW_LINE> <INDENT> for datum in self.get_rows_as_dicts(self.table_name(org_type)): <NEW_LINE> <INDENT> datum["measure_id"] = self.measure.id <NEW_LINE> if self.measure.is_cost_based: <NEW_LINE> <INDENT> datum["cost_savings"] = convertSavingsToDict(datum) <NEW_LINE> <DEDENT> datum["percentile"] = normalisePercentile(datum["percentile"]) <NEW_LINE> datum = {fn: datum[fn] for fn in MEASURE_FIELDNAMES if fn in datum} <NEW_LINE> MeasureValue.objects.create(**datum)
Create measure values for organisation ratios.
625941c3c432627299f04c00
def invoke_hook (self, msg_id, domain, result, body=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = int(result) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> log.error("Received response code is not valid: %s! Abort callback..." % result) <NEW_LINE> return <NEW_LINE> <DEDENT> if (domain, msg_id) not in self.__register: <NEW_LINE> <INDENT> log.warning("Received unregistered callback with id: %s from domain: %s" % (msg_id, domain)) <NEW_LINE> return <NEW_LINE> <DEDENT> log.debug("Received valid callback with id: %s, result: %s from domain: %s" % (msg_id, "TIMEOUT" if not result else result, domain)) <NEW_LINE> cb = self.__register.get((domain, msg_id)) <NEW_LINE> if cb is None: <NEW_LINE> <INDENT> log.error("Missing callback: %s from register!" % msg_id) <NEW_LINE> return <NEW_LINE> <DEDENT> stats.add_measurement_start_entry(type=stats.TYPE_DEPLOY_CALLBACK, info="%s-callback_received" % domain) <NEW_LINE> cb.result_code = result <NEW_LINE> cb.body = body <NEW_LINE> if cb.hook is None: <NEW_LINE> <INDENT> log.debug("No hook was defined!") <NEW_LINE> self.__blocking_mutex.set() <NEW_LINE> return <NEW_LINE> <DEDENT> elif callable(cb.hook): <NEW_LINE> <INDENT> log.debug("Schedule callback hook: %s" % cb.short()) <NEW_LINE> cb.hook(callback=cb) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.warning("No callable hook was defined for the received callback: %s!" % msg_id)
Main entry point to invoke a callback based on the extracted data from received message. :param msg_id: message id :type msg_id: str :param domain: domain name :type domain: str :param result: result of the callback :type result: str :param body: parsed callback body (optional) :type body: str or None :return: None
625941c33cc13d1c6d3c7336
def epsilon_action(a,eps = 0.1): <NEW_LINE> <INDENT> rand_number = np.random.random() <NEW_LINE> if rand_number < (1-eps): <NEW_LINE> <INDENT> return a <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return np.random.choice(CONST_ACTION_LST)
epsilon greedy. Chooses either action a or an radom action with epsioln probablility Args: None Return: None
625941c35fc7496912cc3939
def Oracle(X, B, s, t, list_V): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> Dmax = 1 <NEW_LINE> global num_senses <NEW_LINE> global num_moves <NEW_LINE> global num_experiments <NEW_LINE> t = t[:-3] <NEW_LINE> num_moves += len(t) <NEW_LINE> random_board = Board() <NEW_LINE> random_board.load_random_board() <NEW_LINE> new_start = time.time() <NEW_LINE> for d in range(Dmax): <NEW_LINE> <INDENT> a = random_walk_in_X(X, B) <NEW_LINE> a_t = a+t <NEW_LINE> a_s = a+s <NEW_LINE> new_start = time.time() <NEW_LINE> q = copy.deepcopy(random_board) <NEW_LINE> q2 = copy.deepcopy(q) <NEW_LINE> new_start = time.time() <NEW_LINE> q.apply_basic_moves(a_s) <NEW_LINE> q2.apply_basic_moves(a_t) <NEW_LINE> new_start = time.time() <NEW_LINE> a = q.get_predicate() <NEW_LINE> b = q2.get_predicate() <NEW_LINE> num_senses += 1 <NEW_LINE> if not a == b: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> new_start = time.time() <NEW_LINE> return a == b
determine if s and t are equivilant
625941c3442bda511e8be3d6
def test_bad_attribute_access(): <NEW_LINE> <INDENT> program = f"x = 1\n" f"x.wrong_name\n" <NEW_LINE> module, inferer = cs._parse_text(program) <NEW_LINE> expr_node = next(module.nodes_of_class(nodes.Expr)) <NEW_LINE> expected_msg = "TypeFail: Invalid attribute lookup x.wrong_name" <NEW_LINE> assert expr_node.inf_type.getValue() == expected_msg
User tries to access a non-existing attribute; or misspells the attribute name.
625941c3aad79263cf3909fa
def countSubstrings(self, s): <NEW_LINE> <INDENT> output = [] <NEW_LINE> def substring(index1, index2): <NEW_LINE> <INDENT> if index1 < 0 or index2 == len(s): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if index1 == index2: <NEW_LINE> <INDENT> output.append(1) <NEW_LINE> substring(index1, index2 + 1) <NEW_LINE> substring(index1 - 1, index2 + 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if s[index1] == s[index2]: <NEW_LINE> <INDENT> output.append(1) <NEW_LINE> substring(index1 - 1, index2 + 1) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for index in range(len(s)): <NEW_LINE> <INDENT> substring(index, index) <NEW_LINE> <DEDENT> return sum(output)
:type s: str :rtype: int
625941c3851cf427c661a4cd
def __ConnectAndDrop(self): <NEW_LINE> <INDENT> connection = self.pool.acquire() <NEW_LINE> cursor = connection.cursor() <NEW_LINE> cursor.execute("select count(*) from TestNumbers") <NEW_LINE> count, = cursor.fetchone() <NEW_LINE> self.failUnlessEqual(count, 10)
Connect to the database, perform a query and drop the connection.
625941c326238365f5f0ee27
def read_prefixlist(): <NEW_LINE> <INDENT> global d_prefix <NEW_LINE> try: <NEW_LINE> <INDENT> with open(config['prefixlist'], "r") as fp: <NEW_LINE> <INDENT> prefixdata = fp.readlines() <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> print("cannot read the prefixlist file") <NEW_LINE> return <NEW_LINE> <DEDENT> for line in prefixdata: <NEW_LINE> <INDENT> items = line[:-1].split() <NEW_LINE> if len(items) == 3: <NEW_LINE> <INDENT> d_prefix[items[0]] = items[1]
Read the prefixlist and stotr in the memory object list
625941c3377c676e91272165
def get_modal_lit(self): <NEW_LINE> <INDENT> for disjunct in self.disjuncts: <NEW_LINE> <INDENT> if u.is_complex(disjunct): <NEW_LINE> <INDENT> if isinstance(disjunct[0], parser.Modality): <NEW_LINE> <INDENT> self.disjuncts.remove(disjunct) <NEW_LINE> return disjunct <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None
Returns first modal atom in a given disjunction.
625941c391af0d3eaac9b9d2
def levelOrder(self, root): <NEW_LINE> <INDENT> ans = [] <NEW_LINE> if not root: return ans <NEW_LINE> q = [root] <NEW_LINE> while q: <NEW_LINE> <INDENT> ans.append([x.val for x in q]) <NEW_LINE> nq = [] <NEW_LINE> for node in q: <NEW_LINE> <INDENT> if node.left: nq.append(node.left) <NEW_LINE> if node.right: nq.append(node.right) <NEW_LINE> <DEDENT> q = nq <NEW_LINE> <DEDENT> return ans
:type root: TreeNode :rtype: List[List[int]]
625941c37c178a314d6ef418
def test_cfl_max_report(): <NEW_LINE> <INDENT> test_utils.assert_report(DEMO_ID, 'CFL_max', 0.0, tolerance=0.05, relative=False)
Fluid should be at rest by the end of simulation
625941c31f037a2d8b9461ba
def merge_(self, other): <NEW_LINE> <INDENT> self.data[0] = min(self.data[0], other[0]) <NEW_LINE> self.data[1] = max(self.data[1], other[1]) <NEW_LINE> return self
Merges inplace two ranges together Parameters ---------- other : Range a range Returns ------- Range the range itself
625941c3b5575c28eb68dfba
def isAnagram(self, s, t): <NEW_LINE> <INDENT> dic = {} <NEW_LINE> if len(s) != len(t): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for cs,ct in zip(s,t): <NEW_LINE> <INDENT> if cs not in dic.keys(): <NEW_LINE> <INDENT> dic[cs] = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dic[cs] += 1 <NEW_LINE> <DEDENT> if ct not in dic.keys(): <NEW_LINE> <INDENT> dic[ct] = -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dic[ct] -= 1 <NEW_LINE> <DEDENT> <DEDENT> for key in dic.keys(): <NEW_LINE> <INDENT> if dic[key]!=0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
:type s: str :type t: str :rtype: bool
625941c371ff763f4b549644
def close(self, event=None): <NEW_LINE> <INDENT> if self.cluster_name_ant is not None: <NEW_LINE> <INDENT> xssh.close_ssh_client_connection(self.ssh_client) <NEW_LINE> <DEDENT> self.main.label_process['text'] = '' <NEW_LINE> self.main.close_current_form()
Close "FormShowStatusBatchJobs".
625941c3ff9c53063f47c1b0
def itered(self): <NEW_LINE> <INDENT> return self.elts
An iterator over the elements this node contains. :returns: The contents of this node. :rtype: iterable(NodeNG)
625941c3d7e4931a7ee9ded8
def _maybe_pad_seqs(seqs, dtype, depth): <NEW_LINE> <INDENT> if not len(seqs): <NEW_LINE> <INDENT> return np.zeros((0, 0, depth), dtype) <NEW_LINE> <DEDENT> lengths = [len(s) for s in seqs] <NEW_LINE> if len(set(lengths)) == 1: <NEW_LINE> <INDENT> return np.array(seqs, dtype) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> length = max(lengths) <NEW_LINE> return (np.array([np.pad(s, [(0, length - len(s)), (0, 0)], mode='constant') for s in seqs], dtype))
Pads sequences to match the longest and returns as a numpy array.
625941c3091ae35668666f1d
def gcd_approx(a, b, min_fraction=1E-8, tolerance=1E-5): <NEW_LINE> <INDENT> a=abs(a) <NEW_LINE> b=abs(b) <NEW_LINE> a,b = max(a,b), min(a,b) <NEW_LINE> a0,b0 = a,b <NEW_LINE> if b==0: <NEW_LINE> <INDENT> raise ArithmeticError("Can't find GCD if one of numbers is 0") <NEW_LINE> <DEDENT> min_gcd=b*min_fraction <NEW_LINE> while b>=min_gcd: <NEW_LINE> <INDENT> if (integer_distance(a0/b)+integer_distance(b0/b))<=tolerance: <NEW_LINE> <INDENT> return b <NEW_LINE> <DEDENT> a,b = b,a%b <NEW_LINE> <DEDENT> raise ArithmeticError("Can't find approximate GCD for numbers",a0,b0)
Approximate Euclid's algorithm for possible non-integer values. Try to find a number `d` such that ``a/d`` and ``b/d`` are less than `tolerance` away from a closest integer. If GCD becomes less than ``min_fraction * min(a, b)``, raise :exc:`ArithmeticError`.
625941c3a17c0f6771cbe00e
def show(self, str): <NEW_LINE> <INDENT> self.set_numbers(str) <NEW_LINE> self.__ic_tm1637.set_command(0x44) <NEW_LINE> for i in range(min(4, len(self.__numbers))): <NEW_LINE> <INDENT> dp = True if self.__numbers[i].count('.') > 0 else False <NEW_LINE> num = self.__numbers[i].replace('.','') <NEW_LINE> if num == '#': <NEW_LINE> <INDENT> num = 10 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> num = int(num) <NEW_LINE> <DEDENT> if dp: <NEW_LINE> <INDENT> self.__ic_tm1637.set_data(self.__address_code[i], self.__number_code[num]|0x80) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__ic_tm1637.set_data(self.__address_code[i], self.__number_code[num]) <NEW_LINE> <DEDENT> <DEDENT> self.on()
Set the numbers array to show and enable the display :return: void
625941c35166f23b2e1a5115
def update(self): <NEW_LINE> <INDENT> data_stored = self.data_stored <NEW_LINE> simulator = self.simulator <NEW_LINE> next_step = simulator.get_next_step() <NEW_LINE> if not next_step: <NEW_LINE> <INDENT> timer = self.timer <NEW_LINE> timer.stop() <NEW_LINE> return <NEW_LINE> <DEDENT> trial, noise_level, circuit_size = next_step <NEW_LINE> self.update_labels(trial, noise_level, circuit_size) <NEW_LINE> simulator.run(trial, noise_level, circuit_size, data_stored) <NEW_LINE> random_circuit = simulator.random_circuit <NEW_LINE> gate_parameters = random_circuit.gate_parameters <NEW_LINE> self.update_figures(gate_parameters, random_circuit)
Takes a simulation step, updating labels, circuit, and parameter map.
625941c3ac7a0e7691ed408b
def get_features(self, **kwargs): <NEW_LINE> <INDENT> return PaginatedList( Feature, self._requester, "GET", "accounts/{}/features".format(self.id), {"account_id": self.id}, _kwargs=combine_kwargs(**kwargs), )
Lists all of the features of an account. :calls: `GET /api/v1/accounts/:account_id/features <https://canvas.instructure.com/doc/api/feature_flags.html#method.feature_flags.index>`_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.feature.Feature`
625941c399fddb7c1c9de34d
def get_box_position(box): <NEW_LINE> <INDENT> row = box[ROW_INDEX] <NEW_LINE> cell = box[CELL_INDEX] <NEW_LINE> x = MARGIN_SIZE + (BOX_SIZE * cell) + (GAP_SIZE * cell) <NEW_LINE> y = MARGIN_SIZE + INFO_SIZE + (BOX_SIZE * row) + (GAP_SIZE * row) <NEW_LINE> return x, y
Returns the x and y coordinates of the specified box
625941c34428ac0f6e5ba7ad
def add(self, name, tagged_name, rewrite=True): <NEW_LINE> <INDENT> node = self._trie <NEW_LINE> for token in tagged_name: <NEW_LINE> <INDENT> word = token[0].lower() <NEW_LINE> node = node.setdefault(word, {}) <NEW_LINE> <DEDENT> if rewrite or TermsTrie._TERM_END not in node: <NEW_LINE> <INDENT> node[TermsTrie._TERM_END] = name
Add new term to termtrie :name: [unicode] name of the term :tagged_name: list of tagged tokens
625941c3a79ad161976cc101
def validate(self) -> None: <NEW_LINE> <INDENT> err_collector = GdsCollector_() <NEW_LINE> if not self.validate_(err_collector, recursive=True): <NEW_LINE> <INDENT> raise NuspecValidationError( "Invalid NugetPackage specification", *err_collector.get_messages() )
Ensures that the definition is well-formed according to the Nuspec XML schema definition. See Scripts egenerate_nuspec.ds.py for more details.
625941c32c8b7c6e89b3577d
def set_orientation_period(self, period): <NEW_LINE> <INDENT> self.ipcon.send_request(self, IMU.FUNCTION_SET_ORIENTATION_PERIOD, (period,), 'I', '')
Sets the period in ms with which the :func:`Orientation` callback is triggered periodically. A value of 0 turns the callback off.
625941c391af0d3eaac9b9d3
def _addWall(self, map_object, cell, x, y, column, row): <NEW_LINE> <INDENT> cur_wall = wall.sokobanWall(self) <NEW_LINE> cur_wall.SetPoint(x, y) <NEW_LINE> self.RegDecor(cur_wall) <NEW_LINE> return cur_wall
Create wall object.
625941c3711fe17d8254232b
def brosok(guess, toss): <NEW_LINE> <INDENT> logging.debug('Начало подпрограммы.') <NEW_LINE> if guess == 'решка': <NEW_LINE> <INDENT> guess = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> guess = 1 <NEW_LINE> <DEDENT> logging.debug('guess = ' + str(guess) + ' toss = ' + str(toss)) <NEW_LINE> if toss == guess: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Функция проверки результата
625941c39f2886367277a84a
def run_experiment(): <NEW_LINE> <INDENT> demographics_input() <NEW_LINE> init_pygame_and_exp() <NEW_LINE> load_stimuli() <NEW_LINE> start_welcome_block() <NEW_LINE> start_inst1_block() <NEW_LINE> start_inst2_block() <NEW_LINE> start_begintask_block() <NEW_LINE> start_task() <NEW_LINE> start_endtask_block(1.0) <NEW_LINE> start_goodbye_block() <NEW_LINE> save_results(settings["filename"], results) <NEW_LINE> quit_pygame()
runs the experiment.
625941c3d99f1b3c44c6754d
def load_model(filename): <NEW_LINE> <INDENT> network = keras.models.load_model(filename) <NEW_LINE> return network
Loads an entire model Args: - filename: is the path of the file that the model should be loaded from Returns: the loaded model
625941c399fddb7c1c9de34e
def choose_action(self, actions, qvalues): <NEW_LINE> <INDENT> action = self._get_maxq_action(actions, qvalues) <NEW_LINE> if self._is_active: <NEW_LINE> <INDENT> self._tau *= self._decay <NEW_LINE> pmf = gibbs.pmf(np.asarray(qvalues), self._tau) <NEW_LINE> action = actions[np.random.choice(np.arange(len(np.asarray(qvalues))), p=pmf)] <NEW_LINE> <DEDENT> return action
Choose the next action. Choose the next action according to the Gibbs distribution. Parameters ---------- actions : list[Actions] The available actions. qvalues : list[float] The q-value for each action. Returns ------- Action : The action with maximum q-value that can be taken from the given state.
625941c3a4f1c619b28afff9
def human_bytes(n): <NEW_LINE> <INDENT> if n < 1024: <NEW_LINE> <INDENT> return '%d B' % n <NEW_LINE> <DEDENT> k = n/1024 <NEW_LINE> if k < 1024: <NEW_LINE> <INDENT> return '%d KB' % round(k) <NEW_LINE> <DEDENT> m = k/1024 <NEW_LINE> if m < 1024: <NEW_LINE> <INDENT> return '%.1f MB' % m <NEW_LINE> <DEDENT> g = m/1024 <NEW_LINE> return '%.2f GB' % g
Return the number of bytes n in more human readable form.
625941c301c39578d7e74df7
def __init__(self, entries, length_mi, route_id, route_name = None, elevation_gain_ft = None): <NEW_LINE> <INDENT> self.name = route_name <NEW_LINE> self.id = route_id <NEW_LINE> self.entries = entries <NEW_LINE> self.elevation_gain_ft = elevation_gain_ft <NEW_LINE> self.length_mi = length_mi
Inits the storage members of the class: - entries: A list of Entry objects - length_mi: The total length of the route, in miles. - route_id: The RWGPS route # for this route - route_name: The name of this route (Optional) - elevation_gain_ft : The amount of climb in this route, in ft (Optional)
625941c38e71fb1e9831d766
def __init__( self, *, name: str, type: Union[str, "RuleType"], definition: "ManagementPolicyDefinition", enabled: Optional[bool] = None, **kwargs ): <NEW_LINE> <INDENT> super(ManagementPolicyRule, self).__init__(**kwargs) <NEW_LINE> self.enabled = enabled <NEW_LINE> self.name = name <NEW_LINE> self.type = type <NEW_LINE> self.definition = definition
:keyword enabled: Rule is enabled if set to true. :paramtype enabled: bool :keyword name: Required. A rule name can contain any combination of alpha numeric characters. Rule name is case-sensitive. It must be unique within a policy. :paramtype name: str :keyword type: Required. The valid value is Lifecycle. Possible values include: "Lifecycle". :paramtype type: str or ~azure.mgmt.storage.v2021_01_01.models.RuleType :keyword definition: Required. An object that defines the Lifecycle rule. :paramtype definition: ~azure.mgmt.storage.v2021_01_01.models.ManagementPolicyDefinition
625941c3baa26c4b54cb10dd
def rename(self, curName, newName): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> i = self.__objNameList.index(curName) <NEW_LINE> self.__objNameList[i] = newName <NEW_LINE> self.__objCatalog[newName] = self.__objCatalog[curName] <NEW_LINE> self.__objCatalog[newName].setName(newName) <NEW_LINE> return True <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return False
Change the name of an object in place -
625941c344b2445a33932053
def test_get_image_id(self): <NEW_LINE> <INDENT> img_id = str(uuid.uuid4()) <NEW_LINE> img_name = 'myfakeimage' <NEW_LINE> self.my_image.id = img_id <NEW_LINE> self.my_image.name = img_name <NEW_LINE> self.sahara_client.images.get.return_value = self.my_image <NEW_LINE> self.sahara_client.images.find.side_effect = [[self.my_image], []] <NEW_LINE> self.assertEqual(img_id, self.sahara_plugin.get_image_id(img_id)) <NEW_LINE> self.assertEqual(img_id, self.sahara_plugin.get_image_id(img_name)) <NEW_LINE> self.assertRaises(exception.ImageNotFound, self.sahara_plugin.get_image_id, 'noimage') <NEW_LINE> calls = [mock.call(name=img_name), mock.call(name='noimage')] <NEW_LINE> self.sahara_client.images.get.assert_called_once_with(img_id) <NEW_LINE> self.sahara_client.images.find.assert_has_calls(calls)
Tests the get_image_id function.
625941c338b623060ff0adaa
def merge_station_data( stats, var_name, pref_attr=None, sort_by_largest=True, fill_missing_nan=True, add_meta_keys=None, resample_how=None, min_num_obs=None, ): <NEW_LINE> <INDENT> if isinstance(var_name, list): <NEW_LINE> <INDENT> if len(var_name) > 1: <NEW_LINE> <INDENT> raise NotImplementedError("Merging of multivar data not yet possible") <NEW_LINE> <DEDENT> var_name = var_name[0] <NEW_LINE> <DEDENT> stats, is_3d, has_errs = _check_stats_merge(stats, var_name, pref_attr, fill_missing_nan) <NEW_LINE> if is_3d: <NEW_LINE> <INDENT> merged = _merge_stats_3d(stats, var_name, add_meta_keys, has_errs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> merged = _merge_stats_2d( stats, var_name, sort_by_largest, pref_attr, add_meta_keys, resample_how, min_num_obs ) <NEW_LINE> <DEDENT> if fill_missing_nan: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> merged.insert_nans_timeseries(var_name) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.warning( f"Could not insert NaNs into timeseries of variable {var_name} " f"after merging stations. Reason: {repr(e)}" ) <NEW_LINE> <DEDENT> <DEDENT> merged["stat_merge_pref_attr"] = pref_attr <NEW_LINE> return merged
Merge multiple StationData objects (from one station) into one instance Note ---- all input :class:`StationData` objects need to have same attributes ``station_name``, ``latitude``, ``longitude`` and ``altitude`` Parameters ---------- stats : list list containing :class:`StationData` objects (note: all of these objects must contain variable data for the specified input variable) var_name : str data variable name that is to be merged pref_attr optional argument that may be used to specify a metadata attribute that is available in all input :class:`StationData` objects and that is used to order the input stations by relevance. The associated values of this attribute need to be sortable (e.g. revision_date). This is only relevant in case overlaps occur. If unspecified the relevance of the stations is sorted based on the length of the associated data arrays. sort_by_largest : bool if True, the result from the sorting is inverted. E.g. if ``pref_attr`` is unspecified, then the stations will be sorted based on the length of the data vectors, starting with the shortest, ending with the longest. This sorting result will then be inverted, if ``sort_by_largest=True``, so that the longest time series get's highest importance. If, e.g. ``pref_attr='revision_date'``, then the stations are sorted by the associated revision date value, starting with the earliest, ending with the latest (which will also be inverted if this argument is set to True) fill_missing_nan : bool if True, the resulting time series is filled with NaNs. NOTE: this requires that information about the temporal resolution (ts_type) of the data is available in each of the StationData objects. add_meta_keys : str or list, optional additional non-standard metadata keys that are supposed to be considered for merging. resample_how : str or dict, optional in case input stations come in different frequencies they are merged to the lowest common freq. This parameter can be used to control, which aggregator(s) are to be used (e.g. mean, median). min_num_obs : str or dict, optional in case input stations come in different frequencies they are merged to the lowest common freq. This parameter can be used to control minimum number of observation constraints for the downsampling. Returns ------- StationData merged data
625941c3d164cc6175782d0a
def begin(self, now=None, batchSize=None, inTransaction=False): <NEW_LINE> <INDENT> log.info("Maintenance window %s starting" % self.displayName()) <NEW_LINE> if not now: <NEW_LINE> <INDENT> now = time.time() <NEW_LINE> <DEDENT> self.started = now <NEW_LINE> self.setProdState(self.startProductionState, batchSize=batchSize, inTransaction=inTransaction)
Hook for entering the Maintenance Window: call if you override
625941c3cc40096d6159590d
def int_pair(s, default=(0, None)): <NEW_LINE> <INDENT> s = re.split(r'[^0-9]+', str(s).strip()) <NEW_LINE> if len(s) and len(s[0]): <NEW_LINE> <INDENT> if len(s) > 1 and len(s[1]): <NEW_LINE> <INDENT> return (int(s[0]), int(s[1])) <NEW_LINE> <DEDENT> return (int(s[0]), default[1]) <NEW_LINE> <DEDENT> return default
Return the digits to either side of a single non-digit character as a 2-tuple of integers >>> int_pair('90210-007') (90210, 7) >>> int_pair('04321.0123') (4321, 123)
625941c373bcbd0ca4b2c032
@pytest.mark.parametrize('fmt,path', get_cases(bconv.LOADERS), ids=path_id) <NEW_LINE> def test_loads(fmt, path, expected): <NEW_LINE> <INDENT> with xopen(path, fmt) as f: <NEW_LINE> <INDENT> parsed = bconv.loads(f.read(), fmt, id=path.stem) <NEW_LINE> <DEDENT> _validate(parsed, fmt, expected)
Test the loads function.
625941c3460517430c394146
def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'id_estabelecimento': 'int', 'id_adquirente': 'int', 'codigo_estabelecimento_adquirente': 'str' } <NEW_LINE> self.attribute_map = { 'id_estabelecimento': 'idEstabelecimento', 'id_adquirente': 'idAdquirente', 'codigo_estabelecimento_adquirente': 'codigoEstabelecimentoAdquirente' } <NEW_LINE> self._id_estabelecimento = None <NEW_LINE> self._id_adquirente = None <NEW_LINE> self._codigo_estabelecimento_adquirente = None
VinculoEstabelecimentoAdquirentePersist - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition.
625941c3cdde0d52a9e52fed
@app.route('/logout') <NEW_LINE> def logout(): <NEW_LINE> <INDENT> session.pop('logged_in', None) <NEW_LINE> oauth_provider = session.pop('oauth_provider', None) <NEW_LINE> if oauth_provider: <NEW_LINE> <INDENT> if 'google' in oauth_provider: <NEW_LINE> <INDENT> gdisconnect() <NEW_LINE> <DEDENT> elif 'facebook' in oauth_provider: <NEW_LINE> <INDENT> fbdisconnect() <NEW_LINE> <DEDENT> <DEDENT> return redirect(url_for('home'))
this view will be used to log out the user
625941c321bff66bcd684911
def create_app(config_file: Optional[Union[str, PurePath]] = None) -> Flask: <NEW_LINE> <INDENT> app = Flask(__name__) <NEW_LINE> app.config.from_object('commandment.default_settings') <NEW_LINE> if config_file is not None: <NEW_LINE> <INDENT> app.config.from_pyfile(config_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> app.config.from_envvar('COMMANDMENT_SETTINGS') <NEW_LINE> <DEDENT> db.init_app(app) <NEW_LINE> oauth2.init_app(app) <NEW_LINE> app.register_blueprint(auth_app) <NEW_LINE> app.register_blueprint(enroll_app, url_prefix='/enroll') <NEW_LINE> app.register_blueprint(mdm_app) <NEW_LINE> app.register_blueprint(configuration_app, url_prefix='/api/v1/configuration') <NEW_LINE> app.register_blueprint(api_app, url_prefix='/api') <NEW_LINE> app.register_blueprint(api_push_app, url_prefix='/api') <NEW_LINE> app.register_blueprint(flat_api, url_prefix='/api') <NEW_LINE> app.register_blueprint(profiles_api_app, url_prefix='/api') <NEW_LINE> app.register_blueprint(applications_api, url_prefix='/api') <NEW_LINE> app.register_blueprint(oauth_app, url_prefix='/oauth') <NEW_LINE> app.register_blueprint(saml_app, url_prefix='/saml') <NEW_LINE> app.register_blueprint(omdm_app, url_prefix='/omdm') <NEW_LINE> app.register_blueprint(ac2_app) <NEW_LINE> app.register_blueprint(dep_app) <NEW_LINE> app.register_blueprint(vpp_app) <NEW_LINE> @app.route('/') <NEW_LINE> def index(): <NEW_LINE> <INDENT> return render_template('index.html') <NEW_LINE> <DEDENT> @app.errorhandler(404) <NEW_LINE> def send_index(path: str): <NEW_LINE> <INDENT> return render_template('index.html') <NEW_LINE> <DEDENT> return app
Create the Flask Application. Configuration is looked up the following order: - default_settings.py in the commandment package. - config_file parameter passed to this factory method. - environment variable ``COMMANDMENT_SETTINGS`` pointing to a .cfg file. Args: config_file (Union[str, PurePath]): Path to configuration file. Returns: Instance of the flask application
625941c31b99ca400220aa6d
def calculate_grid_position(index, start_position = (0, 0)): <NEW_LINE> <INDENT> return ( BORDER + (index % PREFERRED_WIDTH + 1) * GRID - GRID / 2, BORDER + int(index / PREFERRED_WIDTH + 1) * GRID - GRID / 2, )
Determines the position of an item in a simple grid, based on default values defined here
625941c32eb69b55b151c869
def p_program(p): <NEW_LINE> <INDENT> if len(p) == 3: <NEW_LINE> <INDENT> p[0] = Node("program", [p[1], p[2]]) <NEW_LINE> <DEDENT> elif len(p) == 2: <NEW_LINE> <INDENT> p[0] = Node("program", [p[1]])
program : program stmt_list | stmt_list
625941c38c0ade5d55d3e975