code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def down_p(polynom): <NEW_LINE> <INDENT> while polynom[1][-1][0][1] == 1 and polynom[1][-1][0][2][0] == 0 and polynom[0] > 0: <NEW_LINE> <INDENT> polynom[0] -= 1 <NEW_LINE> del polynom[1][-1] | Удаление нулевых старших коэффициентов
Пока старший коэффициент равен нулю, то удаляет его и понижает степень. | 625941d291af0d3eaac9bbbf |
def log(self, location, pfrom, vto): <NEW_LINE> <INDENT> assert pfrom.shape[1] == location.size <NEW_LINE> assert vto.shape[1] == location.size <NEW_LINE> assert pfrom.shape[0] == vto.shape[0] <NEW_LINE> yxi = np.clip(np.einsum('ij,j->i', pfrom, location), -1.0, 1.0) <NEW_LINE> ind = yxi >= -1.0 + 16*np.spacing(1) <NEW... | exp_l^{-1}(p) = d(l,p) * (p - <p,l>l)/|p - <p,l>l|
and we use |p - <p,l>l| = sqrt(1 - <p,l>^2) (by |p|=|l|=1)
as well as d(l,p) = arccos(<p,l>) | 625941d2c4546d3d9de72bda |
def get_track_from_id(self, psz_id): <NEW_LINE> <INDENT> return libvlc_media_player_get_track_from_id(self, str_to_bytes(psz_id)) | Get a track from a track id.
@param psz_id: valid string representing a track id (cf. psz_id from
ef L{MediaTrack}).
@return: a valid track or None if there is currently no tracks identified by the string id, release it with L{media_track_release}().
@version: LibVLC 4.0.0 and later. This function can be used to get t... | 625941d23317a56b86939dfc |
def getParent(self): <NEW_LINE> <INDENT> pass | getParent() -> IZXhtmlElement
Returns parent element if available else returns None. | 625941d2435de62698dfddf3 |
def _stripIgnore(self): <NEW_LINE> <INDENT> keys = list(self._spe_header.keys()) <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> for toIgnore in SPE.SPE_IGNORE: <NEW_LINE> <INDENT> if toIgnore in key and self._spe_header[key][0] in ('', 0, 0.0): <NEW_LINE> <INDENT> self._spe_header.pop(key) | Remove some headers in .SPE file
| 625941d2442bda511e8be5bd |
def status(): <NEW_LINE> <INDENT> pid = get_pid() <NEW_LINE> if not pid or not pid_exists(pid): <NEW_LINE> <INDENT> print_("daemon not running") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print_("daemon running with pid %s" % pid) <NEW_LINE> <DEDENT> sys.exit(0) | Print daemon status and exit. | 625941d2cb5e8a47e48b7c4e |
def getMagnetic(self): <NEW_LINE> <INDENT> return self.__lsm303dMag.getMagnetic() | Return the magnetic measured from the sensor. | 625941d267a9b606de4a805f |
def save_backend(self, request, propagate=True, gen_change=True, user=None): <NEW_LINE> <INDENT> from accounts.models import ( notify_new_translation, notify_new_contributor ) <NEW_LINE> from trans.models.changes import Change <NEW_LINE> self.translation.update_lock(request) <NEW_LINE> try: <NEW_LINE> <INDENT> (saved, ... | Stores unit to backend. | 625941d2b830903b967e9ab0 |
def test_howto_example_drawing_text(self): <NEW_LINE> <INDENT> test_image = get_image("canvas_2.png") <NEW_LINE> o = get_mock_output() <NEW_LINE> c = Canvas(o, name=c_name) <NEW_LINE> c.text("Hello world", (0, 0)) <NEW_LINE> assert(imgs_are_equal(c.get_image(), test_image)) | tests the first canvas example from howto | 625941d2187af65679ca52c5 |
@bp.route('/<name>/networks') <NEW_LINE> @user_require(False) <NEW_LINE> def list_networks(name): <NEW_LINE> <INDENT> pod = _get_pod(name) <NEW_LINE> return get_core(g.zone).list_networks(pod.name) | List networks under a pod
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
[
{"name": "host", "subnets": [], "__class__": "Network"},
{"name": "bridge", "subnets": ["172.17.0.0/16"], "__class__": "Network"}
] | 625941d29f2886367277aa32 |
def find_prefix(self, prev): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> next_letter = input("Enter another letter or quit {p}".format( p=prev)) <NEW_LINE> if next_letter != "quit": <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> word_list = self.trie_nodes.prefix_search(prev + next_letter) <NEW_LINE> if word_list... | Method for finding words with input prefix | 625941d24a966d76dd5511b5 |
def detectBorder(self): <NEW_LINE> <INDENT> lower_brown = np.array([0, 60, 0]) <NEW_LINE> upper_brown = np.array([255, 255, 255]) <NEW_LINE> mask = cv2.inRange(self.cv_img, lower_brown, upper_brown) <NEW_LINE> self.cv_cont = cv2.bitwise_and(self.cv_cont, self.cv_cont, mask=mask) <NEW_LINE> self.cv_cont = cv2.Canny(self... | Detecção de bordas | 625941d276e4537e8c351819 |
def get_imagenames(data): <NEW_LINE> <INDENT> return [img['src'] for img in bs.BeautifulSoup(data, 'lxml').find_all('img')] | analyze text for names of image files | 625941d2d7e4931a7ee9e0c4 |
def test_template_args(self): <NEW_LINE> <INDENT> self.registry.register(Charmeleon) <NEW_LINE> self.registry.register(Wartortle) <NEW_LINE> cache = ClassRegistryInstanceCache(self.registry, name='Bruce') <NEW_LINE> poke_1 = cache['fire'] <NEW_LINE> self.assertIsInstance(poke_1, Charmeleon) <NEW_LINE> self.assertEqual(... | Extra params passed to the cache constructor are passed to the
template function when creating new instances. | 625941d2796e427e537b076c |
def main_interactive(): <NEW_LINE> <INDENT> log.info('Running in interactive mode.') <NEW_LINE> (base, fname) = ui_get_input_file() <NEW_LINE> if (base is None): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> log.warn("Parsing project file: %s" % (base + fname)) <NEW_LINE> IJ.showStatus("Parsing experiment file...") <N... | The main routine for running interactively. | 625941d24e696a04525c95f1 |
def _init_env(): <NEW_LINE> <INDENT> curr_path = os.path.dirname( os.path.abspath(os.path.expanduser(__file__))) <NEW_LINE> proj_root = os.path.abspath(os.path.join(curr_path, "../../../")) <NEW_LINE> path_list = [ os.path.join(proj_root, "vta/config/vta_config.json") ] <NEW_LINE> path_list = [p for p in path_list if o... | Initialize the default global env | 625941d28da39b475bd6511a |
def update_item_info_step1(req, ln=CFG_SITE_LANG): <NEW_LINE> <INDENT> navtrail_previous_links = '<a class="navtrail"' ' href="%s/help/admin">Admin Area' '</a>' % (CFG_SITE_URL,) <NEW_LINE> id_user = getUid(req) <NEW_LINE> (auth_code, auth_message) = is_adminuse... | Update the item's information. | 625941d2462c4b4f79d1d876 |
def create_list_templates(self, mtype=None, page=None, pagesize=None, shortcode=None): <NEW_LINE> <INDENT> _query_builder = Configuration.base_uri <NEW_LINE> _query_builder += '/template/lists.json' <NEW_LINE> _query_url = APIHelper.clean_url(_query_builder) <NEW_LINE> _form_parameters = { 'type': mtype, 'page': page, ... | Does a POST request to /template/lists.json.
List Shortcode Templates by Type
Args:
mtype (string, optional): The type (category) of template Valid
values: marketing, authorization
page (int, optional): The page count to retrieve from the total
results in the collection. Page indexing starts a... | 625941d25166f23b2e1a52ff |
def testd(self): <NEW_LINE> <INDENT> d = pdb.pdbdata(4.0, 'double', self.fp) <NEW_LINE> dp = pdb.getdefstr(d) <NEW_LINE> self.assertEqual(type(dp), pdb.defstr) <NEW_LINE> self.assertEqual(dp.type, 'double') <NEW_LINE> size_bites = dp.size_bits <NEW_LINE> size = dp.size <NEW_LINE> alignment = dp.alignment <NEW_LINE> n_i... | defstr attributes | 625941d210dbd63aa1bd2d49 |
def psdChannelOutliner(*args, **kwargs): <NEW_LINE> <INDENT> pass | Dynamic library stub function | 625941d22c8b7c6e89b35966 |
def get_user_ordered_details(*args, **kwargs): <NEW_LINE> <INDENT> access_token = '' <NEW_LINE> http_authorization = args[0].META.get("HTTP_AUTHORIZATION") <NEW_LINE> if http_authorization is not None: <NEW_LINE> <INDENT> if len(http_authorization.split(" ")) == 2: <NEW_LINE> <INDENT> access_token = http_authorization.... | Note: replace below mock implementation with your actual implementation
Request:
kwargs["user"] -> request user
kwargs["user_dto"] -> request user_dto
kwargs["request_object"] -> request body type object
kwargs["request_data"] -> request body data dict
kwargs["request_hea... | 625941d207d97122c4178a33 |
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__ ) <NEW_LINE> parser.add_argument( "--setup", action="store_true", help='run "./env_setup.py" before running self checks', ) <NEW_LINE> parser.add_argument( "-q", "--quiet", action=... | Self check with cli args. | 625941d24a966d76dd5511b6 |
def get_course_path(self, semester, course_code): <NEW_LINE> <INDENT> search_path = '/semesters/%s/%s' % (semester.lower(), course_code.split('-')[0]) <NEW_LINE> return [course['path'] for course in self.get_result(search_path)['courses'] if course_code in course['aliases']][0] | Get a course's absolute path.
Args:
semester: The semester to search in the form '2011A' = Spring 2011
course_code: The target course in the form 'CIS-125' | 625941d2d10714528d5ffe8a |
def maxProfit(self, k, prices): <NEW_LINE> <INDENT> length = len(prices) <NEW_LINE> if length < 2: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> max_profit = 0 <NEW_LINE> if k>=length/2: <NEW_LINE> <INDENT> for i in range(1,length): <NEW_LINE> <INDENT> max_profit += max(prices[i]-prices[i-1],0) <NEW_LINE> <DEDENT> r... | :type k: int
:type prices: List[int]
:rtype: int | 625941d26fb2d068a760f244 |
def setup_method(self, testMethod): <NEW_LINE> <INDENT> self.model = None <NEW_LINE> if testMethod in (self.test_general, ): <NEW_LINE> <INDENT> class Model_FixedPointValue(IndexedRedisModel): <NEW_LINE> <INDENT> FIELDS = [ IRField('name'), IRFixedPointField('value', defaultValue=irNull), ] <NEW_LINE> INDEXED_FIELDS = ... | setup_method - Called before every method. Should set "self.model" to the model needed for the test.
@param testMethod - Instance method of test about to be called. | 625941d2dd821e528d63b34e |
def wait_falling(*ports): <NEW_LINE> <INDENT> if not ports: <NEW_LINE> <INDENT> raise TypeError("wait_falling() missing required argument: 'ports'") <NEW_LINE> <DEDENT> for p in ports: <NEW_LINE> <INDENT> if p._dtype is not typing.bit and p._dtype is not bool: <NEW_LINE> <INDENT> raise TypeError("'wait_falling' functio... | Wait until the signal of the specified port with bit dtype changes from 1 to 0.
*Parameters:*
ports : Port with bit dtype | 625941d23c8af77a43ae3947 |
def _get_valid_last_char(self, city_name): <NEW_LINE> <INDENT> for char in city_name[::-1]: <NEW_LINE> <INDENT> if char in self._city_list: <NEW_LINE> <INDENT> return char <NEW_LINE> <DEDENT> <DEDENT> raise KeyError | Проходит по city_name начиная с конца, выбирает символ так, чтобы в базе были слова начинающиеся на него | 625941d22ae34c7f2600d2d7 |
@patch('twitter_tunes.scripts.youtube_api.build') <NEW_LINE> def test_youtube_search_get_data(yt_search): <NEW_LINE> <INDENT> mock_method = yt_search().search().list().execute <NEW_LINE> mock_method.return_value = API_DATA.GOOD_YOUTUBE_RESPONSE <NEW_LINE> keyword = 'test search' <NEW_LINE> result = youtube_api.youtube_... | Test to see if we are getting result from search. | 625941d21b99ca400220ac57 |
@app.route("/student-add", methods=['POST']) <NEW_LINE> def student_add(): <NEW_LINE> <INDENT> first_name = request.form.get('first_name') <NEW_LINE> last_name = request.form.get('last_name') <NEW_LINE> github = request.form.get('github') <NEW_LINE> hackbright.make_new_student(first_name, last_name, github) <NEW_LINE> ... | Acknowledge student added. Link to student page. | 625941d2627d3e7fe0d68ff6 |
@app.route("/<search_term>/author/<filter_by>") <NEW_LINE> def filter_by_author(filter_by, search_term): <NEW_LINE> <INDENT> search_result = mongo.db.books.aggregate([ {"$match": {"$and": [ {"$text": {"$search": search_term} }, { "author": filter_by } ] } } ]) <NEW_LINE> results = [result for result in search_result] <... | Search Results for search term, filtered by a author | 625941d23cc13d1c6d3c7520 |
def _iptc_table_available(table, ipv6=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> iptc_table = Table6(table) if ipv6 else Table(table) <NEW_LINE> return True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False | Return True if the table is available, False otherwise | 625941d23d592f4c4ed1d212 |
def binaryOperation(self, subtree, mysymtab, inherited): <NEW_LINE> <INDENT> attrs = self.__purgeAttrs__(['tailcall'], inherited) <NEW_LINE> return (subtree[0], subtree[1], TreeOptimizer.visitor[subtree[2][0]]( self, subtree[2], mysymtab, attrs), TreeOptimizer.visitor[subtree[3][0]]( self, subtree[3], mysymtab, attrs)) | binaryOperation copies its subtree. Array concatenation passes
destination array type as an inherited attribute. | 625941d296565a6dacc8f871 |
def nan_win(win): <NEW_LINE> <INDENT> return np.any(np.isnan(win)) | Check if np.nan is either end of the window | 625941d28e05c05ec3eea51c |
def _parser_generator(self): <NEW_LINE> <INDENT> listener = self.listener <NEW_LINE> basic = self.basic <NEW_LINE> escape = self.escape <NEW_LINE> sharp = self.sharp <NEW_LINE> percent = self.percent <NEW_LINE> csi = self.csi <NEW_LINE> ESC = ctrl.ESC <NEW_LINE> CSI = ctrl.CSI <NEW_LINE> CTRL_SEQUENCES_ALLOWED_IN_CSI =... | Coroutine that processes VT100 output.
It's actually a state machine, implemented as a coroutine. So all the
'state' that we have is stored in local variables.
This generator is not the most beautiful, but it is as performant as
possible. When a process generates a lot of output (That is often much
more than a person... | 625941d273bcbd0ca4b2c21c |
def galprop_sourcekey(self, **kwargs): <NEW_LINE> <INDENT> kwargs_copy = self.base_dict.copy() <NEW_LINE> kwargs_copy.update(**kwargs) <NEW_LINE> self._replace_none(kwargs_copy) <NEW_LINE> try: <NEW_LINE> <INDENT> return NameFactory.galprop_sourcekey_format.format(**kwargs_copy) <NEW_LINE> <DEDENT> except KeyError: <NE... | return the sourcekey for merged galprop maps :
specifies the merged component and merging scheme | 625941d2d8ef3951e32436e4 |
def predict(self, X): <NEW_LINE> <INDENT> anomalies = self.decision_function(X) <NEW_LINE> ranking = np.sort(anomalies) <NEW_LINE> threshold = ranking[int((1 - self.contamination) * len(ranking))] <NEW_LINE> self.threshold = threshold <NEW_LINE> mask = (anomalies >= threshold) <NEW_LINE> ranking[mask] = -1 <NEW_LINE> r... | Return outliers with -1 and inliers with 1, with the outlierness score calculated from the `decision_function(X)`,
and the threshold `contamination`.
Parameters
----------
X : dataframe of shape (n_samples, n_features)
The input samples.
Returns
-------
ranking : numpy array of shape (n_samples,)
The outliernes... | 625941d22eb69b55b151ca57 |
def next_batch(num, labels, U): <NEW_LINE> <INDENT> idx = np.arange(0 , len(labels)) <NEW_LINE> np.random.shuffle(idx) <NEW_LINE> idx = idx[:num] <NEW_LINE> U_shuffle = [U[i] for i in idx] <NEW_LINE> label_shuffle = [labels[i] for i in idx] <NEW_LINE> return np.asarray(U_shuffle), np.asarray(label_shuffle) | Return a total of `num` random samples and labels. | 625941d226068e7796caee86 |
def candidate_answers(sentence, query, answer_type, max_ngram): <NEW_LINE> <INDENT> filtered_sentence = [word[0] for word in sentence if word[0] not in query and word[1] in answer_type] <NEW_LINE> return sum([ngrams(filtered_sentence, j) for j in range(1, max_ngram + 1)], []) | Return all the 1-, 2-, and 3-grams in `sentence`. Terms appearing
in `query` are filtered out. Note that the n-grams are returned
as a list of tuples. So a 1-gram is a tuple with 1 element, a
2-gram is a tuple with 2 elements, and so on. | 625941d2d268445f265b5014 |
def __init__(self): <NEW_LINE> <INDENT> self._includer = None | Sets up the parser | 625941d24428ac0f6e5ba999 |
def read_task_result(self, task_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.read_task_result_with_http_info(task_id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.read_task_result_with_http_info... | Get the response of a task # noqa: E501
Get the response of a task # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_task_result(task_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param ... | 625941d20383005118ecf788 |
def save_new_genome(genome, trace, check=False, target_species=None, rootdir='./'): <NEW_LINE> <INDENT> for crm in genome: <NEW_LINE> <INDENT> new_crm = genome[crm] <NEW_LINE> for exp in new_crm.experiments: <NEW_LINE> <INDENT> if check: <NEW_LINE> <INDENT> tadcnt = 0 <NEW_LINE> new_tads = {} <NEW_LINE> for tad in exp.... | Save new chromosomes with remapped or check TAD borders into a new folder.
:para genome: a dict containing all chromosomes computed
:param trace: dictionary containing a trace of all mapped TAD boundaries
:param False check: if no remapping have to be done (only check TAD borders)
:param None target_species: name of t... | 625941d20fa83653e4657161 |
def network_exists(network: str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> get_client().networks.get(network) <NEW_LINE> return True <NEW_LINE> <DEDENT> except NotFound: <NEW_LINE> <INDENT> return False | Return True if a network exists in docker, else False. | 625941d2bde94217f3682f96 |
def __init__(self, atomistic_traj, mapping, weights): <NEW_LINE> <INDENT> super(base.ProtoReader, self).__init__() <NEW_LINE> self._t = atomistic_traj <NEW_LINE> self._mapping = mapping <NEW_LINE> self._weights = weights <NEW_LINE> self.n_atoms = mapping.max() + 1 <NEW_LINE> self.ts = base.Timestep(self.n_atoms) <NEW_L... | Parameters
----------
atomistic_traj : mda.Reader
atomistic trajectory
mapping : numpy array
which bead
weights : numpy array
for each atom, what weight | 625941d2dd821e528d63b34f |
def get_learned_routes( self, resource_group_name, virtual_network_gateway_name, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> raw_result = self._get_learned_routes_initial( resource_group_name=resource_group_name, virtual_network_gateway_name=virtual_network_gateway_name, custom_headers=cust... | This operation retrieves a list of routes the virtual network gateway
has learned, including routes learned from BGP peers.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param virtual_network_gateway_name: The name of the virtual network
gateway.
:type virtual_network_gat... | 625941d215fb5d323cde0cb7 |
def list_event_subscriptions(self): <NEW_LINE> <INDENT> response = self._do_request('GET', '/v2/eventSubscriptions') <NEW_LINE> return [url for url in response.json()['callbackUrls']] | List the event subscriber callback URLs.
:returns: list of callback URLs
:rtype: list[str] | 625941d2be383301e01b562a |
def resource_required(key, flattened_data, errors, context): <NEW_LINE> <INDENT> data_dict = unflatten(flattened_data) <NEW_LINE> if not data_dict.get("id"): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> pkg_obj = toolkit.get_action("package_show")(data_dict={"id": data_dict['id']}) <NEW_LINE>... | check resources. If empty, raise error | 625941d2d164cc6175782ef4 |
def test_class_2_filter(self): <NEW_LINE> <INDENT> self.class_filter(2, 2) | Test to filter classes | 625941d266673b3332b92238 |
def newTopicFrame(self, topic): <NEW_LINE> <INDENT> frame = Frame(self.root) <NEW_LINE> removeFrame = Frame(frame, width=self.defaultWidth, height=30, relief=SOLID, borderwidth=2) <NEW_LINE> removeLabel = Label(removeFrame, text="Drag note here to remove from topic") <NEW_LINE> removeLabel.pack() <NEW_LINE> removeFrame... | Create a new dndlist for the given topic and populate it with the
topic's notes (if any). | 625941d2656771135c3eba16 |
@app.route('/home') <NEW_LINE> def home(): <NEW_LINE> <INDENT> if 'username' not in session: <NEW_LINE> <INDENT> return redirect(url_for('index')) <NEW_LINE> <DEDENT> username = session['username'] <NEW_LINE> money = db.getUserBigcoin(username) <NEW_LINE> return render_template('landing.html', username = session['usern... | LANDING PAGE WHERE PROJECTS ARE LISTED | 625941d2851cf427c661a6b4 |
def _GenerateDockerignore(self, cleaner): <NEW_LINE> <INDENT> dockerignore = os.path.join(self.root, '.dockerignore') <NEW_LINE> if not os.path.exists(dockerignore): <NEW_LINE> <INDENT> self.notify('Writing [.dockerignore] to [{0}].'.format(self.root)) <NEW_LINE> with open(dockerignore, 'w') as f: <NEW_LINE> <INDENT> f... | Generates a .dockerignore file appropriate to this application.
Args:
cleaner: (fingerprinting.Cleaner) A cleaner to populate | 625941d2566aa707497f470e |
def getRawName(path): <NEW_LINE> <INDENT> loc = path.rfind(".") <NEW_LINE> if loc == -1: <NEW_LINE> <INDENT> return loc <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return path[0:loc] | Given a filename with no path before it, returns just the name, no type
:returns filename | 625941d2bde94217f3682f97 |
def _parse_args(self): <NEW_LINE> <INDENT> fix_opts_names = re.compile(r'[^A-Za-z0-9\-]').sub <NEW_LINE> self.supervised_opts = {fix_opts_names('-', k).lower(): v for k, v in self.supervised_opts.iteritems()} <NEW_LINE> method_parser = ArgumentParser() <NEW_LINE> types_map = {} <NEW_LINE> for opt, values in self.superv... | Parse the Reranker-specific parameters (as specified by
supervised_opts) and add them to self.opts. Note: if an
option is already specified in self.opts, it is NOT
overwritten by this method.
Notes
----------
This method is NOT meant to be overwritten. | 625941d232920d7e50b28377 |
def __init__(self, lot_id, city): <NEW_LINE> <INDENT> super(Tract, self).__init__(lot_id, city) | Initialize a Lot object. | 625941d2eab8aa0e5d26dcff |
def overlap_check(center1, center2, rad1, rad2): <NEW_LINE> <INDENT> d_overlap = rad1 + rad2 <NEW_LINE> d = distance(center1, center2) <NEW_LINE> if d == 0: <NEW_LINE> <INDENT> res = 'zero' <NEW_LINE> <DEDENT> elif d <= d_overlap: <NEW_LINE> <INDENT> res = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res = False ... | Check if two circles overlap.
Return 'zero' if they have the same center. | 625941d263f4b57ef00012bd |
def is_rgb_like(image): <NEW_LINE> <INDENT> return (image.ndim == 3) and (image.shape[2] in (3, 4)) | Return True if the image *looks* like it's RGB.
This function should not be public because it is only intended to be used
for functions that don't accept volumes as input, since checking an image's
shape is fragile. | 625941d27047854f462a15af |
def test_prediction_get_result_not_complete( patched_fero_client, prediction_results_response_started ): <NEW_LINE> <INDENT> patched_fero_client.get.return_value = prediction_results_response_started <NEW_LINE> pred = Prediction(patched_fero_client, "c9448486-0c59-487f-9c9c-345d98103fcb") <NEW_LINE> with pytest.raises(... | Test that a Fero Error is raised if get_result is called before a prediction is complete | 625941d2e8904600ed9f20d5 |
def update_exchange_instance_api_keys(self): <NEW_LINE> <INDENT> exchanges_with_keys = [] <NEW_LINE> for exchange in self._API_KEYS.keys(): <NEW_LINE> <INDENT> self.trader[exchange].update_api_keys( self._API_KEYS[exchange].get('APIKey', ''), self._API_KEYS[exchange].get('Secret', ''), self._API_KEYS[exchange].get('API... | Uses current values in self._API_KEYS to update API Keys of exchange instances | 625941d21f037a2d8b9463a4 |
def match(self): <NEW_LINE> <INDENT> transform = MatchTransform() <NEW_LINE> constraints = [ Constraint(c.elem, c.pos, *transform(c.axis, c.value, tw)) for c in self.constraints for tw in [self._get_tw_row(c.elem, c.pos)] ] <NEW_LINE> blacklist = [v.lower() for v in self.model.data.get('readonly', ())] <NEW_LINE> varia... | Match the :attr:`variables` to satisfy :attr:`constraints`. | 625941d23eb6a72ae02ec686 |
def test_bst_root_child_none(bst): <NEW_LINE> <INDENT> bst.insert(8) <NEW_LINE> assert bst.root.left is None <NEW_LINE> assert bst.root.right is None | Test that a root node is created with children set to None. | 625941d28c3a873295158562 |
def item_link(self, item): <NEW_LINE> <INDENT> if item.external_link: <NEW_LINE> <INDENT> return item.external_link <NEW_LINE> <DEDENT> return item.get_absolute_url() | Figure out where the link should go
might goto an external source | 625941d2b57a9660fec33a2b |
def stop(self): <NEW_LINE> <INDENT> self._closing = True <NEW_LINE> self.close_channel() <NEW_LINE> self.close_connection() | Cleanly shutdown the connection to RabbitMQ by stopping the consumer
with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok
will be invoked by pika, which will then closing the channel and
connection. The IOLoop is started again because this method is invoked
when CTRL-C is pressed raising a KeyboardInterr... | 625941d2a934411ee375183a |
def packNeck(meta, head, neck): <NEW_LINE> <INDENT> neck['pack'] = '' <NEW_LINE> if meta.get('nk') == neckKinds.nada: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> meta['nl'] = len(neck['pack']) | Signs the head and puts auth signature into neck | 625941d24e696a04525c95f2 |
def antonym(self): <NEW_LINE> <INDENT> p = self._synset.getPointers(wn.ANTONYM) <NEW_LINE> return len(p) > 0 and Synset(p[0].getTarget()) or None | The semantically opposite synset, for example:
synsets("death")[0].antonym => Synset("birth"). | 625941d276d4e153a657ecd8 |
def testaooverlaps(self): <NEW_LINE> <INDENT> if not hasattr(self.data, "aooverlaps") and hasattr(self.data, "fooverlaps"): <NEW_LINE> <INDENT> self.data.aooverlaps = self.data.fooverlaps <NEW_LINE> <DEDENT> self.assertEquals(sum(self.data.aooverlaps[0,:] - self.data.aooverlaps[:,0]), 0) | Are the first row and colm of the overlap matrix identical? | 625941d24f6381625f114be1 |
def finished_loop(surface, gamestat, msg): <NEW_LINE> <INDENT> grayscale_image(surface) <NEW_LINE> pygame.display.update() <NEW_LINE> finished = TITLE_FONT.render(msg, 1, (255, 0, 0)) <NEW_LINE> surface.blit(finished, (surface.get_width() / 2 - finished.get_width() / 2, surface.get_height() / 2 + finished... | shows finished screen | 625941d223849d37ff7b3236 |
def evaluate(self, version): <NEW_LINE> <INDENT> self.predictor.load_model(version) <NEW_LINE> self._load_eval_set(f"{DATA_DIR}/validation.pkl") <NEW_LINE> self.eval_df['COUNTRY.OF.ORIGIN'].fillna('OTHER', inplace=True) <NEW_LINE> seen_countries = set(self.predictor.label_encoder.classes_) <NEW_LINE> self.eval_df['COUN... | - Load validation data frame
- Maps previously unseed countries to OTHER
- Preprocesses data frame for additional features
- Run prediction
- Calculate confusion matrix and classification report with precision/recall/f-score
for each country
- Save metrics to separate file in model directory for future reference (cou... | 625941d2be383301e01b562b |
def length(self): <NEW_LINE> <INDENT> return hypot(self.point1.x_cord - self.point2.x_cord, self.point1.y_cord - self.point2.y_cord) | Calculate length of the line. | 625941d282261d6c526ab647 |
def _connarg(name, key=None): <NEW_LINE> <INDENT> if key is None: <NEW_LINE> <INDENT> key = name <NEW_LINE> <DEDENT> if name in kwargs: <NEW_LINE> <INDENT> connargs[key] = kwargs[name] <NEW_LINE> <DEDENT> elif 'mysql.%s' % name in __opts__: <NEW_LINE> <INDENT> connargs[key] = __opts__['mysql.%s' % name] | Add key to connargs, only if name exists in our
kwargs or as mysql.<name> in __opts__ | 625941d271ff763f4b549834 |
def create(self, datapath, tracker_urls, comment=None, root_name=None, created_by=None, private=False, no_date=False, progress=None, callback=None): <NEW_LINE> <INDENT> if datapath: <NEW_LINE> <INDENT> self.datapath = datapath <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> tracker_urls = ['' + tracker_urls] <NEW_LINE> <D... | Create a metafile with the path given on object creation.
Returns the last metafile dict that was written (as an object, not bencoded). | 625941d28c0ade5d55d3eb62 |
def disable_charge(self): <NEW_LINE> <INDENT> if not self._can_charge: <NEW_LINE> <INDENT> raise LpdmBatteryNotDischarging() <NEW_LINE> <DEDENT> elif self._power_level != 0: <NEW_LINE> <INDENT> raise Exception("Can't disable charge while there is a load on the device.") <NEW_LINE> <DEDENT> self._logger.debug( self.buil... | Stop discharging:
set the capacity in the power source manager to 0 to mark it as unavailable | 625941d2dc8b845886cb56dc |
@task <NEW_LINE> def install(): <NEW_LINE> <INDENT> with lcd(env.vars['project']['dir']): <NEW_LINE> <INDENT> local('pip install -r requirements/python{}.txt'.format( sys.version_info[0])) | Install packages for testing | 625941d2d268445f265b5015 |
def show(self): <NEW_LINE> <INDENT> print(fmt.green + "") | This function ...
:return: | 625941d2435de62698dfddf4 |
def test_read_but_dont_write_cosmetic_parameter_attribute(self): <NEW_LINE> <INDENT> p1 = BondHandler.BondType( smirks="[*:1]-[*:2]", length=1.02 * unit.angstrom, k=5 * unit.kilocalorie_per_mole / unit.angstrom**2, pilot="alice", allow_cosmetic_attributes=True, ) <NEW_LINE> param_dict = p1.to_dict(discard_cosmetic_attr... | Test ParameterTypes' ability to ignore cosmetic attributes passed to __init__() if instructed | 625941d23617ad0b5ed6809e |
def check_valid_url(self, path): <NEW_LINE> <INDENT> request = urllib2.Request(path) <NEW_LINE> request.get_method = lambda: 'HEAD' <NEW_LINE> try: <NEW_LINE> <INDENT> response = urllib2.urlopen(request) <NEW_LINE> return True <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(... | This function checks to see if the path given is a url or a file path.
Returns True if it is a url and False if it is a file path. Throws an
exception if it is neither or if the paths are incorrect. | 625941d2293b9510aa2c343c |
def get_astros(self, url=url): <NEW_LINE> <INDENT> astro_dict = self._get(url=url) <NEW_LINE> for astro in astro_dict['people']: <NEW_LINE> <INDENT> name = astro['name'].replace('kiy', 'ky').replace(' ', '_').lower() <NEW_LINE> self.astros.append(name) <NEW_LINE> <DEDENT> return self.astros | Return a list of active astronauts. | 625941d2442bda511e8be5be |
def roi_proposals(self, fmap, im_sizes, nms_thresh=0.7, pre_nms_topn=12000, post_nms_topn=2000): <NEW_LINE> <INDENT> class_fmap = fmap[:, :, :, :, :2].contiguous() <NEW_LINE> class_preds = F.softmax(class_fmap, 4)[..., 1].data.contiguous() <NEW_LINE> box_fmap = fmap[:, :, :, :, 2:].data.contiguous() <NEW_LINE> anchor_s... | :param fmap: [batch_size, IM_SIZE/16, IM_SIZE/16, A, 6]
:param im_sizes: [batch_size, 3] numpy array of (h, w, scale)
:return: ROIS: shape [a <=post_nms_topn, 5] array of ROIS. | 625941d25e10d32532c5f0ce |
def convert_dict2list(gpadict): <NEW_LINE> <INDENT> result = [] <NEW_LINE> keys = gpadict.keys() <NEW_LINE> values = gpadict.values() <NEW_LINE> tup = tuple(map(lambda num1, num2: (num1, num2), keys, values)) <NEW_LINE> result.append(tup) <NEW_LINE> return result | Input: a dictionary mapping student names to their gpa
Output: gpalist - list of (student name, gpa) tuples | 625941d25fdd1c0f98dc03db |
def read_data_w_err_ascii(filename, datacol=(1,), errcol=(2,), verbose=False): <NEW_LINE> <INDENT> cols = datacol + errcol <NEW_LINE> if not isinstance(cols, (list, tuple)): <NEW_LINE> <INDENT> print("column must be list or tuple and not %s" % type(column)) <NEW_LINE> os.sys.exit(-1) <NEW_LINE> <DEDENT> _data = read_da... | Reads in data with error from a source file.
The file is assumed to have L. Liu's data format so that the first line
has information about the number of samples and the length of each sample.
This info is used to shape the data into the correct array format.
Args:
filename: The filename of the file.
column: W... | 625941d2097d151d1a223000 |
def post_site(self, body, cluster_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.post_site_with_http_info(body, cluster_id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.post_site_with_http_info(bo... | Create a new site # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.post_site(body, cluster_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param SiteJson body: The configuration of the new site... | 625941d2377c676e91272350 |
def __init__(self): <NEW_LINE> <INDENT> self.heap = [] <NEW_LINE> self.stack = [] | initialize your data structure here. | 625941d2925a0f43d254a01f |
def utf8toStr ( data, ignoreDicts=False ): <NEW_LINE> <INDENT> if isinstance(data,unicode): <NEW_LINE> <INDENT> return data.encode('utf-8') <NEW_LINE> <DEDENT> if isinstance(data,list): <NEW_LINE> <INDENT> return [ utf8toStr( item, ignoreDicts=True ) for item in data ] <NEW_LINE> <DEDENT> if isinstance(data,dict) and n... | Translate UTF-8 strings into basic str ones in dict & list datas.
Based on _byteify() by Mirec Miskuf on Stackoverflow.
reference: https://stackoverflow.com/questions/956867/
how-to-get-string-objects-instead-of-unicode-from-json/
33571117#33571117 | 625941d2ac7a0e7691ed4271 |
def load_config(config_file): <NEW_LINE> <INDENT> if Path(config_file).is_file(): <NEW_LINE> <INDENT> return json.loads(open(config_file).read()) <NEW_LINE> <DEDENT> print('missing {} file.'.format(config_file)) <NEW_LINE> sys.exit(1) | Load *.json config file | 625941d29b70327d1c4e0f7d |
def test_create_predefined_answer(self): <NEW_LINE> <INDENT> pass | Test case for create_predefined_answer
Create predefined answer # noqa: E501 | 625941d2498bea3a759b9c56 |
def remove_nans(dict, cutoff): <NEW_LINE> <INDENT> new_dict = {} <NEW_LINE> for key, values in results_dict.items (): <NEW_LINE> <INDENT> i, j = values <NEW_LINE> if not isnan (i) and i > cutoff: <NEW_LINE> <INDENT> new_dict [ key ] = values <NEW_LINE> <DEDENT> <DEDENT> return new_dict | Remove nans from the output | 625941d2bf627c535bc13376 |
def test_get_config_invalid(): <NEW_LINE> <INDENT> config_file = data_path + os.sep + 'invalid.cfg' <NEW_LINE> with pytest.raises(EC2ConfigFileParseException): <NEW_LINE> <INDENT> ec2utils.get_config(config_file) | Test get_config with an invalid configuration file | 625941d24c3428357757c4cf |
def do_db_sync(): <NEW_LINE> <INDENT> db_api.db_sync(db_api.get_engine(), CONF.command.version) | Place a database under migration control and upgrade,
creating first if necessary. | 625941d2293b9510aa2c343d |
def grade(conn, quiz_id): <NEW_LINE> <INDENT> quiz = get_quiz(conn, quiz_id) <NEW_LINE> submissions = get_submissions(conn, quiz_id) <NEW_LINE> for submission in submissions: <NEW_LINE> <INDENT> grade_submission(conn, quiz, submission) | Grades quiz
| 625941d25fc7496912cc3b25 |
def get_pos(self, char_offset): <NEW_LINE> <INDENT> assert (char_offset >= self._last_line_offset) <NEW_LINE> return TokenPos(self._unit_name, self._last_line_offset + 1, char_offset - self._last_line_offset + 1) | Calculate a TokenPos for a given character offset within the unit.
Note that we only support looking up the positions of tokens that
occur AFTER the last newline we've tracked.
:param char_offset: the character offset (within the unit) of a token
:type char_offset: int
:return: A TokenPos that indicates the position... | 625941d2c4546d3d9de72bdc |
def cal_num_flct_3(num, box_len, box_num, num_mean, num_var): <NEW_LINE> <INDENT> return _num_flct.cal_num_flct_3(num, box_len, box_num, num_mean, num_var) | cal_num_flct_3(unsigned short * num, int * box_len, int * box_num, double * num_mean, double * num_var) | 625941d2a934411ee375183b |
def _get_shutdown_threshold_pct(self): <NEW_LINE> <INDENT> return self.__shutdown_threshold_pct | Getter method for shutdown_threshold_pct, mapped from YANG variable /bgp/neighbors/neighbor/afi_safis/afi_safi/ipv6_labeled_unicast/prefix_limit/config/shutdown_threshold_pct (oc-types:percentage)
YANG Description: Threshold on number of prefixes that can be received
from a neighbour before generation of warni... | 625941d244b2445a3393223d |
def test_notice_date_of_birth(self): <NEW_LINE> <INDENT> self.assertEqual(str(self.notice.date_of_birth), '1989-01-01') | Test the to test date of birth representation | 625941d24527f215b584c5fd |
def generate_hash(self): <NEW_LINE> <INDENT> block_header = str(self.time_stamp) + str(self.data) + str(self.previous_hash) + str(self.nonce) + str( self.index) <NEW_LINE> block_hash = sha256(block_header.encode()) <NEW_LINE> return block_hash.hexdigest() | Generates the Hash of the current block in the chain.
:return: Hash generated of the current block. | 625941d2d18da76e2353267e |
def find_closing_tag(tag, max_tags=sys.maxsize): <NEW_LINE> <INDENT> if tag.self_closing: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> stack = [] <NEW_LINE> block, offset = tag.end_block, tag.end_offset <NEW_LINE> while block.isValid() and max_tags > 0: <NEW_LINE> <INDENT> block, tag_start = next_tag_boundary(bl... | Find the closing tag corresponding to the specified tag. To find it we
search for the first closing tag after the specified tag that does not
match a previous opening tag. Search through at most max_tags. | 625941d29c8ee82313fbb91d |
def stopTest(self, test): <NEW_LINE> <INDENT> old_sigalrm_handler = getattr(test, 'old_sigalrm_handler', None) <NEW_LINE> if old_sigalrm_handler is not None: <NEW_LINE> <INDENT> signal.signal(signal.SIGALRM, old_sigalrm_handler) <NEW_LINE> signal.alarm(0) | Stop the test | 625941d2d4950a0f3b08c4f6 |
def get_offset_name(offset): <NEW_LINE> <INDENT> name = _offset_names.get(offset) <NEW_LINE> if name is not None: <NEW_LINE> <INDENT> return name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('Bad rule given: %s!' % offset) | Return rule name associated with a DateOffset object
Example
-------
get_offset_name(BMonthEnd(1)) --> 'EOM' | 625941d27c178a314d6ef608 |
@address.command(name="add") <NEW_LINE> @click.argument("address_name") <NEW_LINE> @click.option("--active/--inactive", default=True) <NEW_LINE> @click.option("--transport", "-t", default=None) <NEW_LINE> @click.option("--rclass", "-r", default="30", type=click.Choice(RCLASSES)) <NEW_LINE> @click.pass_context <NEW_LINE... | Add an address. | 625941d2287bf620b61d3c0a |
def fn_timer(fn): <NEW_LINE> <INDENT> @wraps(fn) <NEW_LINE> def function_timer(*args, **kwargs): <NEW_LINE> <INDENT> start = time.time() <NEW_LINE> result = fn(*args, **kwargs) <NEW_LINE> end = time.time() <NEW_LINE> logger.info(fn.__name__ + ' total running time %s seconds' % str(end - start)) <NEW_LINE> return result... | 计算 fn 的运算时间
:param fn:
:return: | 625941d25f7d997b87174c40 |
def test_cooperative_gradients(self): <NEW_LINE> <INDENT> pass | Check the functionality of the cooperative-gradients feature. | 625941d2d7e4931a7ee9e0c6 |
def __get_samples_with_pop(self, samples): <NEW_LINE> <INDENT> samples_with_pop = [] <NEW_LINE> pop_names = [pop['name'] for pop in self.pops] <NEW_LINE> for named_sample in samples: <NEW_LINE> <INDENT> assert '_' in named_sample, 'The sample naming scheme is incorrect.' <NEW_LINE> s = named_sample.split('_') <NEW_LINE... | Generates a list of tuples where the first tuple element is an integer corresponding to a pop object,
and the second tuple element is a string corresponding to the name of a sample in that pop object.
(i.e. not including the experiment name). This is just a way to associate samples with a specific
pop object to clean... | 625941d2796e427e537b076e |
def List_video(self): <NEW_LINE> <INDENT> for i in range(len(self.video)): <NEW_LINE> <INDENT> print('录像带ID:%s | 录像带名称:%s | 录像带数量:%s | 录像带价格:%s' % ( self.video[i].ind, self.video[i].name, self.video[i].number, self.video[i].price)) | "
录像带列表 | 625941d27c178a314d6ef609 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.