code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def __compute_wk_and_wk0(self, class_mus, scov, log_priors): <NEW_LINE> <INDENT> noc = class_mus.shape[0] <NEW_LINE> self.w_k0 = np.zeros(shape=(noc), dtype=np.float64) <NEW_LINE> s_inv = np.linalg.inv(scov) <NEW_LINE> self.w_k = s_inv.dot(class_mus.T).T <NEW_LINE> for k in range(noc): <NEW_LINE> <INDENT> mu_k = class_...
Return W_k which is a matrix, where every row corresponds to w_k for a particular class. Compute W_k0 which is a vector, where every element corresponds to w_k0 for a particular class
625941d4dd821e528d63b395
def getAudiencesVocab(self): <NEW_LINE> <INDENT> if not safe_hasattr(self.aq_parent, 'getAudiencesVocab'): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> return self.aq_parent.getAudiencesVocab()
Get sections vocabulary.
625941d473bcbd0ca4b2c263
def revenue1(file): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> revenue = 0.0 <NEW_LINE> for item in file: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> revenue += float(file[item]['Price']) <NEW_LINE> <DEDENT> return revenue
() -> float Gives the added revenue of all the money of each purchase in the log (history.txt).
625941d445492302aab5e4b2
def test_batch_find_gene(): <NEW_LINE> <INDENT> expect_batch = batch_find_gene(["AAA34866", "GAX67478"]) <NEW_LINE> assert expect_batch == ['M22259.1', 'BEGW01000001.1']
test_batch_find_gene should return both gene's corresponding DNA accession numbers.
625941d4e76e3b2f99f3a9f6
def forward(self, x, cond): <NEW_LINE> <INDENT> latent_code, mean, logvar = self.encode(x, cond) <NEW_LINE> x_hat = self.decode(cond, latent_code) <NEW_LINE> return x_hat, mean, logvar
Forward propagation. Args: x (`torch.Tensor`): input feature. cond (`torch.Tensor`): conditioning variable. Returns: The reconstruction of `x`, the mean of the latent variable and the logarithm of its variance.
625941d460cbc95b062c6730
def vulnerable_versions_by_package(arguments: Namespace) -> Dict[str, Dict[str, int]]: <NEW_LINE> <INDENT> agg = defaultdict(lambda: { 'total': 0, 'all_vulnerable': 0, 'any_vulnerable': 0, 'most_recent_vulnerable': 0, }) <NEW_LINE> urls = BACKEND.retrieve_scanned_sites(arguments.identifier) <NEW_LINE> for url in tqdm(u...
Aggregate the number of scan results with detected vulnerable versions by package. This uses the invariant from the previous results that results have at most 1 different package among their guesses.
625941d4bde94217f3682fdd
def _to_move(uf: Dict[Node, Cluster], g: BAGraph) -> Dict[Node, Tuple[Cluster, int]]: <NEW_LINE> <INDENT> moves = {} <NEW_LINE> for k, c in uf.items(): <NEW_LINE> <INDENT> forces = g.calc_attract(k, uf) <NEW_LINE> new_cluster, attract = max(forces.items(), key=itemgetter(1)) <NEW_LINE> old_cluster = c <NEW_LINE> if (at...
Calculate "in parallel" for each node the most attractive clusters. Parameters --------- uf: list of clusters clustering g: the graph of the tolerance relation Returns ------- most attractive clusters for nodes
625941d46fece00bbac2d92d
def save_nwb(output_path, v, sweep): <NEW_LINE> <INDENT> output = NwbDataSet(output_path) <NEW_LINE> output.set_sweep(sweep, None, v)
Save a single voltage output result into an existing sweep in a NWB file. This is intended to overwrite a recorded trace with a simulated voltage. Parameters ---------- output_path : string file name of a pre-existing NWB file. v : numpy array voltage sweep : integer which entry to overwrite in the file.
625941d47c178a314d6ef64e
def write_index_of_names(self): <NEW_LINE> <INDENT> self.doc.start_paragraph("DDR-Title") <NEW_LINE> self.doc.write_text_citation("Index of Names") <NEW_LINE> self.doc.end_paragraph() <NEW_LINE> self.doc.start_paragraph("DDR-IndexNamesHeader") <NEW_LINE> ref_str = "Report Generat. Person Name" <NEW_LINE> self.doc...
This funciont writes the names in alfabetical order and give reference where the person appears in the reports.
625941d492d797404e304378
def test_sort_referral_data_multiple_all_classes(self): <NEW_LINE> <INDENT> test_triage_controller = TriageController(self.intervals_multiple_mock, self.clinic_settings_mock, self.padding_length_large_mock) <NEW_LINE> referral_data_mock = [ { 'date_recieved': datetime.strptime('2019-01-01', '%Y-%m-%d'), 'date_seen': da...
Test Type: Unit Test Purpose: Tests that multiple historic data can be sorted into multiple triage classes.
625941d4c432627299f04e34
def set_message(self, text): <NEW_LINE> <INDENT> self.request.session['message'] = text
Запись сообщения в сессию для последующего отображения в шаблоне через контекстный процессор
625941d46fb2d068a760f28c
def testClusterKerasCustomLayer(self): <NEW_LINE> <INDENT> keras_custom_layer = self.keras_custom_layer <NEW_LINE> cluster_wrapper.ClusterWeights(keras_custom_layer, **self.params) <NEW_LINE> keras_custom_layer.build(input_shape=(10, 10)) <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> cluster_wrappe...
Verifies that attempting to cluster a keras custom layer raises an exception.
625941d423e79379d52ee74f
def editDistance(word0, word1): <NEW_LINE> <INDENT> width = len(word0) + 1 <NEW_LINE> height = len(word1) + 1 <NEW_LINE> distance_matrix = np.zeros((width, height)) <NEW_LINE> for i in range(height): <NEW_LINE> <INDENT> distance_matrix[0][i] = i <NEW_LINE> <DEDENT> for i in range(width): <NEW_LINE> <INDENT> distance_ma...
Find Levenshtein Distance between two words. Refer to Peter Norvig's cost matrix for substitution, insertion, deletion.
625941d43cc13d1c6d3c7567
def reassemble_status(status): <NEW_LINE> <INDENT> status_dict = status.get_content() <NEW_LINE> if status.retweet: <NEW_LINE> <INDENT> status_dict.retweeted_status = status.retweet.get_content() <NEW_LINE> <DEDENT> return status_dict
database -> json status dict with retweet
625941d40a366e3fb873ea08
def parse(self, html): <NEW_LINE> <INDENT> etree_html = etree.HTML(html) <NEW_LINE> ip_ports = etree_html.xpath("//tbody/tr/td[1]/text()") <NEW_LINE> for ip_port in ip_ports: <NEW_LINE> <INDENT> host = ip_port.partition(":")[0] <NEW_LINE> port = ip_port.partition(":")[2] <NEW_LINE> yield host+':'+str(port)
parse html file to get proxies :return:
625941d466673b3332b9227f
def test_is_subscribed_but_not_enabled(self): <NEW_LINE> <INDENT> session = Session(URL, LOGIN, PASSWORD, subscription_enabled=False) <NEW_LINE> resp = session.login() <NEW_LINE> self.assertTrue(resp.ok) <NEW_LINE> url = Tenant._get_subscription_urls()[0] <NEW_LINE> self.assertFalse(session.is_subscribed(url)) <NEW_LIN...
Test is_subscribed function but subscription has not been enabled
625941d4d4950a0f3b08c53b
def valid_coloring(coloring, G): <NEW_LINE> <INDENT> valid = False <NEW_LINE> if coloring is not None: <NEW_LINE> <INDENT> valid = True <NEW_LINE> for color in coloring: <NEW_LINE> <INDENT> for vertex in color: <NEW_LINE> <INDENT> neighbors = G.neighbors(vertex) <NEW_LINE> for neighbor in neighbors: <NEW_LINE> <INDENT>...
a function that determines if the coloring is valid Parameters: coloring: a list of colors in which each color is a list of nodes e.g. [[1,2],[3]] G: a networkx graph (networkx) Returns: valid: True if valid coloring, False otherwise
625941d491af0d3eaac9bc08
def app_api_collection_raw_get_list(self, space_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.app_api_collection_raw_get_list_with_http_info(space_id, **kwargs)
list collections # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.app_api_collection_raw_get_list(space_id, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str...
625941d4287bf620b61d3c51
def print_board(self): <NEW_LINE> <INDENT> for row in self.board: <NEW_LINE> <INDENT> print(" ".join(row))
Print the board
625941d4004d5f362079a520
def function_handler(event, context): <NEW_LINE> <INDENT> global data_per_device <NEW_LINE> logger.info("function_handler received message: {}".format(json.dumps(event))) <NEW_LINE> device_name = event["device_id"] <NEW_LINE> data_per_device[device_name] = event <NEW_LINE> logger.info("Publishing message to cloud : {}"...
This function will be called when the AWS Lambda receives an MQTT message.
625941d4091ae3566866714a
def testChisq(self, array): <NEW_LINE> <INDENT> a, b, c, d = array <NEW_LINE> z = 1.959964 <NEW_LINE> array = [ [a, c], [b, d], ] <NEW_LINE> chi, p, dof, details = scipy.stats.chi2_contingency(array, True) <NEW_LINE> OR = (a * d) / (b * c) <NEW_LINE> SE = math.sqrt(1 / a + 1 / b + 1 / c + 1 / d) <NEW_LINE> ORL = OR * m...
Calculates the chi value of a 2X2 table with: [a c] [b d] It uses the chi2 contingency test with Yates continuity. ToDo: Use numpy here?
625941d415baa723493c4164
def classify(self, itemVector): <NEW_LINE> <INDENT> return(self.knn(self.normalizeVector(itemVector)))
Return class we think item Vector is in
625941d4cad5886f8bd271c7
def submenu(self, submenu): <NEW_LINE> <INDENT> self.tcs.show_menu(submenu)
Go to the given submenu (a Menu)
625941d4a17c0f6771cbe23e
def nodes(self): <NEW_LINE> <INDENT> return self._nodes
The nodes connected by this relationship.
625941d4bf627c535bc133bd
def _VerifyHMAC(self, comms=None): <NEW_LINE> <INDENT> if self.hmac_type == "SIMPLE_HMAC": <NEW_LINE> <INDENT> msg = comms.encrypted <NEW_LINE> digest = comms.hmac <NEW_LINE> <DEDENT> elif self.hmac_type == "FULL_HMAC": <NEW_LINE> <INDENT> msg = b"".join([ comms.encrypted, comms.encrypted_cipher, comms.encrypted_cipher...
Verifies the HMAC. This method raises a DecryptionError if the received HMAC does not verify. If the HMAC verifies correctly, True is returned. Args: comms: The comms RdfValue to verify. Raises: DecryptionError: The HMAC did not verify. Returns: True
625941d4dc8b845886cb5724
def __getitem__(self, k): <NEW_LINE> <INDENT> if self._instance is not _unset and k not in self: <NEW_LINE> <INDENT> self._instance[k] <NEW_LINE> <DEDENT> return self._contents[k]
Retrieve the child tree with key ``k``. If the key is not in the instance that this tree corresponds to and is not known by this tree, whatever error would be raised by ``instance.__getitem__`` will be propagated (usually this is some subclass of :class:`LookupError`.
625941d41f037a2d8b9463eb
def getFloorMetrics(officeList): <NEW_LINE> <INDENT> temps = [office.temp for office in officeList] <NEW_LINE> humidities = [office.humidity for office in officeList] <NEW_LINE> avgTemp = statistics.mean(temps) <NEW_LINE> avgHumidity = statistics.mean(humidities) <NEW_LINE> stdDevTemp = statistics.stdev(temps) <NEW_LIN...
Calculates floor averages and standard deviations for temperature and humidity
625941d463d6d428bbe446dd
def __getitem__(self , index): <NEW_LINE> <INDENT> if isinstance(index , tuple): <NEW_LINE> <INDENT> global_index = self.grid.get_global_index( ijk = index ) <NEW_LINE> if self.global_active: <NEW_LINE> <INDENT> index = global_index <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not self.grid.active( global_index = g...
Will return item [g] or [i,j,k]. The __getitem__() methods supports both scalar indexing like [g] and tuples [i,j,k]. If the input argument is given as a [i,j,k] tuple it is converted to an active index before the final lookup. If the [i,j,k] input corresponds to an inactive cell in a keyword with only nactive elemen...
625941d4a79ad161976cc333
def __init__(self, info, card): <NEW_LINE> <INDENT> self.card = card <NEW_LINE> if info == "False": <NEW_LINE> <INDENT> self.active = False <NEW_LINE> self.minimum = 0 <NEW_LINE> self.months = 0 <NEW_LINE> self.reward = 0 <NEW_LINE> self.progress = 0 <NEW_LINE> return <NEW_LINE> <DEDENT> sub = list(info.split(",")) <NE...
This creates a new sign-up bonus object given a string of info. :param info: is the SUB info provided by the database file or user. :param card: is the card this SUB is attached to.
625941d467a9b606de4a80a6
def to_dict(self): <NEW_LINE> <INDENT> nums = [] <NEW_LINE> for r in self.rulesets: <NEW_LINE> <INDENT> nums.append(r.to_dict_simple()) <NEW_LINE> <DEDENT> foll = [] <NEW_LINE> for f in self.followers: <NEW_LINE> <INDENT> foll.append(f.id) <NEW_LINE> <DEDENT> foll2 = [] <NEW_LINE> for f in self.followcheck: <NEW_LINE> ...
A function that returns key object information in a readable format
625941d4099cdd3c635f0e48
def eval(self, string): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from pyparsing import ParseException <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> message = '{name}: Unable to import pyparsing module. You can install it with `pip install pyparsing`.'.format( name=self.__class__.__name__ ) <NEW_LINE> ...
Evaluate math in the string Parameters ---------- string : str String to be evaluated Returns ------- result : numeric Evaluation result
625941d49c8ee82313fbb963
def write_netcdf(x,xname,xtype,xdims,xdimnames,units,history,fname): <NEW_LINE> <INDENT> import scipy.io.netcdf as spnc <NEW_LINE> f = spnc.netcdf_file(fname,'w') <NEW_LINE> f.history = history <NEW_LINE> ndims = len(xdims) <NEW_LINE> for i in range(0,ndims): <NEW_LINE> <INDENT> f.createDimension(xdimnames[i], xdims[i]...
Writes the data in x to a netcdf file. Up to 3D. Inputs: x = array to save as a variable in netcdf file xname = string, name to give the variable xtype = string, data type - 'd' for double xdims = integer list, dimensions of x xdimnames = string list, names to give dimensions units = string, un...
625941d4eab8aa0e5d26dd46
def setUp(self): <NEW_LINE> <INDENT> self.hass = get_test_home_assistant() <NEW_LINE> self.config = VALID_CONFIG
Initialize the values for this test class.
625941d429b78933be1e5897
def apply_linear(self, params, unknowns, dparams, dunknowns, dresids, mode): <NEW_LINE> <INDENT> dI_bat = dresids['I_bat'] <NEW_LINE> if mode == 'fwd': <NEW_LINE> <INDENT> if 'P_bat' in dparams: <NEW_LINE> <INDENT> dI_bat += self.dI_dP * dparams['P_bat'] <NEW_LINE> <DEDENT> if 'temperature' in dparams: <NEW_LINE> <INDE...
Matrix-vector product with the Jacobian.
625941d42ae34c7f2600d31f
def balanced_binary_crossentropy(y_true, y_pred): <NEW_LINE> <INDENT> from keras import backend as K <NEW_LINE> y_true_f = K.cast(y_true,K.floatx()) <NEW_LINE> num_pos = K.sum(y_true_f)+1 <NEW_LINE> num_neg = K.sum(1-y_true_f)+1 <NEW_LINE> weights = (num_neg)/(num_pos)*y_true_f + (1-y_true_f) <NEW_LINE> score_array = K...
Binary crossentropy loss function with automatic class balancing
625941d416aa5153ce362666
def sort_weights(opts): <NEW_LINE> <INDENT> stationary = opts.stationary <NEW_LINE> state_size = opts.state_size <NEW_LINE> save_path = opts.save_path <NEW_LINE> weight_name = opts.weight_name <NEW_LINE> rnn_size = opts.rnn_size <NEW_LINE> support_size = rnn_size - state_size <NEW_LINE> with open(os.path.join(save_path...
Visualization of trained network.
625941d49f2886367277aa7b
def add(self, *sprites): <NEW_LINE> <INDENT> for sprite in sprites: <NEW_LINE> <INDENT> if sprite not in self._sprites: <NEW_LINE> <INDENT> self._sprites.append(sprite) <NEW_LINE> sprite.add(self)
Adds an object to its drawable list.
625941d4b830903b967e9af8
def process_request(self, request): <NEW_LINE> <INDENT> print("这是爬虫中间件:process_request方法") <NEW_LINE> return request
预处理请求对象
625941d4462c4b4f79d1d8be
def __getDataFromPdc(self, name, stream, version, active=True): <NEW_LINE> <INDENT> if not self.pdcdata: <NEW_LINE> <INDENT> pdc_query = {'name': name, 'active': active} <NEW_LINE> if stream: <NEW_LINE> <INDENT> pdc_query['stream'] = stream <NEW_LINE> <DEDENT> if version: <NEW_LINE> <INDENT> pdc_query['version'] = vers...
Internal method, do not use it :return: None
625941d4d6c5a1020814423a
def delete(self): <NEW_LINE> <INDENT> return self.connection.delete_load_balancer(self.name)
Delete this load balancer.
625941d45510c4643540f5cf
def segment(self, state=None, n=0, z=None, segmentFormat=None): <NEW_LINE> <INDENT> if state is None: <NEW_LINE> <INDENT> state = self._state <NEW_LINE> <DEDENT> if z is None: <NEW_LINE> <INDENT> z = self._z <NEW_LINE> <DEDENT> if segmentFormat is None: <NEW_LINE> <INDENT> segmentFormat = self._segmentFormat <NEW_LINE>...
Return a sieve segment in various formats. >>> a = sieve.Sieve('3@11') >>> a.segment('exp') [2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 56, 59, 62, 65, 68, 71, 74, 77, 80, 83, 86, 89, 92, 95, 98] >>> c = sieve.Sieve('(5|2)&4&8') >>> c.segment('cmp', segmentFormat='wid') [8, 8, 8, 8, 8, 8, 8...
625941d4925a0f43d254a066
def delegation_required(): <NEW_LINE> <INDENT> def delegation(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def decorated_view(*args, **kwargs): <NEW_LINE> <INDENT> if not current_user.is_authenticated(): <NEW_LINE> <INDENT> return current_app.login_manager.unauthorized() <NEW_LINE> <DEDENT> info = get_client_prox...
Checks if a valid delegation is available for the user Otherwise redirects to profile.
625941d44d74a7450ccd43b1
def format(self, record): <NEW_LINE> <INDENT> if record.__dict__.get('request_id', None): <NEW_LINE> <INDENT> self._fmt = FLAGS.logging_context_format_string <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._fmt = FLAGS.logging_default_format_string <NEW_LINE> <DEDENT> if record.levelno == logging.DEBUG and FL...
Uses contextstring if request_id is set, otherwise default
625941d44527f215b584c643
def delete_on_background_response_descriptor_tenants_tenant_tenant_resource(self, id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.delete_on_background_response_descriptor_tenants_tenant_tenant_resource_with_http_info(id, *...
Delete a TenantResource by ID # noqa: E501 Deletes an existing tenant. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_on_background_response_descriptor_tenants_tenant_tenant_resource(id, async_req=True) >>...
625941d4f8510a7c17cf98ea
def build_common_mask(self, bitcount: list, length: int, invert=False) -> str: <NEW_LINE> <INDENT> common_bit = "0" if invert else "1" <NEW_LINE> uncommon_bit = "1" if invert else "0" <NEW_LINE> threshold = length / 2 <NEW_LINE> bits_str = "" <NEW_LINE> for count in bitcount: <NEW_LINE> <INDENT> bits_str += common_bit ...
Return bit sequence of the most common bit for each index.
625941d4d8ef3951e324372c
def test_loaddata_not_found_fields_not_ignore(self): <NEW_LINE> <INDENT> with self.assertRaises(DeserializationError): <NEW_LINE> <INDENT> management.call_command( 'loaddata', 'sequence_extra', verbosity=0 )
Test for ticket #9279 -- Error is raised for entries in the serialised data for fields that have been removed from the database when not ignored.
625941d429b78933be1e5898
def test_ioerror_remove_upload_args(): <NEW_LINE> <INDENT> with pytest.raises(IOError): <NEW_LINE> <INDENT> cli(["--search", "x", "--remove"])
Ensure --remove causes error if --upload arg not present
625941d4c4546d3d9de72c23
def test_create_token_no_user(self): <NEW_LINE> <INDENT> payload = {"email": "test@isoppp.com", "password": "testpass"} <NEW_LINE> res = self.client.post(TOKEN_URL, payload) <NEW_LINE> self.assertNotIn("token", res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
Test that token is not created if user doesn't exist
625941d4d58c6744b4257e4d
def setAuthentication(self,auth): <NEW_LINE> <INDENT> raise NotImplementedError
Sets the authentication object for this Path object and any derived objects that would require authentication information. Preconditions: * None Postconditions: * Any methods that might require authentication now have an authorisation object that can provide authentication information to the file system being...
625941d42eb69b55b151ca9f
def SGD(self, training_data, epochs, mini_batch_size, eta, test_data=None): <NEW_LINE> <INDENT> self.t = eta <NEW_LINE> print('Before Training :' + str(self.evaluate(test_data))) <NEW_LINE> if test_data: <NEW_LINE> <INDENT> n_test = len(test_data) <NEW_LINE> <DEDENT> n = len(training_data) <NEW_LINE> for j in range(epo...
Train the neural network using mini-batch stochastic gradient descent. The ``training_data`` is a list of tuples ``(x, y)`` representing the training inputs and the desired outputs. The other non-optional parameters are self-explanatory. If ``test_data`` is provided then the network will be evaluated against the tes...
625941d4d53ae8145f87a45c
def getCESiteMapping( gridName = None ): <NEW_LINE> <INDENT> sites = getSites( gridName = gridName ) <NEW_LINE> if not sites['OK']: <NEW_LINE> <INDENT> return sites <NEW_LINE> <DEDENT> ceSiteMapping = {} <NEW_LINE> for candidate in sites['Value']: <NEW_LINE> <INDENT> grid = candidate.split( '.' )[0] <NEW_LINE> siteCEs ...
Returns a dictionary of all CEs and their associated site, e.g. {'ce101.cern.ch':'LCG.CERN.ch', ...]} Assumes CS structure of: /Resources/Sites/<GRIDNAME>/<SITENAME>
625941d4a4f1c619b28b0225
def get_muted(self): <NEW_LINE> <INDENT> return self.get_audio_status().get('mute')
Get mute status.
625941d4e5267d203edcde89
def test_connection(self): <NEW_LINE> <INDENT> LOGGER.debug("Testing access to GreyNoise API and for valid API Key") <NEW_LINE> response = self._request(self.EP_PING) <NEW_LINE> return response
Test the API connection and API key.
625941d4442bda511e8be605
def df_from_query(query): <NEW_LINE> <INDENT> print(engine.url) <NEW_LINE> return pd.read_sql_query(query, con)
Takes a SQL query and outputs the information to a pandas ddf Parameters ---------- query : SQL query sql query in postgres format. Returns ------- dataframe returns a pandas dataframe.
625941d4435de62698dfde3b
def _create_data_directories(self): <NEW_LINE> <INDENT> self.main_dir = self.main_dir + '/' if self.main_dir[-1] != '/' else self.main_dir <NEW_LINE> models_dir = zconfig.models_dir + self.main_dir <NEW_LINE> data_dir = zconfig.data_dir + self.main_dir <NEW_LINE> summary_dir = zconfig.summary_dir + self.main_dir <NEW_L...
Create the three directories for storing respectively the models, the data generated by training and the TensorFlow's summaries. :return: tuple of strings(models_dir, data_dir, summary_dir)
625941d450485f2cf553cf89
def RunScheduledTask(self): <NEW_LINE> <INDENT> return self.delegate("RunScheduledTask")()
Runs the scheduled task immediately. The schedule for future runs remains in effect.
625941d4d164cc6175782f3d
def test_outConnectionLost(self): <NEW_LINE> <INDENT> self.pp.outConnectionLost() <NEW_LINE> self.assertFalse(self.session in self.session.conn.eofs) <NEW_LINE> self.pp.errConnectionLost() <NEW_LINE> self.assertTrue(self.session.conn.eofs[self.session])
When outConnectionLost and errConnectionLost are both called, we should send an EOF message.
625941d42c8b7c6e89b359af
def _upsert_into_legal_archive_publish_queue(self, queue_item, subscribers, force_move): <NEW_LINE> <INDENT> legal_publish_queue_service = get_resource_service(LEGAL_PUBLISH_QUEUE_NAME) <NEW_LINE> legal_queue_item = deepcopy(queue_item) <NEW_LINE> lookup = { 'item_id': legal_queue_item.get('item_id'), 'item_version': l...
Upsert into legal publish queue. :param dict queue_item: publish_queue collection item :param dict subscribers: subscribers information :param bool force_move: true set the flag to move to legal.
625941d482261d6c526ab68f
def match(self, cfn): <NEW_LINE> <INDENT> matches = list() <NEW_LINE> resources = cfn.get_resources() <NEW_LINE> for resource_name, resource_values in resources.items(): <NEW_LINE> <INDENT> depends_ons = resource_values.get('DependsOn') <NEW_LINE> if depends_ons: <NEW_LINE> <INDENT> path = ['Resources', resource_name, ...
Check CloudFormation Resources
625941d492d797404e304379
def tearDown(self): <NEW_LINE> <INDENT> for f in os.listdir(tmp_dir_path): <NEW_LINE> <INDENT> f_path = os.path.join(tmp_dir_path,f) <NEW_LINE> try: <NEW_LINE> <INDENT> os.remove(f_path) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> for e in os.listdir(f_path): <NEW_LINE> <INDENT> e_path = os.path.join(f_path,e) <NEW...
remove temporary output files
625941d47047854f462a15f6
def process_video(proc_state): <NEW_LINE> <INDENT> entry = proc_state.entry <NEW_LINE> workbench = proc_state.workbench <NEW_LINE> video_config = mgg.global_config['media_type:mediagoblin.media_types.video'] <NEW_LINE> queued_filepath = entry.queued_media_file <NEW_LINE> queued_filename = proc_state.get_queued_filename...
Process a video entry, transcode the queued media files (originals) and create a thumbnail for the entry. A Workbench() represents a local tempory dir. It is automatically cleaned up when this function exits.
625941d410dbd63aa1bd2d91
def IntPrioritySet(): <NEW_LINE> <INDENT> pass
__NATIVE__ PmReturn_t retval = PM_RET_OK; pPmObj_t p0, p1; uint32_t ui32Interrupt; uint8_t ui8Priority; /* If wrong number of args, raise TypeError */ if (NATIVE_GET_NUM_ARGS() != 2) { PM_RAISE_WITH_INFO(retval, PM_RET_EX_TYPE, "incorrect number of arguments"); return retval; } p0 = NATIVE_GET_LOCAL(0); /* I...
625941d463b5f9789fde72d4
def add_pin(pin, av, mv): <NEW_LINE> <INDENT> new_ao = ao_info(pin, 0, 1) <NEW_LINE> new_av = new_ao[0] <NEW_LINE> new_mv = new_ao[1] <NEW_LINE> tot_av = av + new_av <NEW_LINE> tot_mv = mv + new_mv <NEW_LINE> return tot_av, tot_mv
Calculates the combined Assessed Value and Market Value for two PINs. Parameters ---------- pin : string A string representing the added PIN av : number The assessed value of the original (base) PIN mv : number The market value of the original (base) PIN Returns ------- tot_av : number The new total A...
625941d43539df3088e2e539
def status_from_state(vm_state, task_state='default'): <NEW_LINE> <INDENT> task_map = _STATE_MAP.get(vm_state, dict(default='UNKNOWN')) <NEW_LINE> status = task_map.get(task_state, task_map['default']) <NEW_LINE> if status == "UNKNOWN": <NEW_LINE> <INDENT> LOG.error(_("status is UNKNOWN from vm_state=%(vm_state)s " "ta...
Given vm_state and task_state, return a status string.
625941d47047854f462a15f7
def pointDistance(point1, point2): <NEW_LINE> <INDENT> dx = point1.X - point2.X <NEW_LINE> dy = point1.Y - point2.Y <NEW_LINE> distance = math.sqrt(dx**2 + dy**2) <NEW_LINE> return distance
Zwraca odległość (2D) między dwoma punktami
625941d4167d2b6e31218d84
def enroll_profile(subscription_key, profile_id, file_path, force_short_audio): <NEW_LINE> <INDENT> helper = IdentificationServiceHttpClientHelper.IdentificationServiceHttpClientHelper( subscription_key) <NEW_LINE> enrollment_response = helper.enroll_profile( profile_id, file_path, force_short_audio.lower() == "true") ...
Enrolls a profile on the server. Arguments: subscription_key -- the subscription key string profile_id -- the profile ID of the profile to enroll file_path -- the path of the file to use for enrollment force_short_audio -- waive the recommended minimum audio limit needed for enrollment
625941d4bd1bec0571d9081e
def __init__(self, driver, component_query): <NEW_LINE> <INDENT> self._driver = driver <NEW_LINE> self._cq = component_query
:param driver: Selenium webdriver to work with :param component_query: str ExtJS component query
625941d4d10714528d5ffed3
def vdot_normal(x, y): <NEW_LINE> <INDENT> norm_x = np.sqrt(np.sum(x * x)) <NEW_LINE> norm_y = np.sqrt(np.sum(y * y)) <NEW_LINE> if norm_x > 0 and norm_y > 0: <NEW_LINE> <INDENT> return np.vdot(x.flatten(), y.flatten()) / norm_x / norm_y <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0.
Normalized projection (aka correlation) between to arrays This functions calculates the normalized projection between two vectors x and y. If x and/or are matrices the normalized projection between the flattened arrays is calculated. Inputs: x,y (numpy arrays) Outputs: z - A scalar between -1. and 1.
625941d46e29344779a62800
def update_site_forward(apps, schema_editor): <NEW_LINE> <INDENT> Site = apps.get_model("sites", "Site") <NEW_LINE> Site.objects.update_or_create( id=settings.SITE_ID, defaults={ "domain": "elcolie.com", "name": "experiment-django3", }, )
Set site domain and name.
625941d41d351010ab855d0a
def most_common_idx(self): <NEW_LINE> <INDENT> return self._counter.most_common()
Most common values (ordered) with indices as keys. Returns ------- list : the most common contacts in order. The if the list is ``l``, then each element ``l[e]`` consists of two parts: ``l[e][0]`` is a pair of integers, representing the indices of the objects associated with the contact, and ``l[e][1]`...
625941d438b623060ff0afdc
def test_outcome_mapping_param_type(self): <NEW_LINE> <INDENT> for si in self.SIs: <NEW_LINE> <INDENT> if si.state_class != "ConcurrentState": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if 'outcome_mapping' not in si.parameter_names: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.assertEqual(1, si.paramete...
Test that the outcome_mapping parameter (if set) has valid types.
625941d4cc40096d61595b3f
def _clean_position(self): <NEW_LINE> <INDENT> if self.position is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.position = max(int(self.position), 1) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise Http404(u"Position {} is not an integer!".format(self.position))
Verify that the given position is an integer. If it is not positive, set it to 1.
625941d4f7d966606f6aa1f5
def configure_port_num(self, port=1): <NEW_LINE> <INDENT> self.write(":SOUR:PORT:SEL PRIM;") <NEW_LINE> self.write(":SOUR:PORT:PRIM RFIO%d" % int(port))
Configures port number to use. :param int port: specifies the port number to use, 1, 2, 3, 4 :return: None
625941d445492302aab5e4b4
def export_tf_reid_model(model: torch.nn.Module, tensor_inputs: torch.Tensor, graph_save_path: str): <NEW_LINE> <INDENT> assert isinstance(model, torch.nn.Module) <NEW_LINE> print("Exporting a {} model via ONNX ...".format(type(model).__name__)) <NEW_LINE> predict_net = _export_via_onnx(model, tensor_inputs) <NEW_LINE>...
Export a reid model via ONNX. Arg: model: a tf_1.x-compatible version of detectron2 model, defined in caffe2_modeling.py tensor_inputs: a list of tensors that caffe2 model takes as input.
625941d4dd821e528d63b397
def test_page_subclass_manager(self): <NEW_LINE> <INDENT> self.assertIs(type(SimplePage.objects), PageManager)
Assert that Page subclasses get a PageManager without having to do anything special. MTI subclasses do *not* inherit their parents Manager by default.
625941d4e8904600ed9f211e
def get_learning_objective_query(self): <NEW_LINE> <INDENT> raise errors.Unimplemented()
Gets the query for a learning objective. Multiple retrievals produce a nested ``OR`` term. return: (osid.learning.ObjectiveQuery) - the learning objective query raise: Unimplemented - ``supports_learning_objective_query()`` is ``false`` *compliance: optional -- This method must be implemented if ``...
625941d4627d3e7fe0d69040
def __init__(self): <NEW_LINE> <INDENT> return int()
int QNetworkProxy.Capabilities.__init__()
625941d47b180e01f3dc49ea
def get_home_page_info_by_page_num(self, page_num: int) -> list: <NEW_LINE> <INDENT> def parse_page_info(body) -> list: <NEW_LINE> <INDENT> li_sel = { 'method': 'css', 'selector': 'div.center-wrap a.random_list', } <NEW_LINE> title_sel = { 'method': 'css', 'selector': 'div.random_title ::text', } <NEW_LINE> create_time...
根据page_num获取单页的信息 :param page_num: :return:
625941d47c178a314d6ef651
def do_AXIWB1 (self, value): <NEW_LINE> <INDENT> return None
Perform the command '' and return the result.
625941d4ab23a570cc250372
def density_to_mat(dens_dict): <NEW_LINE> <INDENT> mat = openmc.Material() <NEW_LINE> for key in dens_dict: <NEW_LINE> <INDENT> mat.add_nuclide(key, 1.0e-24*dens_dict[key]) <NEW_LINE> <DEDENT> mat.set_density('sum') <NEW_LINE> return mat
Generates an OpenMC material from a cell ID and self.number_density. Parameters ---------- dens_dict : dict Dictionary mapping nuclide names to densities Returns ------- openmc.Material The OpenMC material filled with nuclides.
625941d491af0d3eaac9bc09
def gen_flash_events(events, flashes): <NEW_LINE> <INDENT> for fl in flashes: <NEW_LINE> <INDENT> fl_id=fl['flash_id'] <NEW_LINE> this_flash = (events['flash_id']==fl_id) <NEW_LINE> yield events[this_flash], fl
Given events and flashes tables, generate events for each flash as (events, flash)
625941d431939e2706e4d058
def getConnectionInfo(self, user): <NEW_LINE> <INDENT> return self.userDB.getConnectionInfo(user)
Returns the connection information for the specified user :param user: User we want connection information for :return: A dictionary containing the host/port information of the user
625941d46fb2d068a760f28e
def test_task_descriptions_success(self): <NEW_LINE> <INDENT> task_descriptions = self.db.get_task_descriptions(state='success') <NEW_LINE> self.assertEquals(type(task_descriptions), list) <NEW_LINE> self.assertEquals(len(task_descriptions), 4)
Test that the task descriptions method returns a list of 'success' tasks and that the list is of size '2'
625941d4187af65679ca530e
def compile(self) -> None: <NEW_LINE> <INDENT> pass
Empty compile.
625941d48e71fb1e9831d998
def __init__(self, G): <NEW_LINE> <INDENT> if not is_undirected(G): <NEW_LINE> <INDENT> raise NotBiconnected <NEW_LINE> <DEDENT> self._dfsnumber = {} <NEW_LINE> self._low = {} <NEW_LINE> self._rootedge = None <NEW_LINE> Searcher.__init__(self, G)
Search for biconnected components of graph G.
625941d4d18da76e235326c7
def zeros(shape: Tuple, name: str, requires_optim: bool = False, is_const=False) -> Tensor: <NEW_LINE> <INDENT> data = np.zeros(shape) <NEW_LINE> return Tensor(data, name, requires_optim=requires_optim, is_const=is_const)
create all zeros tensor
625941d4baa26c4b54cb130d
def setup_configuration(app): <NEW_LINE> <INDENT> conf = environment.load_configuration() <NEW_LINE> setup_database_configuration(app, conf)
Load configuration. Args: app ([flask.Flask]): the application Raises: exceptions.SecretError: if database password is not set
625941d47d847024c06be4ad
def find_tests(tests=None): <NEW_LINE> <INDENT> if not tests: <NEW_LINE> <INDENT> tests = glob.glob('configs/*.yaml') <NEW_LINE> <DEDENT> LOG.info('running %s tests\n%s', len(tests), tests) <NEW_LINE> return sorted(tests)
Determine what tests to run, return array of tests. @param tests: optional, list of test files to run @return list of test files to run
625941d460cbc95b062c6733
def get_copyright(info_list): <NEW_LINE> <INDENT> copyright = set([passage.copyright_display for passage in info_list]) <NEW_LINE> return "\n".join(copyright)
gets a concatentated list of unique copyrights from a list of PassageInfo objects.
625941d40a366e3fb873ea0a
def svn_wc_check_wc(*args): <NEW_LINE> <INDENT> return _wc.svn_wc_check_wc(*args)
svn_wc_check_wc(char path, apr_pool_t pool) -> svn_error_t
625941d4097d151d1a223048
def height_range(self, unit="pixel"): <NEW_LINE> <INDENT> if unit == "pixel": <NEW_LINE> <INDENT> return self.__height_range <NEW_LINE> <DEDENT> elif unit == "meter": <NEW_LINE> <INDENT> res = self.bin_resolution()[0] <NEW_LINE> min_, max_ = self.__height_range <NEW_LINE> return min_ * res, None if max_ is None else ma...
Returns the range of height of the reconstructed volume (min, max) :param str unit: Unit of the returned values, either 'pixel' or 'meter' :rtype: List[Union[int,float,None]] :raises ValueError: If unit is not supported
625941d4a05bb46b383eca11
def resolve_path(dset, loc, first=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if first: <NEW_LINE> <INDENT> return dset[loc], loc <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [dset[loc]], [loc] <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> searches = [loc.strip('/').split('/')] <NEW...
Search for globbed paths in a nested dict-like hierarchy Args: dset (dict): Root of some nested dict-like hierarchy loc (str): path as a glob pattern first (bool): Stop at first match and return a single value Raises: KeyError: If there are no glob matches Returns: If first == True, (value, path)...
625941d4a17c0f6771cbe23f
def filter_MODIS(modis_eops, modis_qa_eops): <NEW_LINE> <INDENT> feature = (FeatureType.DATA, 'AOD_Valid') <NEW_LINE> add_feature = AddFeature(feature) <NEW_LINE> with warnings.catch_warnings(): <NEW_LINE> <INDENT> warnings.simplefilter("ignore", category=RuntimeWarning) <NEW_LINE> for index, modis_eop in enumerate(mod...
Filter the low quality MODIS pixels and add new filtered band to the eopatch :param modis_eops: Eopatch where MODIS bands are stored :param modis_qa_eops: Eopatch where QA bands are stored :return: None
625941d40a366e3fb873ea0b
def receive(client_socket): <NEW_LINE> <INDENT> data = "" <NEW_LINE> size = 0 <NEW_LINE> while not re.search(".*\r\n\r\n", data): <NEW_LINE> <INDENT> data += client_socket.recv(1024) <NEW_LINE> <DEDENT> if CONTENT_LENGH.search(data): <NEW_LINE> <INDENT> size = int(CONTENT_LENGH.search(data).group(1)) <NEW_LINE> while n...
:param func: the exit funcsion of the while loop. :param client_socket: the comm socket :return: the data thet was recived from the socket
625941d421a7993f00bc7ee1
def exec(self): <NEW_LINE> <INDENT> self.running = True <NEW_LINE> while self.running: <NEW_LINE> <INDENT> for event in pygame.event.get(): <NEW_LINE> <INDENT> if event.type == pygame.QUIT: <NEW_LINE> <INDENT> sys.exit() <NEW_LINE> <DEDENT> elif event.type == pygame.KEYDOWN: <NEW_LINE> <INDENT> self.keydown(event.key) ...
Execute the game loop.
625941d444b2445a33932284
def generateDataBase(self): <NEW_LINE> <INDENT> from database import TrainingDataBase <NEW_LINE> from wordparser import WordParser <NEW_LINE> database = TrainingDataBase() <NEW_LINE> for file_path in self._file_list: <NEW_LINE> <INDENT> contents = self._readFileContents(file_path) <NEW_LINE> for line in contents.split(...
This function generates traning database base on list of text files Input: Nothing Returns: Training database
625941d40a50d4780f667083
def _next_legen_der(n, x, p0, p01, p0d, p0dd): <NEW_LINE> <INDENT> help_ = p0 <NEW_LINE> helpd = p0d <NEW_LINE> p0 = ((2 * n - 1) * x * help_ - (n - 1) * p01) / n <NEW_LINE> p0d = n * help_ + x * helpd <NEW_LINE> p0dd = (n + 1) * helpd + x * p0dd <NEW_LINE> p01 = help_ <NEW_LINE> return p0, p0d, p0dd
Compute the next Legendre polynomial and its derivatives.
625941d4cdde0d52a9e53223
@app.route('/free_agents/<player_id>') <NEW_LINE> def free_agent_details(player_id): <NEW_LINE> <INDENT> player = mongo.db.players.find_one({'_id': ObjectId(player_id)}) <NEW_LINE> return render_template("free_agent_details.html", player=player)
Renders the free agent profile page for a free agent with matching player id
625941d4dc8b845886cb5725
def open_as_df(collection_name): <NEW_LINE> <INDENT> table = open_database_collection(collection_name) <NEW_LINE> t_list = table_to_list(table) <NEW_LINE> df = pd.DataFrame(t_list) <NEW_LINE> return df
Takes a collection name and opens that collection as a pandas dataframe
625941d407f4c71912b11673
def annToRLE(self, ann, height, width): <NEW_LINE> <INDENT> segm = ann["segmentation"] <NEW_LINE> if isinstance(segm, list): <NEW_LINE> <INDENT> rles = maskUtils.frPyObjects(segm, height, width) <NEW_LINE> rle = maskUtils.merge(rles) <NEW_LINE> <DEDENT> elif isinstance(segm["counts"], list): <NEW_LINE> <INDENT> rle = m...
将标注(可能是多边形/未压缩RLE/RLE)压缩为RLE格式
625941d4c432627299f04e37