code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def convert_window(self, window): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for token in window.tokens: <NEW_LINE> <INDENT> any_digits = self.regexp_contains_digits.search(token.word) is not None <NEW_LINE> result.append(["cD=%d" % (int(any_digits))]) <NEW_LINE> <DEDENT> return result
Converts a Window object into a list of lists of features, where features are strings. Args: window: The Window object (defined in datasets.py) to use. Returns: List of lists of features. One list of features for each token. Each list can contain any number of features (including 0). Each feature is...
625941f67cff6e4e81117fd7
def download_auxcal(): <NEW_LINE> <INDENT> cwd = os.getcwd() <NEW_LINE> os.chdir(os.environ['AUXCAL']) <NEW_LINE> print('Downloading S1 AUXILARY DATA...') <NEW_LINE> url = 'https://s1qc.asf.alaska.edu/aux_cal' <NEW_LINE> cmd = 'wget -r -l2 -nc -nd -np -nH -A SAFE {}'.format(url) <NEW_LINE> print(cmd) <NEW_LINE> os.syst...
Auxilary data files <20Mb, just download all of them! NOTE: probably can be simplified! see download_orbit
625941f6711fe17d825429ae
def _apply_clusters(self, cluster_labels, cmd_name, function): <NEW_LINE> <INDENT> if self._clusters is None: <NEW_LINE> <INDENT> raise RuntimeError('self._clusters must be initialised first') <NEW_LINE> <DEDENT> new_list_id, new_matrix = function(cluster_labels, self._list_id, self._matrix) <NEW_LINE> cmd_name = '%s-c...
Return a new `Context` which only contains hosts returned by `function` `cluster_labels` is a list of integer containing labels to remove or select, depending on `function` `cmd_name` is a string representing the function
625941f69c8ee82313fbbdc9
def getPluginMethod(self, plugin): <NEW_LINE> <INDENT> return self.app.Hooking.findClass("onAddPage", plugin)
Get other plugin hooked object by class name
625941f6dd821e528d63b7f5
def searchInsert(self, nums, target): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> j = len(nums) - 1 <NEW_LINE> while True: <NEW_LINE> <INDENT> if j < 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if i >= j: <NEW_LINE> <INDENT> return i + 1 if nums[i] < target else i <NEW_LINE> <DEDENT> mid = int((i + j) / 2) <NEW_LINE> ...
:type nums: List[int] :type target: int :rtype: int
625941f65fc7496912cc3fcf
def static_evaluate(self, compiler, expr, arg_list): <NEW_LINE> <INDENT> return None
Do static evaluation of expressions when possible
625941f6ad47b63b2c50a5d2
def hms_to_hours(h, m, s): <NEW_LINE> <INDENT> check_hms_ranges(h, m, s) <NEW_LINE> sign = np.copysign(1.0, h) <NEW_LINE> try: <NEW_LINE> <INDENT> h = np.floor(np.abs(h)) <NEW_LINE> m = np.floor(np.abs(m)) <NEW_LINE> s = np.abs(s) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValueError(format_except...
Convert hour, minute, second to a float hour value.
625941f6099cdd3c635f12aa
def get_https(self, session): <NEW_LINE> <INDENT> url = utils.urljoin(self.base_path, self.id, 'https-info') <NEW_LINE> endpoint_override = self.service.get_endpoint_override() <NEW_LINE> resp = session.get(url, endpoint_filter=self.service, endpoint_override=endpoint_override) <NEW_LINE> resp_json = resp.json() <NEW_L...
Obtains the certificate for the acceleration domain name :param session: The session to use for making this request. :type session: :class:`~openstack.session.Session` :returns: The HTTPS certificate of this domain name :rtype: dict
625941f621bff66bcd684f9e
def scale_larger(self): <NEW_LINE> <INDENT> new_factor = self._zoom_factor + 0.1 <NEW_LINE> if 0 < float(new_factor) < self._MAX_ZOOM: <NEW_LINE> <INDENT> self._zoom_factor = new_factor
Increases the zoom of the graph one step (0.1 units).
625941f621bff66bcd684f9f
def close(self): <NEW_LINE> <INDENT> if self._closed: <NEW_LINE> <INDENT> raise err.Error("Already closed") <NEW_LINE> <DEDENT> self._closed = True
Send the quit message and close the socket. See `Connection.close() <https://www.python.org/dev/peps/pep-0249/#Connection.close>`_ in the specification. :raise Error: If the connection is already closed.
625941f6d18da76e23532b31
def get_item_loans_notes(req, loan_id=None, recid=None, add_notes=None, new_note=None, ln=CFG_SITE_LANG): <NEW_LINE> <INDENT> return bal.get_item_loans_notes(req, loan_id, recid, add_notes, new_note, ln)
http://cds.cern.ch/admin/bibcirculation/bibcirculationadmin.py/get_item_loans_notes
625941f64f88993c3716c6b2
def mutate( model, mom, mutation_rate ) : <NEW_LINE> <INDENT> for i in xrange( 1, len(mom) ) : <NEW_LINE> <INDENT> if random() < mutation_rate : <NEW_LINE> <INDENT> mom[i] = choice( model.adjLst[mom[i-1]] ) <NEW_LINE> <DEDENT> <DEDENT> return mom
Mutation idea one
625941f6cdde0d52a9e5368b
def _dict_to_typestring(self, dictionary: Dict) -> Dict: <NEW_LINE> <INDENT> return {self._key_to_typestring(key): self._value_to_typestring(value) for key, value in dictionary.items()}
Turns all contents of a dict into typestrings.
625941f6aad79263cf39109d
def _generate_otp_params(self): <NEW_LINE> <INDENT> public_id, _ = split_id_otp(self.client_data['otp']) <NEW_LINE> otp_result = self._lookup_otp() <NEW_LINE> otp_params = {'public_id': public_id, 'nonce': self.client_data['nonce'], 'otp': self.client_data['otp'], 'modified': create_timestamp()} <NEW_LINE> return otp_p...
using the otp in the client_data generate all of the otp_params needed 'public_id', 'otp', 'nonce',counters, 'use', 'high', 'low' :return: a dict which has all of the otp_params
625941f62c8b7c6e89b35e0d
def list_subscriptions(project, topic_name): <NEW_LINE> <INDENT> subscriber = pubsub_v1.SubscriberClient() <NEW_LINE> topic_path = subscriber.topic_path(project, topic_name) <NEW_LINE> for subscription in subscriber.list_subscriptions(topic_path): <NEW_LINE> <INDENT> print(subscription.name)
Lists all subscriptions for a given topic.
625941f6bf627c535bc13822
def inst_closure(vm, arity, body_code, isvararg): <NEW_LINE> <INDENT> closure = Closure(arity, body_code, vm.regs[vm.REG_ENV], isvararg=isvararg) <NEW_LINE> vm.regs[vm.REG_VAL] = closure <NEW_LINE> vm.regs[vm.REG_PC] += 1
Create a new closure and save it in VAL.
625941f68da39b475bd655cf
@decorators.aws_resource(SubnetGroup, RESOURCE_TYPE) <NEW_LINE> @decorators.wait_for_status(status_good=['Complete']) <NEW_LINE> def create(ctx, iface, resource_config, **_): <NEW_LINE> <INDENT> params = dict() if not resource_config else resource_config.copy() <NEW_LINE> node_subnet_ids = params.get('SubnetIds'...
Creates an AWS RDS Subnet Group
625941f6a4f1c619b28b067b
def __init__(self, dirname='.', ignore=None): <NEW_LINE> <INDENT> list.__init__(self) <NEW_LINE> self.top_dir = dirname <NEW_LINE> if ignore is None: <NEW_LINE> <INDENT> self.ignore = set(['.tox']) <NEW_LINE> <DEDENT> self.read_py_files()
Read py-files and evaluate them.
625941f6046cf37aa974d393
def postProcessing(self, f_val: List[float]) -> Union[np.array, List[float]]: <NEW_LINE> <INDENT> fc_0_0 = f_val['fc_0_0'].T <NEW_LINE> fc_0_1 = f_val['fc_0_1'].T <NEW_LINE> fc_m1_0 = f_val['fc_m1_0'].T <NEW_LINE> fc_0_1 = f_val['fc_0_1'].T <NEW_LINE> fc_0_m1 = f_val['fc_0_m1'].T <NEW_LINE> f_0_0 = np.reshap...
Combines the 5 outputs into one heatmap and calculates the gaze location. Keyword arguments: f_val -- output of the Caffe model
625941f6cb5e8a47e48b80f1
def enable_editing(self, enable): <NEW_LINE> <INDENT> self._editable = enable <NEW_LINE> self._update_btn_position()
Enable or disable editing of the widget. This is provided as required for widgets that are used as both editor and display. :param bool enable: ``True`` to enable, ``False`` to disable
625941f6f8510a7c17cf9d54
@task <NEW_LINE> def create_kw_docs(c): <NEW_LINE> <INDENT> libdoc(str( Path('src/JavaPropertiesLibrary/keywords/JavaPropertiesLibrary.py')), str(Path('docs/JavaPropertiesLibrary.html')))
Generates the library keyword documentation Documentation is generated by using the Libdoc tool.
625941f6d10714528d60033e
def get_zip_resources(zip_pkg, pkg_name, content_folders, content_files): <NEW_LINE> <INDENT> if exists(zip_pkg): <NEW_LINE> <INDENT> with zipfile.ZipFile(zip_pkg, 'r') as z: <NEW_LINE> <INDENT> for item in z.infolist(): <NEW_LINE> <INDENT> file_name = item.filename <NEW_LINE> if EXCLUDE_PATTERN.search(file_name) is No...
Get resources in archive that are not already in the lists.
625941f615fb5d323cde116c
def test_is_avsc_file(self): <NEW_LINE> <INDENT> is_avsc = is_avsc_file(get_joined_path(self.nest_dir, 'test2.avsc')) <NEW_LINE> is_not_avsc = is_avsc_file(get_joined_path(self.nest_dir, 'bad.txt')) <NEW_LINE> self.assertTrue( is_avsc, '/tmp/avro/nest/test2.avsc is an avsc file!' ) <NEW_LINE> self.assertFalse( is_not_a...
test the is_avsc_file function
625941f623e79379d52eebad
def RunGetOutput(cmd, no_output, chk_err=True): <NEW_LINE> <INDENT> def check_output(no_output, *popenargs, **kwargs): <NEW_LINE> <INDENT> if 'stdout' in kwargs: <NEW_LINE> <INDENT> raise ValueError( 'stdout argument not allowed, it will be overridden.') <NEW_LINE> <DEDENT> if no_output: <NEW_LINE> <INDENT> out_file = ...
Wrapper for subprocess.check_output. Execute 'cmd'. Returns return code and STDOUT, trapping expected exceptions. Reports exceptions to Error if chk_err parameter is True
625941f68e05c05ec3eea9cd
def e(self, t=None): <NEW_LINE> <INDENT> return self._params(t=t)[0]
Return the e vector at a specified time. Parameters ---------- t : array_like, optional A time or array of times at which to retrieve e. Returns ------- e : ndarray e vector at the specified time steps.
625941f6dc8b845886cb5b89
def execute(self): <NEW_LINE> <INDENT> if self.disk_dvr.mp_uuid in self.disk_dvr.vios_uuids: <NEW_LINE> <INDENT> dev_name = self.disk_dvr.get_bootdisk_path( self.instance, self.disk_dvr.mp_uuid) <NEW_LINE> if dev_name is not None: <NEW_LINE> <INDENT> return None, None, dev_name <NEW_LINE> <DEDENT> <DEDENT> self.stg_ele...
Map the instance's boot disk and discover it.
625941f6cdde0d52a9e5368c
def research(self, word): <NEW_LINE> <INDENT> logging.info("Searching the web for word " + word) <NEW_LINE> words = [] <NEW_LINE> headers = {'X-Mashape-Key': self.WORDS_API_KEY, 'Accept': 'application/json'} <NEW_LINE> request = requests.get(self.WORDS_API_HOST + word, headers=headers) <NEW_LINE> content = json.loads(r...
Searches for a word on the internet Args: word (str): the word we want to know about Returns: list: A list of words related to the word passed in argument
625941f6d58c6744b42582af
def search(self, nums, target): <NEW_LINE> <INDENT> l, r = 0, len(nums) - 1 <NEW_LINE> while l <= r: <NEW_LINE> <INDENT> m = (l + r) // 2 <NEW_LINE> if nums[m] == target: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> while l < m and nums[m] == nums[l]: <NEW_LINE> <INDENT> l += 1 <NEW_LINE> <DEDENT> if nums[m] >= ...
Potentially O(n) solution but O(logn) solution is not possible for this question since there are duplicate elements, so you need to linearly search through the elements to get rid of the duplicates otherwise you don't know which side to go after current step
625941f666656f66f7cbc800
def get_report(self, product_type: Union[str, List[str]] = None) -> Any: <NEW_LINE> <INDENT> url = "{0}/reports/participants/user/v1/allbalances".format(self.api_url) <NEW_LINE> params = { "productType": ",".join(product_type) if type(product_type) is list else product_type } <NEW_LINE> response = self.session.get(url,...
10.1.1. List of all balances for a client's own and connected products. Args: product_type (Union[str, List[str]], optional): Filter by one or more of "ACCOUNT", "CARD", "DEPOT", "LOAN", "SAVINGS" (list or comma-separated string). Defaults to None. Returns: Any: Response object
625941f69f2886367277aeda
def filter_params(self, src_mod): <NEW_LINE> <INDENT> STRIKE_PARAMS[src_mod.num_np:] = [] <NEW_LINE> DIP_PARAMS[src_mod.num_np:] = [] <NEW_LINE> RAKE_PARAMS[src_mod.num_np:] = [] <NEW_LINE> NPW_PARAMS[src_mod.num_np:] = [] <NEW_LINE> HDEPTH_PARAMS[src_mod.num_hd:] = [] <NEW_LINE> HDW_PARAMS[src_mod.num_hd:] = [] <NEW_L...
Remove params unneeded by source_model
625941f607d97122c4178eee
def test_toElementBooleanTextSingle(self): <NEW_LINE> <INDENT> field = data_form.Field(var='test', value=True) <NEW_LINE> element = field.toElement() <NEW_LINE> self.assertEqual(u'true', unicode(element.value))
A boolean value should render to text if the field type is text-single.
625941f6004d5f362079a981
def showDescription(self): <NEW_LINE> <INDENT> self.heading.setText(singleMessage.messages['description_heading']) <NEW_LINE> descriptionText = singleMessage.messages['description_Content'] <NEW_LINE> self.content.setText(descriptionText) <NEW_LINE> self.description_btn.setDisabled(True) <NEW_LINE> self.author_and_lice...
Show Description
625941f630c21e258bdfaaf8
@click.command('init-db') <NEW_LINE> @with_appcontext <NEW_LINE> def init_db_command(): <NEW_LINE> <INDENT> init_db() <NEW_LINE> collect_data_command() <NEW_LINE> click.echo('Initialized the database.')
Clear the existing data and create new tables.
625941f65166f23b2e1a57ac
def heatmap(AUC, title, xlabel, ylabel, xticklabels, yticklabels, figure_width=40, figure_height=20, correct_orientation=False, cmap='RdBu'): <NEW_LINE> <INDENT> fig, ax = plt.subplots() <NEW_LINE> c = ax.pcolor(AUC, edgecolors='k', linestyle= 'dashed', linewidths=0.2, cmap=cmap) <NEW_LINE> ax.set_yticks(np.arange(AUC....
Inspired by: - http://stackoverflow.com/a/16124677/395857 - http://stackoverflow.com/a/25074150/395857
625941f615fb5d323cde116d
def test_customizations(self): <NEW_LINE> <INDENT> progress = ProgressHelper() <NEW_LINE> progress.set_bar_width(10) <NEW_LINE> progress.set_bar_character('_') <NEW_LINE> progress.set_empty_bar_character(' ') <NEW_LINE> progress.set_progress_character('/') <NEW_LINE> progress.set_display_format(' %current%/%max% [%bar%...
Customizing ProgressHelper should be possible
625941f696565a6dacc8fd1c
def merge_dicts_by_weight(dicts): <NEW_LINE> <INDENT> _ = {} <NEW_LINE> for d in dicts: <NEW_LINE> <INDENT> for k in d: <NEW_LINE> <INDENT> existing_value = _.get(k) <NEW_LINE> if existing_value is None or existing_value > d[k]: <NEW_LINE> <INDENT> _[k] = d[k] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return _
Merge dicts by the lowest weight
625941f60a366e3fb873ee73
@views.route('/') <NEW_LINE> def index(): <NEW_LINE> <INDENT> return render_template('index.html', session=session)
Render index.
625941f67d847024c06be914
def _parse_response(self, response): <NEW_LINE> <INDENT> if not response: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if response.code == 204: <NEW_LINE> <INDENT> logger.debug("no content") <NEW_LINE> return "" <NEW_LINE> <DEDENT> rsp_data = response <NEW_LINE> with suppress(KeyError): <NEW_LINE> <INDENT> if re...
Parse response
625941f6462c4b4f79d1dd22
def logout(self, client_id, return_to, federated=False): <NEW_LINE> <INDENT> return_to = quote_plus(return_to) <NEW_LINE> if federated is True: <NEW_LINE> <INDENT> return self.get( 'https://{}/v2/logout?federated&client_id={}&returnTo={}'.format( self.domain, client_id, return_to), headers={'Content-Type': 'application...
Logout Use this endpoint to logout a user. If you want to navigate the user to a specific URL after the logout, set that URL at the returnTo parameter. The URL should be included in any the appropriate Allowed Logout URLs list: Args: client_id (str): The client_id of your application. returnTo (str): URL to ...
625941f65fc7496912cc3fd0
def __init__(self, file_to_parse, pickle_path): <NEW_LINE> <INDENT> self.input_path = file_to_parse <NEW_LINE> self.output_path = pickle_path <NEW_LINE> self.converted_doc = None
Constructor
625941f663d6d428bbe44b44
def softmax_loss_vectorized(W, X, y, reg): <NEW_LINE> <INDENT> loss = 0.0 <NEW_LINE> dW = np.zeros_like(W) <NEW_LINE> num_train = X.shape[0] <NEW_LINE> num_class = W.shape[1] <NEW_LINE> score = X.dot(W) <NEW_LINE> score -= np.max(score, axis=1).reshape((-1, 1)) <NEW_LINE> exp_sum = np.sum(np.exp(score), axis=1).reshape...
Softmax loss function, vectorized version. Inputs and outputs are the same as softmax_loss_naive.
625941f6eab8aa0e5d26e1ad
def addition(self,mat_B): <NEW_LINE> <INDENT> size_A = np.shape(self.mat_A) <NEW_LINE> size_B = np.shape(mat_B) <NEW_LINE> if size_A == size_B: <NEW_LINE> <INDENT> result = [[self.mat_A[i][j] + mat_B[i][j] for j in range(len(self.mat_A[0]))] for i in range(len(self.mat_A))] <NEW_LINE> return result <NEW_LINE> <DEDENT>...
Function to add two matrices. Args: mat_B(list): second matrix Returns: result(list): addition of two matrices
625941f673bcbd0ca4b2c6c8
def __set__(self, instance, value): <NEW_LINE> <INDENT> instance._indirect_references = getattr(instance, '_indirect_references', {}) <NEW_LINE> instance._indirect_references[self.field] = value <NEW_LINE> if value: <NEW_LINE> <INDENT> setattr(instance, self.field.attname, value.pk) <NEW_LINE> setattr(instance, self.fi...
Here we have to store the referenced object in a temporary attribute of instance and set a temporary Fossil instance to the field.
625941f64428ac0f6e5bae4b
def heapify2(self, index): <NEW_LINE> <INDENT> if index >= self.size: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> left = index * 2 + 1 <NEW_LINE> if left >= self.size: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> right = left + 1 <NEW_LINE> largest = left if right < self.size or self._heap[left] > self._heap[right...
递归版本实现
625941f60a366e3fb873ee74
def change(query: str, params): <NEW_LINE> <INDENT> with sqlite3.connect(DB_FILE) as conn: <NEW_LINE> <INDENT> c = conn.cursor() <NEW_LINE> c.execute(query, params) <NEW_LINE> conn.commit()
Executes a given query and commits changes.
625941f64f88993c3716c6b3
def reg_logistic_regression(y, tx, lambda_, initial_w, max_iters, gamma): <NEW_LINE> <INDENT> w = initial_w <NEW_LINE> for i in range(max_iters): <NEW_LINE> <INDENT> for y_batch, tx_batch in batch_iter(y, tx, batch_size=100, num_batches=1): <NEW_LINE> <INDENT> loss = compute_loss_lr(y_batch, tx_batch, w) + lambda_/2 * ...
Regularized logistic regression using gradient descent or SGD.
625941f691af0d3eaac9c071
def getRawResults(self): <NEW_LINE> <INDENT> return self._rawresults
Returns a dictionary containing the parsed results data Each dict key is the results row ID (usually AR ID or Worksheet's Reference Sample ID). Each item is another dictionary, in which the key is a the AS Keyword. Inside the AS dict, the column 'DefaultResult' must be provided, that maps to the column from which the d...
625941f64428ac0f6e5bae4c
def make_tf_dataset( self, batch_size=None, prefetch=None, num_epochs=None, workers_count=None, shuffling_queue_capacity=None, **petastorm_reader_kwargs ): <NEW_LINE> <INDENT> self._check_and_set_overriden_petastorm_args( petastorm_reader_kwargs, num_epochs=num_epochs, workers_count=workers_count) <NEW_LINE> return TFD...
Make a tensorflow dataset. This method will do the following two steps: 1) Open a petastorm reader on the materialized dataset dir. 2) Create a tensorflow dataset based on the reader created in (1) :param batch_size: The number of items to return per batch. Default ``None``. If ``None``, current implementatio...
625941f663f4b57ef0001759
def value_from_datadict(self, data, files, name): <NEW_LINE> <INDENT> if data.has_key(name): <NEW_LINE> <INDENT> if isinstance(data[name], datetime.datetime): <NEW_LINE> <INDENT> if isinstance(self.widgets[0], forms.DateInput) and isinstance(self.widgets[1], forms.TimeInput): <NEW_LINE> <INDENT> data[name + '_0'] = dat...
Quick dirty solution. Fix SplitDateTimeWidget bugs when displaying the form with SplitDateTimeField. (Original problem: SplitDateTimeField can not display the field data into the seperated DateInput and TimeInput)
625941f6e76e3b2f99f3ae53
def put_user_env(swift, container_name, env): <NEW_LINE> <INDENT> swiftutils.put_object_string( swift, container_name, constants.USER_ENVIRONMENT, yaml.safe_dump(env, default_flow_style=False) )
Convert given user environment to yaml and upload it to Swift.
625941f60fa83653e465760a
def rover_coords(binary_img): <NEW_LINE> <INDENT> ypos, xpos = binary_img.nonzero() <NEW_LINE> x_pixel = -(ypos - binary_img.shape[0]).astype(np.float) <NEW_LINE> y_pixel = -(xpos - binary_img.shape[1] / 2).astype(np.float) <NEW_LINE> return x_pixel, y_pixel
Converts from image coordinates to rover coordinates. Accepts the binary image returned from color_thresh(). Returns [x, y] coordinates with an origin at the Rover's camera.
625941f6f8510a7c17cf9d55
def access_get(self, path): <NEW_LINE> <INDENT> feature = self.xfeature_get(path) <NEW_LINE> if not feature: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> permissions = self.feature_dict(feature) <NEW_LINE> if READ in permissions: <NEW_LINE> <INDENT> permissions['read'] = permissions[READ] <NEW_LINE> del(permission...
Get permissions for path.
625941f607f4c71912b11ad8
def remove(self, name): <NEW_LINE> <INDENT> os.unlink("%s/%s" % (self.directory_path, name))
Remove the named message.
625941f6be8e80087fb2128a
def execute_put(self, endpoint, data=None): <NEW_LINE> <INDENT> return self._execute("put", endpoint, data)
Execute a REST call using PUT
625941f6cc40096d61595fa0
def wordBreak(self, s, wordDict): <NEW_LINE> <INDENT> word_trie = PrefixTrie(wordDict) <NEW_LINE> possible_sentences = [[] for i in range(len(s))] <NEW_LINE> for i in range(len(s)-1,-1,-1): <NEW_LINE> <INDENT> possible_words = word_trie.possible_words_at_index(s,i) <NEW_LINE> for word in possible_words: <NEW_LINE> <IND...
:type s: str :type wordDict: List[str] :rtype: List[str]
625941f6d486a94d0b98e79a
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, RoomSpaceSwapPreferenceItem): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941f6eab8aa0e5d26e1ae
def dfs(digits, dic, index, path, res): <NEW_LINE> <INDENT> if len(path) == len(digits): <NEW_LINE> <INDENT> res.append(path) <NEW_LINE> return <NEW_LINE> <DEDENT> for i in range(index, len(digits)): <NEW_LINE> <INDENT> for j in dic[digits[i]]: <NEW_LINE> <INDENT> dfs(digits, dic, i + 1, path + j, res)
DFS.
625941f6adb09d7d5db6cddf
def test_update_preferential_attachment(self): <NEW_LINE> <INDENT> update = solver.update_preferential_attachment <NEW_LINE> assert_equal(3, len(update(np.array([0, 1]), 1, 1, 1))) <NEW_LINE> assert_equal(3, len(update(np.array([0, 1, 0]), 1, 1, 1))) <NEW_LINE> def manual_update(b, g, t): <NEW_LINE> <INDENT> return np....
[solver.py] Unit test for update_preferential_attachment.
625941f660cbc95b062c6b97
def deleteMatches(): <NEW_LINE> <INDENT> db = connect() <NEW_LINE> cursor = db.cursor() <NEW_LINE> cursor.execute("DELETE FROM matches *") <NEW_LINE> db.commit() <NEW_LINE> cursor.close() <NEW_LINE> db.close()
Remove all the match records from the database.
625941f66fb2d068a760f6fb
def countBinarySubstrings(self, s): <NEW_LINE> <INDENT> group = [1] <NEW_LINE> for i in range(1, len(s)): <NEW_LINE> <INDENT> if s[i] == s[i-1]: <NEW_LINE> <INDENT> group[-1] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> group.append(1) <NEW_LINE> <DEDENT> <DEDENT> ans = 0 <NEW_LINE> for i in range(0, len(group) -...
:type s: str :rtype: int
625941f6a79ad161976cc799
def test_non_default_construction(self): <NEW_LINE> <INDENT> m = Material((1,1,1)) <NEW_LINE> nt.assert_almost_equal(m.color, (1,1,1)) <NEW_LINE> nt.assert_almost_equal(m.color, m(None, None, None, None))
Test if the material is constructed correctly with non-default parameters.
625941f6bde94217f368343e
def test_po_login(self): <NEW_LINE> <INDENT> base_url=dom_xml('url') <NEW_LINE> data=open_csv('po_data.csv',1) <NEW_LINE> self.driver.get(base_url) <NEW_LINE> self.driver.refresh() <NEW_LINE> wait_by_linkText(self.driver,'登录') <NEW_LINE> self.driver.find_element_by_link_text('登录').click() <NEW_LINE> time.sleep(2) <NEW_...
测试正确的用户名和密码登录
625941f6a934411ee3751ce9
def set_types_acf(kmc_model, site_property): <NEW_LINE> <INDENT> types = get_types_acf(kmc_model) <NEW_LINE> for i in range(len(types)): <NEW_LINE> <INDENT> if types[i] == 0: <NEW_LINE> <INDENT> kmc_model.base_acf.set_types(i + 1, site_property) <NEW_LINE> break
Set the properties, which are given by the user to a type index.
625941f61d351010ab85616e
def file_download(self, file_name, destination, download_async='true'): <NEW_LINE> <INDENT> file_name = urllib.parse.quote(file_name, safe='') <NEW_LINE> destination = urllib.parse.quote(destination, safe='') <NEW_LINE> file_download_api = '{}/{}/{}?destination={}&async={}'.format(self._start_url, 'download', file_name...
Download file from DxChain Network :param file_name: file you are trying to download from DxChain Network :param destination: absolute path, where to place downloaded file :param download_async: download file in async way
625941f645492302aab5e91e
def _get_ruleobjs_from_components(pyobj=None): <NEW_LINE> <INDENT> if not pyobj: <NEW_LINE> <INDENT> raise RulesError("Expecting list of lists of rule components.") <NEW_LINE> <DEDENT> ruleobj_list = [] <NEW_LINE> for item in pyobj: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if Rule(*item).is_valid(): <NEW_LINE> <IND...
Return list of Rule objects from list of lists of rule components.
625941f6283ffb24f3c55f4d
def test_instantiate(self): <NEW_LINE> <INDENT> with (self.assertRaises(TypeError)): <NEW_LINE> <INDENT> square1 = Square() <NEW_LINE> <DEDENT> square2 = Square(3) <NEW_LINE> self.assertEqual(square2.width, 3) <NEW_LINE> self.assertEqual(square2.height, 3) <NEW_LINE> self.assertEqual(square2.x, 0) <NEW_LINE> self.asser...
Test instantiation
625941f650812a4eaa59c96e
def get_status_with_http_info(self, id, **kwargs): <NEW_LINE> <INDENT> all_params = ['id'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LINE> params = locals() <NEW_...
Get status of machine translate engine # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_status_with_http_info(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: (r...
625941f63539df3088e2e99f
def compute_ll(dist, x): <NEW_LINE> <INDENT> if isinstance(dist, Normal): <NEW_LINE> <INDENT> ll = dist.log_prob(x).mean(1, keepdims=True) <NEW_LINE> <DEDENT> elif isinstance(dist, Categorical): <NEW_LINE> <INDENT> ll = dist.log_prob(x.view(-1)).unsqueeze(1) <NEW_LINE> <DEDENT> elif isinstance(dist, MultivariateNormal)...
Function to compute the log likelihood depending on the output distribution.
625941f6925a0f43d254a4d1
def add_complement_header(self, address, number, complement, district, postal, name, phone): <NEW_LINE> <INDENT> self.add(SintegraRegister11( address, number, complement, district, postal, name, phone))
Receive values to generate Sintegra Register type 11. :param address: the branch address. :param number: the number of the branch address. :param complement: the complement of the branch address. :param district: district of the branch address. :param postal: postal code number of the branch address. :param name: the ...
625941f607f4c71912b11ad9
def testShowPsfMosaic(self): <NEW_LINE> <INDENT> testDisplay = display if display else afwDisplay.getDisplay(backend="virtualDevice") <NEW_LINE> mos = showPsfMosaic(self.exposure, showEllipticity=True, showFwhm=True, display=testDisplay) <NEW_LINE> self.assertTrue(len(mos.images) > 0)
Test that the showPsfMosaic function works. This function is usually called without display=None, which would activate ds9
625941f667a9b606de4a8509
def get_data(self): <NEW_LINE> <INDENT> return [self.k]
Returns the parameter k.
625941f64a966d76dd55166a
def hasNext(self): <NEW_LINE> <INDENT> return len(self.values)>0
:rtype: bool
625941f6d8ef3951e3243b91
def v2na(a, old = 0.0, new = np.nan): <NEW_LINE> <INDENT> return _v2na(a, old = old, new = new)
replaces an old value with a new value (default is nan) :Examples: -------------- >>> from pyg import * >>> a = np.array([1., np.nan, 1., 0.]) >>> assert eq(v2na(a), np.array([1., np.nan, 1., np.nan])) >>> assert eq(v2na(a,1), np.array([np.nan, np.nan, np.nan, 0])) >>> assert eq(v2na(a,1,0), np.array([0., np.nan, 0., ...
625941f68c3a873295158a17
def splitData(data, fold=0): <NEW_LINE> <INDENT> data = np.array(data) <NEW_LINE> X = data[:, :-1] <NEW_LINE> y = data[:, -1:] <NEW_LINE> y = np.ravel(y) <NEW_LINE> if fold > 0: <NEW_LINE> <INDENT> kfolds = KFold(n_splits=fold, shuffle=True) <NEW_LINE> folded_data = [] <NEW_LINE> for train_inds, test_inds in kfolds.spl...
Divide data into Testing, Validation, and Training segments or, if a fold value is provided, into k cross-validation folds
625941f6e8904600ed9f258c
def set_work_period(self, read=False, work_time=0): <NEW_LINE> <INDENT> assert work_time >= 0 and work_time <= 30 <NEW_LINE> cmd = self.cmd_begin() <NEW_LINE> cmd += (self.WORK_PERIOD_CMD + (self.READ if read else self.WRITE) + bytes([work_time]) + b"\x00" * 10) <NEW_LINE> cmd = self._finish_cmd(cmd) <NEW_LINE> self._e...
Get work period command. Does not contain checksum and tail. @rtype: list
625941f6d99f1b3c44c67bd6
def _getGmError(self, classify, x, y, sample_weight): <NEW_LINE> <INDENT> error_rate = 0 <NEW_LINE> error_index = [] <NEW_LINE> for i in range(len(x)): <NEW_LINE> <INDENT> if y[i] != classify.predict(x[i]): <NEW_LINE> <INDENT> error_rate += sample_weight[i] <NEW_LINE> error_index.append(i) <NEW_LINE> <DEDENT> <DEDENT> ...
计算新的单分类器的分类误差,用来更新样本和分类器的权值 :param classify: :param x: :param y: :param sample_weight: :return:
625941f69c8ee82313fbbdcb
def dict_for_row(self, row): <NEW_LINE> <INDENT> kwargs = { 'number': row[0], 'lastname': row[1], 'firstname': row[2], 'hand': row[3], 'position': row[4], 'height': row[5], 'weight': row[6], 'year': row[7], 'hometown': row[8], 'highschool': row[9], 'story': row[10], } <NEW_LINE> return kwargs
Get a row of data, return a dict whose keys are Players properties and values are instance values for that row.
625941f650485f2cf553d3f0
def parameters_create_flat_lcdm(Omega_c, Omega_b, h, norm_pk, n_s, status): <NEW_LINE> <INDENT> return _ccllib.parameters_create_flat_lcdm(Omega_c, Omega_b, h, norm_pk, n_s, status)
parameters_create_flat_lcdm(double Omega_c, double Omega_b, double h, double norm_pk, double n_s, int * status) -> parameters
625941f6a8ecb033257d371e
def connect_account(self, account): <NEW_LINE> <INDENT> raise NotImplementedError
Return an authenticated IMAPClient instance for the given account. This is an optional interface, which is only needed for accounts that are synced using IMAP.
625941f6b545ff76a8914469
@main.route('/t5/') <NEW_LINE> @main.route('/t5/index') <NEW_LINE> def t5_index(): <NEW_LINE> <INDENT> intro_text = 'T5 utilities' <NEW_LINE> links = [ { 'text': 'T5 cargogen', 'uri': '/t5/cargogen', 'api': '/api_doc?endpoint=/t5/cargogen' }, { 'text': 'T5 orbit details', 'uri': '/t5/orbit', 'api': '/api_doc?endpoint=/...
T5 index
625941f616aa5153ce362acd
def _convert_data_similarity( data, perm_type=None, ignore_diagonal=ignore_diagonal ): <NEW_LINE> <INDENT> if (perm_type is None) or (perm_type == "1d"): <NEW_LINE> <INDENT> if ignore_diagonal and (not data.issymmetric): <NEW_LINE> <INDENT> d = data.squareform() <NEW_LINE> data = d[~np.eye(d.shape[0]).astype(bool)] <NE...
Helper function to convert data correctly
625941f63346ee7daa2b33c6
def chunk_minus_offset(self, p, s): <NEW_LINE> <INDENT> return dl_chunk(self, p.address - s, inuse=False)
Treat space at ptr - offset as a chunk
625941f6e1aae11d1e74a312
def calc8456(self,P,F_G,F_Q,F_R,F_B,Tesneni): <NEW_LINE> <INDENT> W_F = (pi/4) * self.f_F * (2 * self.b_F * self.e_F**2 + self.d_0 * (1 - self.ro * self.e_0**2)) <NEW_LINE> self.Phi_F = zeros(len(P)) <NEW_LINE> A = abs(F_B * self.h_G + F_Q * (1 - self.ro**3) * Tesneni.d_Ge / 6 + F_R * (1 - self.ro) * Tesneni.d_Ge / 2) ...
(146)(145)
625941f6566aa707497f4bb3
def exercise_delete_comment(self, fail=True): <NEW_LINE> <INDENT> exercise_1 = Exercise.objects.get(pk=1) <NEW_LINE> comments = exercise_1.exercisecomment_set.all() <NEW_LINE> comment_1: ExerciseComment = comments[0] <NEW_LINE> self.assertEqual(comment_1.id, 1) <NEW_LINE> self.assertEqual(comment_1.comment, "test 123")...
Tests the deletion of exercise comments
625941f621bff66bcd684fa0
def process(options=None,args=None): <NEW_LINE> <INDENT> items = None <NEW_LINE> if options["debug"]: <NEW_LINE> <INDENT> print(options, file=sys.stderr) <NEW_LINE> <DEDENT> prng = RandomState(options['seed']) <NEW_LINE> if options['gold']: <NEW_LINE> <INDENT> goldlabel,golddata = read_data_file(options['gold'], option...
Do the processing
625941f6be7bc26dc91cdc48
def MockModel(self, model_name, *args, **kwargs): <NEW_LINE> <INDENT> test_class_models = self.GetTestClassModule().models <NEW_LINE> if 'models_%s' % model_name not in self._set_mock: <NEW_LINE> <INDENT> self.mox.StubOutWithMock( getattr(self.GetTestClassModule(), 'models'), model_name) <NEW_LINE> for mock in self._se...
Mock creating an instance of a model, and return the mock instance. Args: name: str, name of model, like 'Package' *args: list, optional arguments supplied to model instantiation **kwargs: dict, optional arguments supplied to model instantiation Returns: a new mocked instance of the model
625941f6a8370b7717052ef1
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'teste_oficina.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are yo...
Run administrative tasks.
625941f656ac1b37e6264816
def test_activities(self, activities_list): <NEW_LINE> <INDENT> return EXERCISE_ACTIVITY in activities_list
Overridden to process all of the log files that are passed in.
625941f6d18da76e23532b33
@app.task <NEW_LINE> def poll_audit_status_every_hour_task(): <NEW_LINE> <INDENT> poll_audit_status()
每小时轮询小程序的审核状态
625941f6460517430c3947c7
def __place_details_godparents_style(self): <NEW_LINE> <INDENT> font = FontStyle() <NEW_LINE> font.set(face=FONT_SERIF, size=10, italic=1, bold=0) <NEW_LINE> para = ParagraphStyle() <NEW_LINE> para.set_font(font) <NEW_LINE> para.set(first_indent=0, lmargin=4.5) <NEW_LINE> para.set_description(_('The style used for Godp...
Define the style used for the place details
625941f67cff6e4e81117fda
@enforce_types <NEW_LINE> def copy_and_overwrite(from_path: Union[str, Path], to_path: Union[str, Path]): <NEW_LINE> <INDENT> if Path(from_path).is_dir(): <NEW_LINE> <INDENT> shutil.rmtree(to_path, ignore_errors=True) <NEW_LINE> shutil.copytree(from_path, to_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> with open...
copy a given file or directory to a given path, overwriting the destination
625941f6711fe17d825429b1
def parent(self, index): <NEW_LINE> <INDENT> return QModelIndex()
QModelIndex DNSSD.ServiceModel.parent(QModelIndex index)
625941f61f037a2d8b946850
@fiss_cmd <NEW_LINE> def space_lock(args): <NEW_LINE> <INDENT> r = fapi.lock_workspace(args.project, args.workspace) <NEW_LINE> fapi._check_response_code(r, 204) <NEW_LINE> if fcconfig.verbosity: <NEW_LINE> <INDENT> eprint('Locked workspace {0}/{1}'.format(args.project, args.workspace)) <NEW_LINE> <DEDENT> return 0
Lock a workspace
625941f626068e7796caf33d
def is_cve_tracker(bug_obj): <NEW_LINE> <INDENT> return "SecurityTracking" in bug_obj.keywords and "Security" in bug_obj.keywords
Check if a bug is a CVE tracker. A CVE tracker bug must have `SecurityTracking` and `Security` keywords. :param bug_obj: bug object :returns: True if the bug is a CVE tracker.
625941f623849d37ff7b36de
def test_adolescent_popularity(self): <NEW_LINE> <INDENT> user = UserProfile.objects.all()[0] <NEW_LINE> cd = ClientData.objects.create(region=mkt.regions.BR.id) <NEW_LINE> unknown1 = amo.tests.app_factory() <NEW_LINE> Installed.objects.create(addon=unknown1, user=user, client_data=cd) <NEW_LINE> unknown2 = amo.tests.a...
Adolescent regions use global popularity. Webapp: Global: 0, Regional: 0 Unknown1: Global: 1, Regional: 1 + 10 * 1 = 11 Unknown2: Global: 2, Regional: 0
625941f6ff9c53063f47c844
def send_head(self): <NEW_LINE> <INDENT> path = self.translate_path(self.path) <NEW_LINE> f = None <NEW_LINE> if os.path.isdir(path): <NEW_LINE> <INDENT> parts = urlparse.urlsplit(self.path) <NEW_LINE> if not parts.path.endswith('/'): <NEW_LINE> <INDENT> self.send_response(301) <NEW_LINE> new_parts = (parts[0], parts[1...
Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in which case the caller has nothing furth...
625941f6dc8b845886cb5b8b
def test_invalid_ignore_older(self): <NEW_LINE> <INDENT> self.render_config_template( ignore_older="1 hour", event_logs=[ {"name": "Application"} ] ) <NEW_LINE> self.start_beat(extra_args=["-configtest"]).check_wait(exit_code=1) <NEW_LINE> assert self.log_contains( "Invalid top level ignore_older value '1 hour'")
With -configtest and an error in the configuration, it should return a non-zero error code.
625941f62eb69b55b151cf0e
def to_row(self, fieldnames: list): <NEW_LINE> <INDENT> row = {k: self.data.get(k, "") for k in fieldnames} <NEW_LINE> row[ "name" ] = f'{self.data.get("first_name", "")} {self.data.get("last_name", "")}' <NEW_LINE> for k in self.data["certificates"]: <NEW_LINE> <INDENT> if k in fieldnames: <NEW_LINE> <INDENT> row[k] =...
Extract data from internal structures and put in a csv's row.
625941f6dc8b845886cb5b8c
def _filter_joints(self, state, remove_arm=True): <NEW_LINE> <INDENT> name = [] <NEW_LINE> position = [] <NEW_LINE> for n, pos in zip(state.state.joint_state.name, state.state.joint_state.position): <NEW_LINE> <INDENT> if (remove_arm and all(s not in n for s in self._arm_joints)) or (not remove_arm a...
Filters out the joints that we don't want and their positions :param state: initial state :param remove_arm: If True we remove the arm joints, if False we remove the non-arm joints (hand joints) :return: the filtered state
625941f63346ee7daa2b33c7
def close(self): <NEW_LINE> <INDENT> self._report_file.close() <NEW_LINE> for files in self._output_files.values(): <NEW_LINE> <INDENT> for f in files.values(): <NEW_LINE> <INDENT> f.close()
Implementation of Reporter callback.
625941f6cad5886f8bd2762d