code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def read_sentence_col_raw(file_stream): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> first_line = file_stream.next() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> first_line = "" <NEW_LINE> <DEDENT> data_block = {} <NEW_LINE> data_block['paper_id'] = first_line.strip() <NEW_LINE> data_block['data_block'] = "" <NEW_LI...
Recives read a POS tagged sentence in the format described below and returns a dictionary with the paper_id and the block of data as an unique string. Keyword arguments: file_stream -- File stream of the data. Return if there are tokens after a paper_id: { 'paper_id': "some_string", 'data_block': "data bl...
625941e8a4f1c619b28b04c1
def test_make_profile_private(self): <NEW_LINE> <INDENT> username, user_id = self.log_in_as_unique_user() <NEW_LINE> profile_page = self.visit_profile_page(username, privacy=self.PRIVACY_PUBLIC) <NEW_LINE> with self.verify_pref_change_event_during( username, user_id, 'account_privacy', old=None, new=self.PRIVACY_PRIVAT...
Scenario: Verify that the user can change their privacy. Given that I am a registered user And I visit my public profile page And I set the profile visibility to private Then a user preference changed event should be recorded When I reload the page Then the profile visibility should be shown as private
625941e894891a1f4081bf3e
def cross_entropy(y_hat,y): <NEW_LINE> <INDENT> y = tf.cast(tf.reshape(y,shape=(-1,1)),dtype=tf.int32) <NEW_LINE> y = tf.one_hot(y,depth=y_hat.shape[-1]) <NEW_LINE> y = tf.cast(tf.reshape(y, shape=[-1, y_hat.shape[-1]]),dtype=tf.int32) <NEW_LINE> return -tf.math.log(tf.boolean_mask(y_hat, y)+1e-8)
计算交叉熵 :param y_hat: np.array([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]]) :param y:np.array([0, 2], dtype='int32') :return:
625941e8ff9c53063f47c684
def score_results(testing_dataset, labels, num_clusters, save_fig=False): <NEW_LINE> <INDENT> conf_matrix = sklearn.metrics.confusion_matrix(testing_dataset.values[:,NUM_FEATURES], labels) <NEW_LINE> total_pts = len(testing_dataset) <NEW_LINE> correct_pts = np.trace(conf_matrix) <NEW_LINE> score = correct_pts/total_pts...
Learning evaluation function. Computes the confusion matrix and the average score Args: testing_dataset (pd.Dataframe): testing dataset labels (list[int]): labels for the testing dataset num_clusters (int): number of clusters used (display purpose only) save_fig (bool, optional): Defaults to False. Whe...
625941e85fcc89381b1e1b55
def get_item(self, item_title): <NEW_LINE> <INDENT> return self.session.query(Item).filter(Item.title == item_title).one()
get_latest_items: Returns a specific item Args: item_title (data type: str): The item's title Returns: An item object
625941e84f6381625f114ecf
def return_path(current_node,maze): <NEW_LINE> <INDENT> path = [] <NEW_LINE> rows, columns = np.shape(maze) <NEW_LINE> result = [[-1 for i in range(columns)] for j in range(rows)] <NEW_LINE> current = current_node <NEW_LINE> while current is not None: <NEW_LINE> <INDENT> path.append(current.position) <NEW_LINE> current...
Esta funcion devuelve el camino que se ha recorrido desde el principio hasta un nodo actual. Se inicializa el tablero con -1, para luego escribir el camino encontrado y devolverlo
625941e871ff763f4b549b27
def stop(self): <NEW_LINE> <INDENT> if self._timer: <NEW_LINE> <INDENT> self._timer.cancel()
Cleans up the timer when the plotter is running in test mode.
625941e891af0d3eaac9beb0
def setUp(self): <NEW_LINE> <INDENT> self.ir = ImgRes(width=1920, height=1080)
Get a new ImgRes object for each test.
625941e8dc8b845886cb59ca
def __init__( self, reduction: str = 'elementwise_mean', ): <NEW_LINE> <INDENT> super().__init__(name='rmse') <NEW_LINE> self.reduction = reduction
Args: reduction: a method for reducing mse over labels (default: takes the mean) Available reduction methods: - elementwise_mean: takes the mean - none: pass array - sum: add elements
625941e860cbc95b062c69d7
def _is_current_page(self): <NEW_LINE> <INDENT> self.selenium.wait_until_location_contains(f"/lightning/r/Account/",timeout=60, message="Current page is not an Account record detail view")
Verify we are on the Account detail page by verifying that the url contains '/view'
625941e8a79ad161976cc5d9
def main(): <NEW_LINE> <INDENT> print('Creating folders') <NEW_LINE> create_folders() <NEW_LINE> print('Cloning git repos') <NEW_LINE> git_clones() <NEW_LINE> print('Miscellaneous') <NEW_LINE> misc()
Make it so
625941e821bff66bcd684de1
def pull_cdp_neighbor(self, activeSession): <NEW_LINE> <INDENT> command = self.cmd_cdp_neighbor() <NEW_LINE> result = self.get_cmd_output(command, activeSession) <NEW_LINE> return self.cleanup_cdp_neighbor_output(result)
Retrieve CDP/LLDP neighbor information from device. This should be redone using XML pulls/parsing.
625941e8adb09d7d5db6cc20
def _create_dynamic_handlers(self, host, endpoint, endpoint_definition, app_ctx): <NEW_LINE> <INDENT> return host, [ (endpoint, DynamicHandler, dict( endpoint_definition=endpoint_definition, endpoint=endpoint, after_request_funcs=self.after_request_funcs, error_handler_funcs=self.error_handlers, before_request_funcs=se...
Creates dynamic handler and sets all pipeline functions as a dictionary which will be injected to dynamic handler.
625941e867a9b606de4a834a
def get_json_mapping(mode): <NEW_LINE> <INDENT> root = ['jobs', 0] <NEW_LINE> jobOptions = root + ['job options'] <NEW_LINE> data = root + [mode] <NEW_LINE> dictionary = { 'iodepth': (jobOptions + ['iodepth']), 'numjobs': (jobOptions + ['numjobs']), 'rw': (jobOptions + ['rw']), 'iops': (data + ['iops']), 'iops_stddev':...
This function contains a hard-coded mapping of FIO nested JSON data to a flat dictionary.
625941e88e05c05ec3eea80c
def output_integration(self, h1, c2, g2, h2): <NEW_LINE> <INDENT> if self.multiplicative_excitation: <NEW_LINE> <INDENT> e = self.gamma * c2 <NEW_LINE> a = self.kappa * (h1 + e) <NEW_LINE> m = self.omega * (h1 * e) <NEW_LINE> h2_hat = self.recurrent_nl(a + m) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> h2_hat = self....
Integration on the output.
625941e82c8b7c6e89b35c50
def test_push_loom_loom(self): <NEW_LINE> <INDENT> source = self.get_tree_with_loom('source') <NEW_LINE> source.branch.new_thread('bottom') <NEW_LINE> source.branch.new_thread('top') <NEW_LINE> source.branch._set_nick('bottom') <NEW_LINE> source.branch.record_loom('commit to loom') <NEW_LINE> target = source.controldir...
Pushing a loom to a loom copies the current loom state.
625941e8460517430c39460c
def preorderTraversal(self, root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> tmp = [root.val] <NEW_LINE> if root.left: <NEW_LINE> <INDENT> tmp += self.preorderTraversal(root.left) <NEW_LINE> <DEDENT> if root.right: <NEW_LINE> <INDENT> tmp += self.preorderTraversal(root.right) <N...
:type root: TreeNode :rtype: List[int]
625941e8b830903b967e9d99
def initialize( self, layout, numGhostAgents ): <NEW_LINE> <INDENT> self.food = layout.food.copy() <NEW_LINE> self.capsules = layout.capsules[:] <NEW_LINE> self.layout = layout <NEW_LINE> self.score = 500 <NEW_LINE> self.scoreChange = 0 <NEW_LINE> self.agentStates = [] <NEW_LINE> numGhosts = 0 <NEW_LINE> for isPacman, ...
Creates an initial game state from a layout array (see layout.py).
625941e829b78933be1e5b3a
def read_passive_target(self, card_baud=PN532_MIFARE_ISO14443A, timeout_sec=1, as_hex=False): <NEW_LINE> <INDENT> response = self.call_function(PN532_COMMAND_INLISTPASSIVETARGET, params=[0x01, card_baud], response_length=17) <NEW_LINE> if response is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if response...
Wait for a MiFare card to be available and return its UID when found. Will wait up to timeout_sec seconds and return None if no card is found, otherwise a bytearray with the UID of the found card is returned.
625941e823e79379d52ee9f1
def install(self, *args): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description=self.install.__doc__, prog="conan", formatter_class=RawTextHelpFormatter) <NEW_LINE> parser.add_argument("reference", nargs='?', default="", help='reference name or path to conanfile file, ' 'e.g., openssl/1.0.2@lasote/testing or...
install in the local store the given requirements. Requirements can be defined in the command line or in a conanfile. EX: conans install opencv/2.4.10@lasote/testing
625941e88c0ade5d55d3ee52
def test_write_missing_rng_algorithm(self): <NEW_LINE> <INDENT> rng_parameters = objects.RNGParameters() <NEW_LINE> args = (utils.BytearrayStream(), ) <NEW_LINE> self.assertRaisesRegex( exceptions.InvalidField, "The RNGParameters structure is missing the RNG algorithm field.", rng_parameters.write, *args )
Test that an InvalidField error is raised during the encoding of an RNGParameters structure when the structure is missing the RNG algorithm field.
625941e821a7993f00bc818b
def test_jsonify(): <NEW_LINE> <INDENT> assert view.jsonify(True) == 'true' <NEW_LINE> assert view.jsonify({'foo': 'bar'}) == '{"foo": "bar"}'
Test the ability to jsonify an object
625941e8167d2b6e31219028
def _insertMany(table, values, returning): <NEW_LINE> <INDENT> builder = InsertBuilder() <NEW_LINE> assert isinstance(values, list) <NEW_LINE> for e in values: <NEW_LINE> <INDENT> builder.add(e) <NEW_LINE> <DEDENT> returning = sql_columns(returning) <NEW_LINE> sql = ( f"INSERT INTO {table} ({builder.names()}) " f"VALUE...
Allows to insert multiple values into a table.
625941e830bbd722463cc25c
def generate_function_pointer_declarations(functions): <NEW_LINE> <INDENT> lines = [] <NEW_LINE> lines.append("/* Dynamic functions. */") <NEW_LINE> lines.extend(generate_single_type_function_pointer_declarations( getFunctionsWithType(functions, 'DYNAMIC'))) <NEW_LINE> lines.append("\n/* Functions with wrappers. */") <...
Same as above, but groups functions based on their type.
625941e87cff6e4e81117e19
def Ligne_stations(self): <NEW_LINE> <INDENT> A ={} <NEW_LINE> for cle in self.ligne : <NEW_LINE> <INDENT> A[cle]= self.ligne[cle][0] <NEW_LINE> <DEDENT> return A
Dictionnaire de Lignes: stations
625941e85166f23b2e1a55ed
def extract_table_identifiers(token_stream, allow_functions=True): <NEW_LINE> <INDENT> def parse_identifier(item): <NEW_LINE> <INDENT> name = item.get_real_name() <NEW_LINE> schema_name = item.get_parent_name() <NEW_LINE> alias = item.get_alias() <NEW_LINE> if not name: <NEW_LINE> <INDENT> schema_name = None <NEW_LINE>...
yields tuples of TableReference namedtuples
625941e856b00c62f0f14af0
def __init__(self, xml, **kwargs): <NEW_LINE> <INDENT> inning_tag = xml if type(xml) == ELEMENT_TAG else BS(xml, "lxml").find("inning") <NEW_LINE> self.inning_tag = inning_tag <NEW_LINE> for attr in inning_tag.attrs: <NEW_LINE> <INDENT> if attr in Inning.INN_ATTRS: <NEW_LINE> <INDENT> self.__dict__[attr] = inning_tag[a...
Params ------ xml : string | bs4.element.Tag instance
625941e8293b9510aa2c3725
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, OutboxFileChanges): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941e8baa26c4b54cb15af
def cmd_service_info(self): <NEW_LINE> <INDENT> return self.uc.srvmsg( { 'service:common.Service-Message': { 'common.Service-Message-Type': common.Message.INFO } }, service.namespace_id )
query services information
625941e8e1aae11d1e74a150
@pytest.mark.parametrize("dim", [1, 2, 3]) <NEW_LINE> @pytest.mark.parametrize("nspecies", [0, 10]) <NEW_LINE> def test_uniform_init(ctx_factory, dim, nspecies): <NEW_LINE> <INDENT> cl_ctx = ctx_factory() <NEW_LINE> queue = cl.CommandQueue(cl_ctx) <NEW_LINE> actx = PyOpenCLArrayContext(queue) <NEW_LINE> nel_1d = 4 <NEW...
Test the uniform flow initializer. Simple test to check that uniform initializer creates the expected solution field.
625941e8ec188e330fd5ac29
@contextmanager <NEW_LINE> def stdout_redirected(to=os.devnull, stdout=None): <NEW_LINE> <INDENT> if stdout is None: <NEW_LINE> <INDENT> stdout = sys.stdout <NEW_LINE> <DEDENT> stdout_fd = fileno(stdout) <NEW_LINE> with os.fdopen(os.dup(stdout_fd), 'wb') as copied: <NEW_LINE> <INDENT> stdout.flush() <NEW_LINE> try: <NE...
From: http://stackoverflow.com/questions/4675728/ redirect-stdout-to-a-file-in-python/22434262#22434262
625941e891af0d3eaac9beb1
def byte_mulx(b): <NEW_LINE> <INDENT> return b << 1 if b & 128 == 0 else (b << 1) ^ _m
Returns the product of the polynomial representation of (int) byte B and x in GF(2^8). >>> x = byte_mulx(0x57) >>> x == 0xae True >>> x = byte_mulx(x) >>> x == 0x47 True >>> x = byte_mulx(x) >>> x == 0x8e True >>> byte_mulx(x) == 0x07 True
625941e8cc40096d61595de2
def kron_prod(matList): <NEW_LINE> <INDENT> ret = matList[0] <NEW_LINE> for i in range(1, len(matList)): <NEW_LINE> <INDENT> ret = kron(ret, matList[i]) <NEW_LINE> <DEDENT> return ret
Returns the kronecker product of the matrices in matList
625941e8090684286d50f180
def shelter(): <NEW_LINE> <INDENT> tablename = "cr_shelter" <NEW_LINE> table = s3db[tablename] <NEW_LINE> if deployment_settings.has_module("req"): <NEW_LINE> <INDENT> s3mgr.load("req_req") <NEW_LINE> <DEDENT> field = s3db.pr_presence.shelter_id <NEW_LINE> field.requires = IS_NULL_OR(IS_ONE_OF(db, "cr_shelter.id", "%(n...
RESTful CRUD controller >>> resource="shelter" >>> from applications.sahana.modules.s3_test import WSGI_Test >>> test=WSGI_Test(db) >>> "200 OK" in test.getPage("/sahana/%s/%s" % (module,resource)) True >>> test.assertHeader("Content-Type", "text/html") >>> test.assertInBody("List Shelters") >>> "200 OK" in test.getPa...
625941e8ec188e330fd5ac2a
def validate_block(response_json: dict) -> bool: <NEW_LINE> <INDENT> inner_key_name_of_block = ["version", "prev_block_hash","merkle_tree_root_hash","time_stamp","confirmed_transaction_list"] <NEW_LINE> is_valid = response_json["result"]["response_code"] is 0 and has_keys(response_json["result"]["block"],...
Check the response json of the block has right format. :param response_json :return: bool
625941e80c0af96317bb867c
def irfftn(a, shape=None, axes=None): <NEW_LINE> <INDENT> a_shape, v_shape, axes, slices, u, v = _irfftn_preparations(a, shape, axes) <NEW_LINE> has_smaller_axis = any(s1 < s2 for s1, s2 in zip(a_shape, v_shape)) <NEW_LINE> has_larger_axis = any(s1 > s2 for s1, s2 in zip(a_shape, v_shape)) <NEW_LINE> return _ifftn(has_...
Returns a planned function that computes the N-D DFT of a real-valued array. Parameters ---------- a : array-like or shape An input array or its shape. shape : Optional[sequence of ints] Number of FFT points. Default is input size along specified axes axes : Optional[sequence of ints] Axes along which to p...
625941e826238365f5f0f309
def __init__(self, block, n, dir): <NEW_LINE> <INDENT> Element.__init__(self, block) <NEW_LINE> self._name = n['name'] <NEW_LINE> self._key = n['key'] <NEW_LINE> self._type = n['type'] <NEW_LINE> self._hide = n.find('hide') or '' <NEW_LINE> self._dir = dir
Make a new port from nested data. Args: block: the parent element n: the nested odict dir: the direction source or sink
625941e8fff4ab517eb2f8d3
def testOneProperty(self): <NEW_LINE> <INDENT> read = AARead('id', 'AI') <NEW_LINE> self.assertEqual( { 'hydropathy': [0.4, 1.0], }, propertiesForSequence(read, ['hydropathy']))
If one property is wanted, a dict with the property must be returned, and have the expected property values.
625941e866673b3332b92525
def disconnect(self): <NEW_LINE> <INDENT> self.handler.busy() <NEW_LINE> self.connected = False <NEW_LINE> self.enableUI() <NEW_LINE> self.connectMenu.entryconfig(0,label="Connect", state=NORMAL, command=self.connect) <NEW_LINE> self.handler.disconnect() <NEW_LINE> self.handler.notbusy()
Event handler for changing connection status.
625941e8009cb60464c63842
def _has_expired(self): <NEW_LINE> <INDENT> expired = False <NEW_LINE> if hasattr(self, 'Expiration'): <NEW_LINE> <INDENT> now = datetime.datetime.utcnow() <NEW_LINE> expiration = datetime.datetime.strptime(self.Expiration, '%Y-%m-%dT%H:%M:%SZ') <NEW_LINE> expired = (now >= expiration) <NEW_LINE> <DEDENT> else: <NEW_LI...
Has this HIT expired yet?
625941e85510c4643540f86c
def resample(self, A): <NEW_LINE> <INDENT> self._resample_L(A) <NEW_LINE> self._resample_mu_0(A) <NEW_LINE> self._resample_mu_self(A)
Resample the parameters of the distribution given the observed graphs. :param data: :return:
625941e83617ad0b5ed6838b
def ddpm_sample(self, x_T, predictor): <NEW_LINE> <INDENT> x_t = x_T <NEW_LINE> for t in range(1, self.num_steps + 1)[::-1]: <NEW_LINE> <INDENT> ts = np.array([t] * x_T.shape[0]) <NEW_LINE> alphas = self.alphas_for_ts(ts) <NEW_LINE> x_t = self.ddpm_previous(x_t, ts, predictor.predict_epsilon(x_t, alphas)) <NEW_LINE> <D...
Sample x_0 from x_t using DDPM. Usage is the same as ddim_sample().
625941e80fa83653e465744c
def add_impulse_to_body(self,key,impulse,vector=[0,1,0]): <NEW_LINE> <INDENT> force = self.world.impulseToForce(self.stepsize,[impulse*v for v in vector]) <NEW_LINE> self.bodies[key].addRelForce([force[0],force[1],force[2]]) <NEW_LINE> return force
Add an impulse to a body. Args: key: body id to add force to impulse: the impulse to add to the body vector: axis along which to add the force to the body
625941e85fdd1c0f98dc06c9
def relu_ai(lst): <NEW_LINE> <INDENT> return [0 if n < 0 else n for n in lst]
shows negative numbers as 0 and positive numbers as it is: like Relu function
625941e8cc40096d61595de3
def plot_weight_map(self, out_file=None): <NEW_LINE> <INDENT> image_size = self.network.options.get('image_size', (28, 28)) <NEW_LINE> output_number = self.network.OUTPUT.size <NEW_LINE> cols = ceil(sqrt(output_number)) <NEW_LINE> w = torchvision.utils.make_grid(self.weights.cpu().view(1, *image_size, -1).permute(3, 0,...
Plots weight map.
625941e876e4537e8c351b0a
def SpecializedForm(formModel, myModel, queryGenerator=None): <NEW_LINE> <INDENT> tmpFormClass = type('tmpForm', (formModel,), dict()) <NEW_LINE> def initMethod(self, *args, **kwargs): <NEW_LINE> <INDENT> if queryGenerator: <NEW_LINE> <INDENT> kwargs['queryGenerator'] = queryGenerator <NEW_LINE> <DEDENT> formModel.__in...
Returns form class using the given model, so you don't have to pass the model to the constructor. Helps with formsets
625941e844b2445a33932527
def is_mammal(text): <NEW_LINE> <INDENT> return text == 'cat' or text == 'dog'
Return true if text is mammal.
625941e8be383301e01b5911
def get_storage_root(self): <NEW_LINE> <INDENT> return self._storage_root_path
Local storages are defined in the Shotgun preferences. This method returns the local OS path that is associated with the local storage that this project node is associated with. (By default, this is the primary storage, but if you have a multi root config, there may be more than one project node.)
625941e807d97122c4178d2a
def move_up(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not _driver.connected: <NEW_LINE> <INDENT> msg = 'Driver nao conectado.' <NEW_LINE> _QMessageBox.critical( self, 'Falha', msg, _QMessageBox.Ok ) <NEW_LINE> return False <NEW_LINE> <DEDENT> self.ui.pbt_up.setStyleSheet(self.button_on_stylesheet) <NEW_LIN...
Start continuous upward move of vertical motor
625941e8c432627299f050de
def run_case(self, testcase: DataDrivenTestCase) -> None: <NEW_LINE> <INDENT> options = infer_ir_build_options_from_test_name(testcase.name) <NEW_LINE> if options is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> with use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase): <NEW_LINE> <I...
Perform a runtime checking transformation test case.
625941e8dc8b845886cb59cb
def display_logo(self): <NEW_LINE> <INDENT> self.plot(NXdata(logo, title='NeXpy'), image=True) <NEW_LINE> self.ax.xaxis.set_visible(False) <NEW_LINE> self.ax.yaxis.set_visible(False) <NEW_LINE> self.ax.title.set_visible(False) <NEW_LINE> self.draw()
Display the NeXpy logo in the plotting pane.
625941e88c3a873295158855
def _getVolumeId(self): <NEW_LINE> <INDENT> return self._volumeId
Property target used to get the volume id.
625941e866656f66f7cbc641
def postorderTraversalOne(root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> res, stack = [], [root] <NEW_LINE> while stack: <NEW_LINE> <INDENT> node = stack.pop() <NEW_LINE> res.append(node.val) <NEW_LINE> if node.left: <NEW_LINE> <INDENT> stack.append(node.left) <NEW_LINE> <DEDE...
145. 二叉树的后序遍历 前序遍历思路:中右左,然后逆序输出 :type root: TreeNode :rtype: List[int]
625941e80a50d4780f66732a
def build_site_structure(repository_map): <NEW_LINE> <INDENT> sitepages = {} <NEW_LINE> for repo in repository_map: <NEW_LINE> <INDENT> sitepages[repo.sitesection] = {} <NEW_LINE> for sourcepage in repo.sources: <NEW_LINE> <INDENT> filename = '%s.rst' % sourcepage.title <NEW_LINE> filename = filename.replace('\::', '_'...
Make a mapping of files with their new names for the website.
625941e876e4537e8c351b0b
def function_(_arg): <NEW_LINE> <INDENT> pass
Function
625941e8d6c5a102081444e3
def get_closests(df: pd.DataFrame, col: int, val: int) -> Tuple[int, int]: <NEW_LINE> <INDENT> lower_idx = bisect_left(df[col].values, val) <NEW_LINE> higher_idx = bisect_right(df[col].values, val) <NEW_LINE> if higher_idx == lower_idx: <NEW_LINE> <INDENT> return lower_idx - 1, lower_idx <NEW_LINE> <DEDENT> else: <NEW_...
find the closet value in th edataframe
625941e8462c4b4f79d1db64
def train(self, train_data=None, validate_data=None): <NEW_LINE> <INDENT> print('========== TRAIN:') <NEW_LINE> if train_data is None: <NEW_LINE> <INDENT> train_data = self.data.dataset['train'] <NEW_LINE> <DEDENT> if validate_data is None: <NEW_LINE> <INDENT> validate_data = self.data.dataset['validate'] <NEW_LINE> <D...
Parameters ---------- train_data: None, tf.data.Dataset Training dataset. If ``None``, use the default dataset ``self.data.dataset['train']``. validate_data: None, tf.data.Dataset Validation dataset. If ``None``, use the default dataset ``self.data.dataset['validate']``.
625941e8cc0a2c11143dd327
def _invert(self): <NEW_LINE> <INDENT> self.phi2 = np.abs(self.phi)**2 <NEW_LINE> self.gphi2h = -self.wv2*self.fft(self.phi2) <NEW_LINE> self.qwh = 0.5*(0.5*self.gphi2h + self.jacobian_phic_phi())/self.f <NEW_LINE> self.qwh *= self.filtr <NEW_LINE> self.pw = self.ifft((self.wv2i*self.qwh)).real <NEW_LINE> self.pv = se...
Calculate the streamfunction given the potential vorticity. The algorithm is: 1) Calculate wave potential vorticity 2) Invert for wave, pw, and vortex stremfunctions, pv. 3) Calculate geostrophic stremfunction, p = pv+pw.
625941e807f4c71912b11919
def _pl(self, varidx, w): <NEW_LINE> <INDENT> var = self.mrf.variable(varidx) <NEW_LINE> values = var.valuecount() <NEW_LINE> gfs = self._varidx2fidx.get(varidx) <NEW_LINE> if gfs is None: <NEW_LINE> <INDENT> p = 1.0 / values <NEW_LINE> return [p] * values <NEW_LINE> <DEDENT> sums = [0] * values <NEW_LINE> for fidx in ...
Computes the pseudo-likelihoods for the given variable under weights w.
625941e8566aa707497f49f7
def load_maps(maps_dir): <NEW_LINE> <INDENT> maps_dir = os.path.abspath(maps_dir) <NEW_LINE> maps = {} <NEW_LINE> for root, dirnames, filenames in os.walk(maps_dir): <NEW_LINE> <INDENT> for filename in filenames: <NEW_LINE> <INDENT> if filename.endswith(".xml"): <NEW_LINE> <INDENT> xml_file = os.path.join(root, filenam...
Load all xml map sources from a given directory. Args: maps_dir: path to directory to search for maps Returns: dict of MapSource:
625941e8cad5886f8bd2746d
def run_traceback(level, textview_only=False, text_only=False): <NEW_LINE> <INDENT> from ubuntutweak.gui import GuiBuilder <NEW_LINE> output = StringIO.StringIO() <NEW_LINE> exc = traceback.print_exc(file=output) <NEW_LINE> worker = GuiBuilder('traceback.ui') <NEW_LINE> textview = worker.get_object('%s_view' % level) <...
Two level: fatal and error
625941e87b25080760e398eb
def url(self, path): <NEW_LINE> <INDENT> return self.url_base + ('' if self.url_base.endswith('/') else '/') + path
Get asset URL
625941e81f037a2d8b946692
def __init__(self): <NEW_LINE> <INDENT> self.label = "Create GRG From Point" <NEW_LINE> self.description = "Create a Gridded Reference Graphic (GRG) from an selected location on the map." <NEW_LINE> self.category = "Gridded Reference Graphic"
Point Target GRG constructor
625941e88e05c05ec3eea80d
@contextlib.contextmanager <NEW_LINE> def tqdm_unwrap_stdout(): <NEW_LINE> <INDENT> saved = sys.stdout <NEW_LINE> sys.stdout = _STREAMS.stdout_stack.pop() <NEW_LINE> yield <NEW_LINE> _STREAMS.stdout_stack.append(sys.stdout) <NEW_LINE> sys.stdout = saved
Unwrap a tqdm.write and funnel it to sys.stdout
625941e8be7bc26dc91cda8c
def read_clipboard(sep='\s+', **kwargs): <NEW_LINE> <INDENT> encoding = kwargs.pop('encoding', 'utf-8') <NEW_LINE> if encoding is not None and encoding.lower().replace('-', '') != 'utf8': <NEW_LINE> <INDENT> raise NotImplementedError( 'reading from clipboard only supports utf-8 encoding') <NEW_LINE> <DEDENT> from panda...
Read text from clipboard and pass to read_table. See read_table for the full argument list Parameters ---------- sep : str, default '\s+'. A string or regex delimiter. The default of '\s+' denotes one or more whitespace characters. Returns ------- parsed : DataFrame
625941e83d592f4c4ed1d4f6
def ComponentProgram(env, prog_name, *args, **kwargs): <NEW_LINE> <INDENT> env = _ComponentPlatformSetup(env, 'ComponentProgram', **kwargs) <NEW_LINE> env['PROGRAM_BASENAME'] = prog_name <NEW_LINE> out_nodes = env.Program(prog_name, *args, **kwargs) <NEW_LINE> env.Depends(out_nodes, env['INCLUDES']) <NEW_LINE> env.Publ...
Pseudo-builder for program to handle platform-dependent type. Args: env: Environment in which we were called. prog_name: Test program name. args: Positional arguments. kwargs: Keyword arguments. Returns: Output node list from env.Program().
625941e80383005118ecfa76
@bp.app_context_processor <NEW_LINE> def auth_context(): <NEW_LINE> <INDENT> return { 'current_user': current_user, 'has_group': has_group, }
Add auth-related values to the template context. * current_user * has_group
625941e8a8370b7717052d32
def receive_bytes_secure(self): <NEW_LINE> <INDENT> if not self.connected: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> data = receive_message(self.socket) <NEW_LINE> if not data: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> except ConnectionAbortedError: <NEW_LINE> <INDE...
Waits for data to be read then decrypts it and verifies the sender. :return: The decrypted data or None if the decryption or verification failed, or no data was received.
625941e85fcc89381b1e1b57
def merge(self, nums1, m, nums2, n): <NEW_LINE> <INDENT> i = j = 0 <NEW_LINE> inserted = 0 <NEW_LINE> while i < m + inserted and j < n: <NEW_LINE> <INDENT> if nums1[i] < nums2[j]: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for k in range(m + n - 1, i, -1): <NEW_LINE> <INDENT> nums1[k] = nu...
:type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead.
625941e8e5267d203edce12c
def deleteRoster(rosterName): <NEW_LINE> <INDENT> print(rosterName)
Deletes a roster with the given name. Args: rosterName: The name of the roster to delete.
625941e84f6381625f114ed1
def _read_tx_parts(self): <NEW_LINE> <INDENT> start = self.cursor <NEW_LINE> marker = self.binary[self.cursor + 8] <NEW_LINE> if marker: <NEW_LINE> <INDENT> tx = super().read_tx() <NEW_LINE> tx_hash = self.TX_HASH_FN(self.binary[start:self.cursor]) <NEW_LINE> return tx, tx_hash, self.binary_length <NEW_LINE> <DEDENT> v...
Return a (deserialized TX, tx_hash, vsize) tuple.
625941e891af0d3eaac9beb2
def search_prefix(self, word: str, allow_same=False) -> list[str]: <NEW_LINE> <INDENT> ans = [] <NEW_LINE> node = self <NEW_LINE> for ch in word: <NEW_LINE> <INDENT> if ch not in node.children: <NEW_LINE> <INDENT> return ans <NEW_LINE> <DEDENT> node = node.children[ch] <NEW_LINE> if node.val: <NEW_LINE> <INDENT> if all...
查询是否有元素是给定 word 的前缀
625941e86fb2d068a760f53a
def end(self): <NEW_LINE> <INDENT> self._stop_time = time.time() <NEW_LINE> self.element.setAttribute('time', self.elapsed_time()) <NEW_LINE> self._set_result_counters() <NEW_LINE> return self.element
Closes this context (started with a call to `begin`) and creates an attribute for each counter and another for the elapsed time.
625941e8ac7a0e7691ed4558
@selfservice(delete_selfservice) <NEW_LINE> def delete(request, mail_id): <NEW_LINE> <INDENT> mail_id = check_mail_id(request, mail_id) <NEW_LINE> connector = SQLconnector() <NEW_LINE> valid_addresses = get_user_valid_addresses(request.user) <NEW_LINE> for mid in mail_id: <NEW_LINE> <INDENT> r, i = mid.split() <NEW_LIN...
Delete message selection. :param str mail_id: message unique identifier
625941e892d797404e304621
def restart(self): <NEW_LINE> <INDENT> self.n_steps = 0 <NEW_LINE> self._sut = [False]
Restarts a regimen.
625941e873bcbd0ca4b2c50a
def reverse_num(n:int) -> int: <NEW_LINE> <INDENT> i = 3 <NEW_LINE> rev_num = 0 <NEW_LINE> while n > 10: <NEW_LINE> <INDENT> rev_num += (n % 10 * 10 ** i) <NEW_LINE> i -= 1 <NEW_LINE> n //= 10 <NEW_LINE> <DEDENT> rev_num += n <NEW_LINE> return(rev_num)
>>> reverse_num(1234) 4321 >>> reverse_num(1915) 5191
625941e82eb69b55b151cd4b
def get_single_package(self, package_name): <NEW_LINE> <INDENT> return self.fetchone("SELECT * FROM packages WHERE pack_name=?", (package_name,))
Fetches a single package details from the database :param package_name: Name of package :type package_name: str :return: Package record :rtype: dict
625941e84e4d5625662d4866
def login(self): <NEW_LINE> <INDENT> self.driver.get('https://auth.hulu.com/web/login') <NEW_LINE> sleep(2) <NEW_LINE> form = self.driver.find_element_by_class_name('hulu-login') <NEW_LINE> form.find_element_by_name('email').send_keys(self.creds['hulu_u']) <NEW_LINE> form.find_element_by_name('password').send_keys(self...
Logs in to site, returns true if logged in.
625941e829b78933be1e5b3b
def _from_csv(value): <NEW_LINE> <INDENT> buffer = io.StringIO(value) <NEW_LINE> reader = csv.reader(buffer) <NEW_LINE> try: <NEW_LINE> <INDENT> return next(reader) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> return []
:type value: str :rtype: list[str]
625941e821bff66bcd684de3
def f2(shorter,longer): <NEW_LINE> <INDENT> if len(longer) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if len(shorter) == 0: <NEW_LINE> <INDENT> return (0,0) <NEW_LINE> <DEDENT> bestsub = None <NEW_LINE> for start_i in range(len(longer)): <NEW_LINE> <INDENT> shorter_set = set(shorter) <NEW_LINE> for end_j...
O(M+N^2) somewhat brute-force version for testing. See f1.
625941e863b5f9789fde757b
def __init__(self, testsuite): <NEW_LINE> <INDENT> self.level = testsuite.env.options.level <NEW_LINE> self.sid_dir = testsuite.env.options.gnatcov <NEW_LINE> self.temp_dir = os.path.join(testsuite.env.working_dir, 'gnatcov') <NEW_LINE> self.output_dir = testsuite.output_dir <NEW_LINE> self.ensure_clean_dir(self.temp_d...
:param Testsuite testsuite: Testsuite instance to work with.
625941e867a9b606de4a834c
def setUp(self): <NEW_LINE> <INDENT> self.app = create_app('testing') <NEW_LINE> self.app_context = self.app.app_context() <NEW_LINE> self.app_context.push() <NEW_LINE> db.create_all()
在测试前创建一个测试环境。 1). 使用测试配置创建程序 2). 激活上下文, 确保能在测试中使用 current_app 3). 创建一个全新的数据库,以备不时之需。 :return:
625941e8bde94217f3683282
@pytest.yield_fixture <NEW_LINE> def tmpworkdir(tmpdir): <NEW_LINE> <INDENT> cwd = os.getcwd() <NEW_LINE> os.chdir(tmpdir.strpath) <NEW_LINE> yield tmpdir <NEW_LINE> os.chdir(cwd)
Create a temporary working working directory.
625941e88e05c05ec3eea80e
def refresh_missions(self): <NEW_LINE> <INDENT> if not self.vtol_sync.vtolvrmissions_online: <NEW_LINE> <INDENT> self.display_message("VTOLVRMissions.com Offline", "VTOLVRMissions.com is currently offline, we will only show local resources. Try refreshing data later.") <NEW_LINE> <DEDENT> if not self.refresh_missions_r...
Runs the refresh_mission_thread in another thread.
625941e8a17c0f6771cbe4e5
def test_to_json(self): <NEW_LINE> <INDENT> create_package_listing(self.session) <NEW_LINE> pkg = model.Package.by_name(self.session, 'rpms', 'guake') <NEW_LINE> package = model.PackageListing.by_package_id(self.session, pkg.id)[0] <NEW_LINE> package = package.to_json() <NEW_LINE> self.assertEqual( set(package.keys()),...
Test the to_json function of PackageListing.
625941e8498bea3a759b9f43
def get_translation_vec(self): <NEW_LINE> <INDENT> return self._translation_vec
Return the translation vector.
625941e83cc13d1c6d3c780d
def _processEvents(self): <NEW_LINE> <INDENT> pgl.clock.tick() <NEW_LINE> if not self.closed: <NEW_LINE> <INDENT> self.window.switch_to() <NEW_LINE> self.window.dispatch_events() <NEW_LINE> self.window.flip()
This is the replacement for a custom event loop for Pyglet. The lines below are typical of Pyglet examples. Manually resizing the window is still very clunky.
625941e844b2445a33932528
def getAirport(self, code): <NEW_LINE> <INDENT> return(self.airportDict[code])
Returns airport objects stored in a Dictionary using IATA code as key
625941e873bcbd0ca4b2c50b
def createViz(self): <NEW_LINE> <INDENT> self.ui.bar.clearWidgets() <NEW_LINE> self.ui.bar.pushMessage("Info", QApplication.translate('CartoDBPlugin', 'Creating Map'), level=QgsMessageBar.INFO) <NEW_LINE> self.withWarnings = False <NEW_LINE> for ly in self.cartoDBLayers: <NEW_LINE> <INDENT> layer = ly <NEW_LINE> if not...
Create Map in CartoDB
625941e88da39b475bd6540f
def run(self): <NEW_LINE> <INDENT> self.catchall() <NEW_LINE> while(True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.outfd(self.prompt) <NEW_LINE> line = self.readline() <NEW_LINE> if(len(line) > 0): <NEW_LINE> <INDENT> self.log.append(line) <NEW_LINE> <DEDENT> self.cli.findMatch(line) <NEW_LINE> <DEDENT> excep...
Main running function, loops through forever until the user kills us.
625941e810dbd63aa1bd3037
def get_highestValue(self): <NEW_LINE> <INDENT> if self._cacheExpiration <= YAPI.GetTickCount(): <NEW_LINE> <INDENT> if self.load(YAPI._yapiContext.GetCacheValidity()) != YAPI.SUCCESS: <NEW_LINE> <INDENT> return YSensor.HIGHESTVALUE_INVALID <NEW_LINE> <DEDENT> <DEDENT> res = self._highestValue * self._iresol <NEW_LINE>...
Returns the maximal value observed for the measure since the device was started. Can be reset to an arbitrary value thanks to set_highestValue(). @return a floating point number corresponding to the maximal value observed for the measure since the device was started On failure, throws an exception or returns YSensor....
625941e8be383301e01b5912
def _assetschanged(self): <NEW_LINE> <INDENT> assets_model = self.data["model"]["assets"] <NEW_LINE> subsets_widget = self.data["model"]["subsets"] <NEW_LINE> subsets_model = subsets_widget.model <NEW_LINE> t1 = time.time() <NEW_LINE> asset_item = assets_model.get_active_asset() <NEW_LINE> if asset_item is None: <NEW_L...
Selected assets have changed
625941e821a7993f00bc818d
def testItemInsertionFailure(self): <NEW_LINE> <INDENT> ITEM = item.Item(5, 11) <NEW_LINE> self.assertFalse(self.BIN.insert(ITEM, 'best_area_fit'))
Single Item Fits no FreeRectangles Split Horizontal Rotation == False RectMerge == False
625941e823e79379d52ee9f3
def _parse_scenario(self, filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for lineno, line in enumerate(open(filename, "r")): <NEW_LINE> <INDENT> if not line.startswith('#'): <NEW_LINE> <INDENT> cmd = self._parse_scenario_line(lineno + 1, line) <NEW_LINE> if cmd is not None: <NEW_LINE> <INDENT> yield cmd <NEW_L...
Returns a list of commands that will be executed. A command is a (TIMESTAMP, LINENO, CALLABLE, ARGS) tuple. CALLABLE is the name of a function, method, etc. registered with this scenario using the register() method.
625941e829b78933be1e5b3c
def test_read_sys_net_int_returns_none_on_valueerror(self): <NEW_LINE> <INDENT> write_file(os.path.join(self.sysdir, 'dev', 'attr'), 'NOTINT\n') <NEW_LINE> self.assertFalse(net.read_sys_net_int('dev', 'attr'))
read_sys_net_safe returns None when content is not an int.
625941e815fb5d323cde0fac
def __init__(self, service_plan_id, api_token, source, targets=None, region=None, **kwargs): <NEW_LINE> <INDENT> super(NotifySinch, self).__init__(**kwargs) <NEW_LINE> self.service_plan_id = validate_regex( service_plan_id, *self.template_tokens['service_plan_id']['regex']) <NEW_LINE> if not self.service_plan_id: <NEW_...
Initialize Sinch Object
625941e8167d2b6e3121902a
def bases(self): <NEW_LINE> <INDENT> if self.elfclass == 32: <NEW_LINE> <INDENT> return self._bases32() <NEW_LINE> <DEDENT> if self.elfclass == 64: <NEW_LINE> <INDENT> return self._bases64()
Resolve base addresses of all loaded libraries. Return a dictionary mapping library path to its base address.
625941e830bbd722463cc25e
def get_mws_status(): <NEW_LINE> <INDENT> return MWS.get_mws_status()
Return Amazon MWS API status # noqa: E501 :rtype: GetMwsStatusResponse
625941e8aad79263cf390edd
def check_revision(version): <NEW_LINE> <INDENT> revision = get_revision() <NEW_LINE> if revision: <NEW_LINE> <INDENT> version = "%s-%s" % (version, revision) <NEW_LINE> <DEDENT> return version
Adapts the default version string and banner to use the revision number.
625941e8009cb60464c63843
def selectTravelItems(transportationMode, transportationTime, internationalDomestic): <NEW_LINE> <INDENT> pass
Select travel docs and items related to time in transit.
625941e85166f23b2e1a55ee