code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def get_lfw_paths(end = None, change = True): <NEW_LINE> <INDENT> path = "../dataset/lfw/lfw" <NEW_LINE> s_names = os.listdir(path) <NEW_LINE> filenames = [] <NEW_LINE> labels = [] <NEW_LINE> for s_index, s_name in enumerate(s_names): <NEW_LINE> <INDENT> if end is not None and s_index == end: <NEW_LINE> <INDENT> break ... | 读取lfw数据,jpg格式
:return:[类index, 路径] | 625941ea3cc13d1c6d3c784b |
def predict(self, data, useCPUOnly=False, **kwargs): <NEW_LINE> <INDENT> if self.__proxy__: <NEW_LINE> <INDENT> return self.__proxy__.predict(data,useCPUOnly) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if _sys.platform != 'darwin' or float('.'.join(_platform.mac_ver()[0].split('.')[:2])) < 10.13: <NEW_LINE> <INDENT>... | Return predictions for the model. The kwargs gets passed into the
model as a dictionary.
Parameters
----------
data : dict[str, value]
Dictionary of data to make predictions from where the keys are
the names of the input features.
useCPUOnly : bool
Set to true to restrict computation to use only the CPU. ... | 625941ea3cc13d1c6d3c784c |
def _call(self, base_url, url, body): <NEW_LINE> <INDENT> url = urljoin(base_url.geturl(), url) <NEW_LINE> return _urlopen(url, data=self._encode_params(body)) | Open a network connection and performs HTTP Post
with provided body. | 625941ea462c4b4f79d1dba3 |
def EndEdit(self, row, col, grid, oldVal): <NEW_LINE> <INDENT> self._tc.unbind_handlers() <NEW_LINE> val = self._tc.GetValue() <NEW_LINE> self._tc.SetScrollCallback(None) <NEW_LINE> if val != oldVal: <NEW_LINE> <INDENT> return val <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | End editing the cell. This function must check if the current
value of the editing control is valid and different from the
original value (available as oldval in its string form.) If
it has not changed then simply return None, otherwise return
the value in its string form. | 625941ea9c8ee82313fbbc4b |
def choose_action(self, state): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> self.next_waypoint = self.planner.next_waypoint() <NEW_LINE> self.q_value = self.get_maxQ(state) <NEW_LINE> if self.learning: <NEW_LINE> <INDENT> if random.uniform(self.level_of_tolerance, 1.0) < self.epsilon: <NEW_LINE> <INDENT> action =... | The choose_action function is called when the agent is asked to choose
which action to take, based on the 'state' the smartcab is in. | 625941ea3539df3088e2e81f |
def parseTrialString(string): <NEW_LINE> <INDENT> rangeStrs = string.split(TRIAL_STRING_DELIMITER) <NEW_LINE> res = set() <NEW_LINE> for rangeStr in rangeStrs: <NEW_LINE> <INDENT> r = [int(x) for x in rangeStr.strip().split('-')] <NEW_LINE> if len(r) == 2: <NEW_LINE> <INDENT> r = list(range(r[0], r[1] + 1)) <NEW_LINE> ... | Converts a comma-separated list of ranges into a list of numbers.
Ex. 1,3,4-6,2 becomes [1,3,4,5,6,2]. Duplicates are deleted. | 625941eaff9c53063f47c6c5 |
def loan_line_vals(self, form, context=None): <NEW_LINE> <INDENT> context = {} if context is None else context <NEW_LINE> user = context.get("user", request.env.user) <NEW_LINE> vals = { "creation_mode": "manual", "state": "paid", "loan_issue_id": int(form.cleaned_data["loan_issue"]), "quantity": form.cleaned_data["qua... | Return vals to create a loan issue line object | 625941ea24f1403a92601036 |
def run(self): <NEW_LINE> <INDENT> self.checkReady() <NEW_LINE> with server(get_ro_server(), no_replace=True): <NEW_LINE> <INDENT> with BranchMergeProposalDelta.monitor(self.branch_merge_proposal): <NEW_LINE> <INDENT> PreviewDiff.fromBranchMergeProposal(self.branch_merge_proposal) | See `IRunnableJob`. | 625941ea046cf37aa974d216 |
def addMenu(self): <NEW_LINE> <INDENT> a = self.parent.action() <NEW_LINE> menuFile = slicer.util.lookupTopLevelWidget('menuFile') <NEW_LINE> if menuFile: <NEW_LINE> <INDENT> for action in menuFile.actions(): <NEW_LINE> <INDENT> if action.text == 'Save': <NEW_LINE> <INDENT> menuFile.insertAction(action,a) | Add an action to the File menu that will go into
the DICOM module by selecting the module. Note that
once the module is constructed (below in setup) another
connection is made that will also cause the instance-created
DICOM browser to be raised by this menu action | 625941eae76e3b2f99f3acd8 |
def setup_paths(self, project_folder, project_name): <NEW_LINE> <INDENT> if not isinstance(project_name, string_types): <NEW_LINE> <INDENT> raise ConfigError("project_name value must be a string") <NEW_LINE> <DEDENT> if not isinstance(project_folder, string_types): <NEW_LINE> <INDENT> raise ConfigError("project_folder ... | Fills the project_name, project_name and its
dependent keys after evaluation.
.. version changed :: 6.0.0
Added string type checks and os based path normalising.
.. version changed :: 6.1.0
FIX: fixed path issue when using relative path for project_folder
.. version changed :: 6.3.0
FIX: Removed file bas... | 625941ea60cbc95b062c6a18 |
def ajouter_symbole_sur_carte(symb,a): <NEW_LINE> <INDENT> place = random.randint(0,len(a)) <NEW_LINE> while a[place] != " ": <NEW_LINE> <INDENT> place = random.randint(0,len(a)) <NEW_LINE> <DEDENT> a = a[0:place] + symb + a[place+1:] <NEW_LINE> return a | Ajoute le symbole du joueur sur la carte | 625941ea26068e7796caf1bb |
def invalidate_caches(self): <NEW_LINE> <INDENT> self.cached_tracks = None <NEW_LINE> self.cached_playlists = None <NEW_LINE> self.cached_stations = None <NEW_LINE> self.caches_invalidated.fire() | Clear cached tracks & playlists & stations. | 625941ea1d351010ab855fef |
def _retrieve_location_from_ssdp(response): <NEW_LINE> <INDENT> parsed_headers = re.findall(r'(?P<name>.*?): (?P<value>.*?)\r\n', response) <NEW_LINE> header_locations = [header[1] for header in parsed_headers if header[0].lower() == 'location'] <NEW_LINE> if len(header_locations) < 1: <NEW_LINE> <INDENT> raise IGDErro... | Parse raw HTTP response to retrieve the UPnP location header
and return a ParseResult object. | 625941ea377c676e9127267b |
def make_session_select(self): <NEW_LINE> <INDENT> self.session_text = tk.Message(self) <NEW_LINE> self.session_text["text"] = "Session Number" <NEW_LINE> self.session_text["width"] = 100 <NEW_LINE> self.session_text.place(x=50+self.controller.x_offset,y=self.session_y+5) <NEW_LINE> self.session_select = tk.OptionMenu(... | Initialize widgets for session dropdown selection | 625941ea046cf37aa974d217 |
def py_error_handler(filename, line, function, err, fmt): <NEW_LINE> <INDENT> pass | Gestion des erreurs | 625941ea76d4e153a657f007 |
def __iter__(self): <NEW_LINE> <INDENT> return (self._text[line] for line in self._order) | Iterate over the text in the text body. | 625941eab7558d58953c53de |
def __fetch_check_members__(self, members): <NEW_LINE> <INDENT> _members = [] <NEW_LINE> for m in members: <NEW_LINE> <INDENT> if m.name == ".": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if ".." in m.name: <NEW_LINE> <INDENT> iocage_lib.ioc_common.logit( { "level": "WARNING", "message": f"{m.name} is not a relat... | Checks if the members are relative, if not, log a warning. | 625941ea6fb2d068a760f579 |
def create_train_test(X, y): <NEW_LINE> <INDENT> X_train, X_test, y_train, y_test = train_test_split(X, y, shuffle=True, stratify=y, random_state=13, test_size=0.2) <NEW_LINE> return X_train, X_test, y_train, y_test | Splits X and y (dataframe with sentences and Series with labels respectively) into training and test sets. | 625941ea6fece00bbac2dc19 |
def open_time(control_dist_km, brevet_dist_km, brevet_start_time): <NEW_LINE> <INDENT> if control_dist_km > brevet_dist_km: <NEW_LINE> <INDENT> control_dist_km = brevet_dist_km <NEW_LINE> <DEDENT> max_speed = acp_brevets['{}'.format(brevet_dist_km)][1] <NEW_LINE> open_t = control_dist_km / max_speed <NEW_LINE> mn = rou... | Args:
control_dist_km: number, the control distance in kilometers
brevet_dist_km: number, the nominal distance of the brevet
in kilometers, which must be one of 200, 300, 400, 600,
or 1000 (the only official ACP brevet distances)
brevet_start_time: An ISO 8601 format date-time string indicating... | 625941eafb3f5b602dac3b6c |
def version(): <NEW_LINE> <INDENT> return SAGE_VERSION_BANNER | Return the version of Sage.
OUTPUT:
str
EXAMPLES::
sage: version()
'SageMath version ..., Release Date: ...' | 625941eae64d504609d74d14 |
def add_to_inventory(inventory, added_items): <NEW_LINE> <INDENT> for i in added_items: <NEW_LINE> <INDENT> if i in inventory: <NEW_LINE> <INDENT> inventory[i] += 1 <NEW_LINE> <DEDENT> elif i not in inventory: <NEW_LINE> <INDENT> inventory[i] = 1 <NEW_LINE> <DEDENT> <DEDENT> return inventory | Add to the inventory dictionary a list of items from added_items. | 625941ea5fdd1c0f98dc0709 |
def dispatch(self): <NEW_LINE> <INDENT> self.get_query_sm() | Main method to add metadata and get df from database. | 625941ea4e696a04525c9922 |
def lucas(n): <NEW_LINE> <INDENT> if (n==0 or n == 1): <NEW_LINE> <INDENT> return abs(n-2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return lucas(n-1) + lucas(n-2) | The Lucas Numbers are a related series of integers that start with the values 2 and 1 rather than 0 and 1.
The resulting series looks like this:2, 1, 3, 4, 7, 11, 18, 29, ... similiar to f(n)=f(n-1)+f(n-2)
The function lucas returns the nth value in the lucas numbers series (starting with zero index). | 625941ead4950a0f3b08c81c |
def _on_review_published(self, user, review, **kwargs): <NEW_LINE> <INDENT> open_issues = 0 <NEW_LINE> first_comment = None <NEW_LINE> for comment in review.get_all_comments(): <NEW_LINE> <INDENT> if not first_comment: <NEW_LINE> <INDENT> first_comment = comment <NEW_LINE> <DEDENT> if (comment.issue_opened and comment.... | Handler for when a review is published.
This will send a notification to any configured channels when
a review is published.
Args:
user (django.contrib.auth.models.User):
The user who published the review.
review (reviewboard.reviews.models.Review):
The review that was published.
**kwarg... | 625941ea167d2b6e31219069 |
def isMatch(self, s, p): <NEW_LINE> <INDENT> s = "0" + s <NEW_LINE> p = "0" + p <NEW_LINE> print(s,p) <NEW_LINE> nrow,ncol = len(s), len(p) <NEW_LINE> T = [['']*(ncol) for i in range(nrow)] <NEW_LINE> T[0][0] = True <NEW_LINE> for i in range(1,nrow): <NEW_LINE> <INDENT> T[i][0] = False <NEW_LINE> <DEDENT> for j in rang... | :type s: str
:type p: str
:rtype: bool | 625941ea38b623060ff0b2c1 |
def initial_polyhedron(X): <NEW_LINE> <INDENT> dimension = X.shape[1] <NEW_LINE> A = [] <NEW_LINE> b = [] <NEW_LINE> for i in range(dimension): <NEW_LINE> <INDENT> a_upper = [0]*dimension <NEW_LINE> a_lower = [0]*dimension <NEW_LINE> a_upper[i] = 1 <NEW_LINE> a_lower[i] = -1 <NEW_LINE> A.append(a_upper) <NEW_LINE> A.ap... | Returns the initial polyhedron defined by Ax <= b, a unit hypercube
centered at the origin. | 625941ea656771135c3ebd49 |
def test_03_delete_iso(self): <NEW_LINE> <INDENT> self.debug("Deleting ISO with ID: %s" % self.iso_1.id) <NEW_LINE> self.iso_1.delete(self.apiclient) <NEW_LINE> time.sleep(self.services["sleep"]) <NEW_LINE> list_iso_response = list_isos( self.apiclient, id=self.iso_1.id ) <NEW_LINE> self.assertEqual( list_iso_response,... | Test delete ISO
| 625941ea8a43f66fc4b54534 |
def goto ( self, next_state ): <NEW_LINE> <INDENT> i_next_state = self.get_state ( next_state ) <NEW_LINE> if i_next_state in self.STATE_TRANSITION_TABLE [self.state]: <NEW_LINE> <INDENT> self.state = i_next_state <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ConsoleStatusException ( "inval... | state transition | 625941eae5267d203edce16b |
def _parse_property_01(ctx): <NEW_LINE> <INDENT> ctx.p._ancestors = ctx.ancestors <NEW_LINE> ctx.p._depth = len(ctx.ancestors) <NEW_LINE> ctx.p._parent = ctx.parent <NEW_LINE> ctx.p._property_tree = [] | Sets property extension properties. | 625941ea3539df3088e2e820 |
def put(self): <NEW_LINE> <INDENT> data = request.get_json() <NEW_LINE> name = data.pop("name", None) <NEW_LINE> desc = data.pop("desc", None) <NEW_LINE> public = data.pop("public", 0) <NEW_LINE> extra_info = data <NEW_LINE> if not (name and public in [0, 1, None]): <NEW_LINE> <INDENT> return APIResponse(code=BAD_REQUE... | 更新 bucket | 625941ea10dbd63aa1bd3076 |
@report_pages.route('/approved/<string:tag_name>/build', methods=['GET']) <NEW_LINE> @login_required <NEW_LINE> def build_approved_report(tag_name): <NEW_LINE> <INDENT> category = request.args.get('category') <NEW_LINE> tag = database.get(Tag, tag_name, 'name') <NEW_LINE> report_builder.build(tag, category=category) <N... | Builds the an approved report for a tag.
| 625941ea50485f2cf553d270 |
def get_version(version=None): <NEW_LINE> <INDENT> if version is None: <NEW_LINE> <INDENT> version = __version_info__ <NEW_LINE> <DEDENT> if isinstance(version, (list, tuple)): <NEW_LINE> <INDENT> version = '.'.join(map(str, version)) <NEW_LINE> <DEDENT> return version | Returns a PEP 440 version string (in the form of major.minor.micro)
for any ``(major, minor, micro)`` tuple.
:param version: tuple of (major, minor, micro) version numbers
:see: http://legacy.python.org/dev/peps/pep-0440/
If no version is supplied as a parameter, will return this package's
version string. | 625941ea01c39578d7e75310 |
def render(self): <NEW_LINE> <INDENT> self.screen.fill(appdefs.BACKGROUND_COLOR) <NEW_LINE> self.all_sprites.draw(self.screen) <NEW_LINE> pg.display.update() | Fill screen and render all actors. | 625941ead7e4931a7ee9e3f4 |
def get_mail_context(note): <NEW_LINE> <INDENT> app = note.thread.addon <NEW_LINE> if app.name.locale != app.default_locale: <NEW_LINE> <INDENT> lang = to_language(app.default_locale) <NEW_LINE> with translation.override(lang): <NEW_LINE> <INDENT> app = Webapp.objects.get(id=app.id) <NEW_LINE> <DEDENT> <DEDENT> return ... | Get context data for comm emails, specifically for review action emails. | 625941ea97e22403b379d470 |
def utils(opts, whitelist=None, context=None, proxy=None, pack_self=None): <NEW_LINE> <INDENT> return LazyLoader( _module_dirs(opts, "utils", ext_type_dirs="utils_dirs", load_extensions=False), opts, tag="utils", whitelist=whitelist, pack={"__context__": context, "__proxy__": proxy or {}}, pack_self=pack_self, ) | Returns the utility modules | 625941eabd1bec0571d90b03 |
def hosts_get_by_region(context, region_id, filters): <NEW_LINE> <INDENT> host_devices = with_polymorphic(models.Device, [models.Host]) <NEW_LINE> query = model_query(context, host_devices, project_only=True) <NEW_LINE> query = query.filter_by(region_id=region_id) <NEW_LINE> if "name" in filters: <NEW_LINE> <INDENT> qu... | Get all hosts for this region.
:param region_id: ID for the region
:param filters: filters wich contains differnt keys/values to match.
Supported filters are by name, ip_address, id and cell_id. | 625941eafff4ab517eb2f914 |
def bind_put(self, ports, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.bind_put_with_http_info(ports, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.bind_put_with_http_info(ports, **kwargs) <NEW_LINE>... | bind additional listening ports # noqa: E501
only supported on Netty version # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.bind_put(ports, async_req=True)
>>> result = thread.get()
:param async_req bool
:param ... | 625941ea07f4c71912b11959 |
def deleteDuplicates(self, head): <NEW_LINE> <INDENT> if not head or not head.next: <NEW_LINE> <INDENT> return head <NEW_LINE> <DEDENT> h, curr = head, head <NEW_LINE> while curr.next: <NEW_LINE> <INDENT> prev, curr = curr, curr.next <NEW_LINE> if curr.val != prev.val: <NEW_LINE> <INDENT> h.next = curr <NEW_LINE> h = h... | :type head: ListNode
:rtype: ListNode | 625941eacc0a2c11143dd366 |
def exec_line_input(ins): <NEW_LINE> <INDENT> finp = expressions.parse_file_number(ins, 'IR') <NEW_LINE> if not finp: <NEW_LINE> <INDENT> newline = not util.skip_white_read_if(ins, (';',)) <NEW_LINE> prompt = parse_prompt(ins, '') <NEW_LINE> <DEDENT> readvar, indices = expressions.get_var_or_array_name(ins) <NEW_LINE> ... | LINE INPUT: request input from user. | 625941eabaa26c4b54cb15ef |
def connect_user(request, access_token=None, facebook_graph=None, connect_facebook=False): <NEW_LINE> <INDENT> user = None <NEW_LINE> graph = facebook_graph or get_facebook_graph(request, access_token) <NEW_LINE> converter = get_instance_for('user_conversion', graph) <NEW_LINE> assert converter.is_authenticated() <NEW_... | Given a request either
- (if authenticated) connect the user
- login
- register | 625941ead10714528d6001bd |
def isFullySet(self, memoize=False): <NEW_LINE> <INDENT> if memoize: <NEW_LINE> <INDENT> if not self._memoIsFullySet and self.countUnsetSides() == 0: <NEW_LINE> <INDENT> self._memoIsFullySet = True <NEW_LINE> <DEDENT> return self._memoIsFullySet <NEW_LINE> <DEDENT> return self.countUnsetSides() == 0 | Returns true if there are no more UNSET sides remaining in the cell. | 625941eaf548e778e58cda54 |
@plymouth_update_milestone <NEW_LINE> def stop_dbus(): <NEW_LINE> <INDENT> UI.info(_("Stopping %s") % "DBus") <NEW_LINE> run("/sbin/start-stop-daemon", "--stop", "--quiet", "--pidfile", "/run/dbus/pid") | Stops the D-Bus service. | 625941ea091ae3566866742a |
def run_test(res, domain): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return res.query(domain, rdtype=rdatatype.A, rdclass=rdataclass.IN).response.time * 1000 <NEW_LINE> <DEDENT> except resolver.NXDOMAIN as e: <NEW_LINE> <INDENT> return e.kwargs['responses'][list(filter(lambda a: str(a) == (domain + '.'), e.kwargs['r... | run a single dns query test on a server. Query time can be recovered from successful and NXDOMAIN responses | 625941ea21a7993f00bc81cd |
def ssh(): <NEW_LINE> <INDENT> template = 'ssh {0} -i {1} {2} {3}@{4}' <NEW_LINE> command = template.format(conf['ssh-options'], conf['ssh-key'], conf['ssh-forwards'], conf['ssh-user'], conf['ssh-host']).split() <NEW_LINE> proc = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE) <NEW_LINE> data['stdout'] = proc.stdo... | Do ssh to destination host and controll threads count
If threads count not have right value stop all threads and start from scratch
Write controll messages for destination host | 625941ea0a50d4780f66736b |
def findMaximumXOR(self, nums): <NEW_LINE> <INDENT> INT_SIZE = 30 <NEW_LINE> def insert(root, num): <NEW_LINE> <INDENT> node = root <NEW_LINE> i = INT_SIZE <NEW_LINE> while i >= 0 and node.children[(num >> i) & 1] is not None: <NEW_LINE> <INDENT> node = node.children[(num >> i) & 1] <NEW_LINE> i -= 1 <NEW_LINE> <DEDENT... | :type nums: List[int]
:rtype: int | 625941ea6fb2d068a760f57a |
def get_detail_url(url: str) -> set: <NEW_LINE> <INDENT> products = set() <NEW_LINE> page = 1 <NEW_LINE> flag = True <NEW_LINE> while flag: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = { 'keyword': '伊婉', 'cityId': 176, 'page_size': 12, '_json': 1, 'sort': 0, 'service': '', 'coupon': '', 'group': '', 'maxprice'... | 从搜索目录中获取详情页链接
@param url 搜索目录根地址
@return products 所有详情页链接 | 625941eacc0a2c11143dd367 |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.CHUNKSIZE = kwargs.get('chunksize', self.DEF_CHUNKSIZE) <NEW_LINE> self.MARKER = 'SpreadSASLMemcachedCache.SpreadedValue' <NEW_LINE> self.MAXCHUNKS = kwargs.get('maxchunks', self.DEF_MAXCHUNKS) <NEW_LINE> super(SpreadSASLMemcachedCache, self).__init__(*args,... | Kwargs:
chunksize (int): max length of a pickled object that can fit in
memcached (memcache has an upper limit of 1MB for values,
default: 1048448) | 625941ea596a897236089f8e |
def get_auth_cfg(plan: LandUsePlanEnum) -> str: <NEW_LINE> <INDENT> value = get_setting(plan.value.auth_cfg_key, "", str) <NEW_LINE> if value == "": <NEW_LINE> <INDENT> raise QaavaDatabaseNotSetException() <NEW_LINE> <DEDENT> return value | :param plan:
:return: Auth config id name of the connection | 625941eaa8370b7717052d72 |
def probably_prime(n, k): <NEW_LINE> <INDENT> small_primes = sieve(1000) <NEW_LINE> if n < 2: return False <NEW_LINE> for p in small_primes: <NEW_LINE> <INDENT> if n < p * p: return True <NEW_LINE> if n % p == 0: return False <NEW_LINE> <DEDENT> r, s = 0, n - 1 <NEW_LINE> while s % 2 == 0: <NEW_LINE> <INDENT> r += 1 <N... | Return True if n passes k rounds of the Miller-Rabin primality
test (and is probably prime). Return False if n is proved to be
composite. | 625941eab57a9660fec33d60 |
def complete(self, operation): <NEW_LINE> <INDENT> self.callback(self.rcode) | Complete. | 625941eaf548e778e58cda55 |
def test_docs_host_not_excluded(self): <NEW_LINE> <INDENT> with self.settings(LOCALE_MIDDLEWARE_EXCLUDED_HOSTS=[]): <NEW_LINE> <INDENT> resp = self.client.get('/', HTTP_HOST=self.docs_host) <NEW_LINE> <DEDENT> self.assertEqual(resp.status_code, HTTPStatus.FOUND) <NEW_LINE> self.assertIn('Content-Language', resp) <NEW_L... | We still get Content-Language when docs host is not excluded | 625941eaa219f33f34628e37 |
@bp.route('/login', methods=['GET', 'POST']) <NEW_LINE> def login(): <NEW_LINE> <INDENT> if current_user.is_authenticated: <NEW_LINE> <INDENT> return redirect(url_for('main.index')) <NEW_LINE> <DEDENT> form = LoginForm() <NEW_LINE> if form.validate_on_submit(): <NEW_LINE> <INDENT> user = User.query.filter_by(username=f... | View function for the login page | 625941ead10714528d6001be |
def testExplicitPdshWorkerStdErr(self): <NEW_LINE> <INDENT> worker = WorkerPdsh("localhost", command="echo alright 1>&2", handler=None, stderr=True, timeout=5) <NEW_LINE> self.assert_(worker != None) <NEW_LINE> self._task.schedule(worker) <NEW_LINE> self._task.resume() <NEW_LINE> self.assertEqual(worker.node_error_buff... | test simple localhost command with explicit pdsh worker (stderr) | 625941ea94891a1f4081bf81 |
def longestValidParentheses(self, s): <NEW_LINE> <INDENT> if len(s) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> lvp = [0] * len(s) <NEW_LINE> if s[len(s)-2] == '(' and s[len(s)-1] == ')': <NEW_LINE> <INDENT> lvp[len(s)-2] = 2 <NEW_LINE> <DEDENT> for i in range(len(s)-3, -1, -1): <NEW_LINE> <INDENT> if s[i] =... | :type s: str
:rtype: int | 625941ea8da39b475bd6544f |
def delayed_kill(cmd): <NEW_LINE> <INDENT> kill_container_at[cmd] = int(time.time()) + kill_container_after | We can define a web request as one request,
which will load multiple sources (e.g. css, html, js)
for this reason, we want our container to keep running
for a short time, to be sure that it can respond to multiple
http request for a single web page request.
The delayed kill time should be rescheduled every time a cont... | 625941eaff9c53063f47c6c6 |
def cmd_generate(nfiles, nsamples, folder, length, temperature, batch_size, prefix, truncate, include_prefix, sample_delim, run_name, checkpoint_dir, top_k, top_p, multi_gpu): <NEW_LINE> <INDENT> sess = start_tf_sess() <NEW_LINE> load_gpt2(sess, run_name=run_name, checkpoint_dir=checkpoint_dir, multi_gpu=multi_gpu) <NE... | Wrapper script for generating text via the CLI.
The files are generated into a folder, which can be downloaded
recursively by downloading the entire folder. | 625941ea9b70327d1c4e12ad |
def on_aborted(self): <NEW_LINE> <INDENT> logging.error('Authentication aborted') <NEW_LINE> self.is_authenticating.acquire() <NEW_LINE> self.is_authenticating.notify_all() <NEW_LINE> self.is_authenticating.release() | Triggered when device authentication was aborted (either with `DeviceOAuthPoller.stop()`
or via the "poll" event) | 625941ea63f4b57ef00015e0 |
def locked(func, lockname='_lock'): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def _wrapper_(self, *args, **kwargs): <NEW_LINE> <INDENT> with getattr(self, lockname): <NEW_LINE> <INDENT> return func(self, *args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> return _wrapper_ | Thread-locking object method decorator. | 625941ea07f4c71912b1195a |
def __init__(self, init_args): <NEW_LINE> <INDENT> for arg_name in init_args: <NEW_LINE> <INDENT> setattr(self, arg_name, init_args[arg_name]) | Initializes attribute class with init_args | 625941ea0383005118ecfab6 |
def train(self): <NEW_LINE> <INDENT> num_train = self.X_train.shape[0] <NEW_LINE> iterations_per_epoch = int(max(num_train / self.batch_size, 1)) <NEW_LINE> num_iterations = int(self.num_epochs * iterations_per_epoch) <NEW_LINE> for t in range(num_iterations): <NEW_LINE> <INDENT> self._step() <NEW_LINE> if self.verbose... | Run optimization to train the model. | 625941ea004d5f362079a805 |
def begin_shard(self, shard_ctx): <NEW_LINE> <INDENT> pass | Called at the beginning of a shard.
This method may be called more than once due to shard and slice retry.
Make it idempotent.
Args:
shard_ctx: map_job.ShardContext object. | 625941ea24f1403a92601037 |
def set_default_mode(self, resources, mode): <NEW_LINE> <INDENT> self._set_resource_option(resources, key='mode', value=mode) | Set the default mode for the specified resources. | 625941eaf9cc0f698b140acc |
def test(): <NEW_LINE> <INDENT> for program, result in test_inoutputs: <NEW_LINE> <INDENT> assert compute(program) == result | Test given inputs | 625941ea460517430c39464d |
def is_codec_mpg2_enabled(): <NEW_LINE> <INDENT> return get_codec_enabled("MPG2") | Determine if the MPG2 code is enabled.
:returns: True if enabled; Otherwise, False.
:rtype: bool | 625941ea4428ac0f6e5baccc |
def cb(content=None): <NEW_LINE> <INDENT> clipboard = QApplication.clipboard() <NEW_LINE> if content is None: <NEW_LINE> <INDENT> return str(clipboard.text()) <NEW_LINE> <DEDENT> clipboard.setText(str(content)) | Copies content to clipboard. If no content, returns clipboard content. | 625941ea4e4d5625662d48a6 |
def read_annotations(self): <NEW_LINE> <INDENT> with open(self.annotations_file) as file: <NEW_LINE> <INDENT> annotations = [float(line.rstrip()) for line in file] <NEW_LINE> <DEDENT> return annotations | Read annotations from text file line by line.
If required, split the drum instrument tag from the timestamp
Would be like: 2.35 bd
3.47 sd | 625941ea3eb6a72ae02ec9c0 |
def exit(self): <NEW_LINE> <INDENT> if self.confirm_exit: <NEW_LINE> <INDENT> if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): <NEW_LINE> <INDENT> self.ask_exit() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.ask_exit() | Handle interactive exit.
This method calls the ask_exit callback. | 625941eaa934411ee3751b6a |
def get_data_context(): <NEW_LINE> <INDENT> global _DATA_CONTEXT <NEW_LINE> return _DATA_CONTEXT | Return the global DataContext object. | 625941ea8a349b6b435e8648 |
def FlipCase( sText, bAlternate = False ): <NEW_LINE> <INDENT> lParts = oFinderCRorLFnMore.split( sText ) <NEW_LINE> if bAlternate: <NEW_LINE> <INDENT> def getFlip( s, i ): <NEW_LINE> <INDENT> if i % 2: <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return s.swapcase() <NEW_LINE> <DEDENT> ... | if bAlternate = False aBcDeF becomes AbCdEf
if bAlternate = True aBcDeF becomes ABCDEF
BUT
now that this code is accomodating new lines,
\n & \r should not be swapped to \N or \R !!!! | 625941eade87d2750b86026d |
def add(self, flow_detail): <NEW_LINE> <INDENT> self._flowdetails.append(flow_detail) | Adds a new entry to the underlying logbook.
Does not *guarantee* that the details will be immediatly saved. | 625941ea91f36d47f21ac9cd |
def q4(self): <NEW_LINE> <INDENT> self.args['roles']['yubin'].discard('warrior') <NEW_LINE> return self.args['roles']['yubin'] | 將 'warrior'角色從 yubin 的使用角色中刪除, 提示 discard | 625941ea4a966d76dd5514ea |
def get_position(self, val, idx): <NEW_LINE> <INDENT> return self.axes[idx].index(val) | This function will try to convert the types of
the values in the array.
Input:
- val the values
- idx the axis index
Output:
- position of the indices | 625941ea15baa723493c444f |
def switchDnNodeProcess(): <NEW_LINE> <INDENT> if g_opts.rolling: <NEW_LINE> <INDENT> start_time = timeit.default_timer() <NEW_LINE> switchFencedUDFProcess() <NEW_LINE> elapsed = timeit.default_timer() - start_time <NEW_LINE> g_logger.log( "Time to switch gaussdb fenced udf: %s" % getTimeFormat(elapsed)) <NEW_LINE> <DE... | function: switch node process which CN or DN exits
:return: | 625941eab545ff76a89142eb |
def __getattr__(self, attr): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.attributes[attr] <NEW_LINE> <DEDENT> except (KeyError, TypeError): <NEW_LINE> <INDENT> raise AttributeError( "'%s' object has no attribute '%s'" % (self.__class__, attr)) | Attribute shortcut.
Data classes have their attributes stored in the `attributes` attribute,
a dictionary. For convenience, access to attributes can be shortcut by
accessing the attributes directly::
>>> var = DapType('var')
>>> var.attributes['foo'] = 'bar'
>>> print var.foo
bar
| 625941ea3d592f4c4ed1d536 |
def filter(self, targdict=None, data=True, container=False, recursive=True, objects=None, **kwargs): <NEW_LINE> <INDENT> if objects: <NEW_LINE> <INDENT> data = True <NEW_LINE> container = True <NEW_LINE> <DEDENT> children = [] <NEW_LINE> if data: <NEW_LINE> <INDENT> if recursive: <NEW_LINE> <INDENT> children.extend(sel... | Return a list of child objects matching *any* of the search terms
in either their attributes or annotations. Search terms can be
provided as keyword arguments or a dictionary, either as a positional
argument after data or to the argument targdict. targdict can also
be a list of dictionaries, in which case the filters... | 625941eabf627c535bc136a5 |
def trigger_callback(self, sid, namespace, id, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> callback = self.callbacks[sid][namespace][id] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise ValueError('Unknown callback') <NEW_LINE> <DEDENT> del self.callbacks[sid][namespace][id] <NEW_LINE> callback(*d... | Invoke an application callback. | 625941ea2ae34c7f2600d606 |
def make_file(self, filename): <NEW_LINE> <INDENT> return("-".join(filter(None, [self.lang, self.project, self.date, filename]))) | Create a filename in the format "langcode-project-date-restofname
Returns the filename | 625941ea187af65679ca55f5 |
def __getattr__(self, name): <NEW_LINE> <INDENT> if hasattr(self.box, name): <NEW_LINE> <INDENT> return getattr(self.box, name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError( "'MemorizedBox' and associated box objects have no attribute " "'{0}'".format(name)) | Define behavior for when a user attempts to access an attribute
of a MemorizedBox instance.
__getattr__ is only invoked if the attribute wasn't found the usual
ways, so we first check the MemorizedBox object and then the box
object.
Parameters
----------
name: string
the name of the parameter we want to access. | 625941ea379a373c97cfb01d |
def strategy(self, opponent: Player) -> Action: <NEW_LINE> <INDENT> if len(self.history) >= 2: <NEW_LINE> <INDENT> if self.history[-2] == D: <NEW_LINE> <INDENT> if opponent.history[-1] == C: <NEW_LINE> <INDENT> self.cd_counts += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.dd_counts += 1 <NEW_LINE> <DEDENT> <DE... | Actual strategy definition that determines player's action. | 625941ea26068e7796caf1bc |
def test_encode_none_raises(self): <NEW_LINE> <INDENT> item = ApplicationContextItem() <NEW_LINE> msg = "'Application Context Name' must be str, bytes or UID, not 'NoneType'" <NEW_LINE> with pytest.raises(TypeError, match=msg): <NEW_LINE> <INDENT> item.application_context_name = None | Test encoding None raises an exception | 625941ea60cbc95b062c6a19 |
def connect(self, scheme, address, port): <NEW_LINE> <INDENT> if scheme == "http": <NEW_LINE> <INDENT> print("SSLyze cannot scan a http port") <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> port = int(port) <NEW_LINE> try: <NEW_LINE> <INDENT> server_tester = ServerConnectivityTester( hostname=add... | Run all configurations necessary to perform a test against the target. This function is mean to set up
the connection to the target. The function should work for one or two specified ports if supported by engine
:param scheme: http or https
:type scheme: str
:param: address
:type: str
:param port:
:type str: | 625941ea8e71fb1e9831dc7d |
def update(self, idx, item): <NEW_LINE> <INDENT> assert self.contains_idx(idx), f"idx {idx} has not been added." <NEW_LINE> self._items[idx] = item <NEW_LINE> self._swim(self._heap_idx[idx]) <NEW_LINE> self._sink(self._heap_idx[idx]) | Update the item associted with the given idx.
Heap order is maintained afterwards. | 625941ea24f1403a92601038 |
def get_tree_root(self): <NEW_LINE> <INDENT> root = self <NEW_LINE> while root.up is not None: <NEW_LINE> <INDENT> root = root.up <NEW_LINE> <DEDENT> return root | Returns the absolute root node of current tree structure. | 625941ea82261d6c526ab97d |
def fromBase64(self, base64): <NEW_LINE> <INDENT> return QByteArray() | static QByteArray QByteArray.fromBase64(QByteArray base64) | 625941eae76e3b2f99f3acd9 |
def set_parse_mode(self, parse_mode: Union[str, None] = "combined"): <NEW_LINE> <INDENT> if parse_mode not in self.PARSE_MODES: <NEW_LINE> <INDENT> raise ValueError('parse_mode must be one of {} or None. Not "{}"'.format( ", ".join('"{}"'.format(m) for m in self.PARSE_MODES[:-1]), parse_mode )) <NEW_LINE> <DEDENT> self... | Set the parse mode to be used globally by the client.
When setting the parse mode with this method, all other methods having a *parse_mode* parameter will follow the
global value by default. The default value *"combined"* enables both Markdown and HTML styles to be used and
combined together.
Parameters:
parse_mo... | 625941ead268445f265b5345 |
@app.route('/employees/<int:count>', methods=['GET']) <NEW_LINE> def get_employees_count(count): <NEW_LINE> <INDENT> results = users.get_employees_count_with_prefix(dbconn, count, None) <NEW_LINE> return response.get_multi_result(results) | Return any active employee id
---
tags:
- employee
parameters:
- in: path
name: count
type: integer
format: int
required: true
description: Users count
responses:
200:
description: Return counts of active employees id | 625941ea55399d3f05588b8d |
def _change_pattern_position(self, position): <NEW_LINE> <INDENT> green = self._green_radio_buttons[position].isSelected() <NEW_LINE> red = self._red_radio_buttons[position].isSelected() <NEW_LINE> colour_char = "B" <NEW_LINE> if green and red: <NEW_LINE> <INDENT> colour_char = "O" <NEW_LINE> <DEDENT> elif green: <NEW_... | Change a character at the given position
Character to use comes from the values of the red and green radio
buttons at that position | 625941eaadb09d7d5db6cc62 |
def write_bit(value, bit_num, address, board_num=0): <NEW_LINE> <INDENT> bit_mask = get_bit_mask(bit_num) <NEW_LINE> old_byte = read(address, board_num) <NEW_LINE> if value: <NEW_LINE> <INDENT> new_byte = old_byte | bit_mask <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_byte = old_byte & ~bit_mask <NEW_LINE> <DEDEN... | Writes the value given to the bit in the address specified.
:param value: The value to write.
:type value: int
:param bit_num: The bit number to write to.
:type bit_num: int
:param address: The address to write to.
:type address: int
:param board_num: The board number to write to.
:type board_num: int | 625941ea046cf37aa974d219 |
def blocks_attack(self, defender: ISituationSpecies, attacker: ISituationSpecies, defenders_left_neighbor: OptSituationSpecies = NoSituationSpecies, defenders_right_neighbor: OptSituationSpecies = NoSituationSpecies, owner_flag: OptSituationFlag = NoSituationFlag) -> bool:... | Does this TraitCard block attacks from a given attacker and the defenders neighbors
:param defender: The defending Species
:param attacker: The attacking Carnivore
:param defenders_left_neighbor: The defender's left neighbor,
:param defenders_right_neighbor: The defender's right neighbo... | 625941ea0a50d4780f66736c |
def LU2(A): <NEW_LINE> <INDENT> m,n = A.shape <NEW_LINE> U = np.array(np.copy(A), dtype=float) <NEW_LINE> L = np.zeros((n,n)) <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> L[i,i] = 1 <NEW_LINE> <DEDENT> for i in range(1,n): <NEW_LINE> <INDENT> for j in range(i): <NEW_LINE> <INDENT> L[i,j] = U[i,j]/U[j,j] <NEW_LINE>... | Returns the LU decomposition of a square matrix A. | 625941ea7cff6e4e81117e5b |
@given(headers=st.lists(elements=st.text(), min_size=2), col_maker=dvalues) <NEW_LINE> def test_repandasify_roundtrip(headers, col_maker): <NEW_LINE> <INDENT> d = st.dictionaries(keys=headers,values=col_maker()) <NEW_LINE> df = pd.DataFrame.from_dict(d) <NEW_LINE> arr = np.array(df) <NEW_LINE> assert df == crun.sklearn... | Test repandasify roundtrip. | 625941ea8c3a873295158897 |
@app.route('/') <NEW_LINE> def index(): <NEW_LINE> <INDENT> flash("Welcome to my blog page!") <NEW_LINE> return render_template( "index.html" ) | Main webpage | 625941ea6fece00bbac2dc1b |
def _enqueue_task(self, task_id): <NEW_LINE> <INDENT> self._pending_queue.enqueue(task_id) <NEW_LINE> AsyncResult(task_id).pend() <NEW_LINE> self._dequeue_task() | Puts a task into the task queue, after which checks if there're tasks
available to run. | 625941ea4e696a04525c9924 |
def test_set_tau_popview(self): <NEW_LINE> <INDENT> self.net_pop1[1:3, 1].tau = 5.0 <NEW_LINE> self.assertTrue(numpy.allclose(self.net_pop1.tau, [[10., 10., 10.], [10., 5., 10.], [10., 5., 10.]])) | Assigned a new value, all instances will change normally.
One can use *PopulationView* to update more specific. | 625941ea91f36d47f21ac9ce |
def _normalize_string(orig): <NEW_LINE> <INDENT> return orig.replace('"', '').replace("'", "").strip() | Helper function for _get_systemd_os_release_var() to remove quotes
and whitespaces around the string (strip/trim) | 625941ea0383005118ecfab7 |
def build_input(input_index, embedding_size=None, name='de'): <NEW_LINE> <INDENT> embedding_layer = build_embedding(embedding_size[0], embedding_size[1]) <NEW_LINE> embedding_out = tf.nn.embedding_lookup(embedding_layer, input_index, name=name) <NEW_LINE> return embedding_out | - embeddinng_size: ListType Length>=2 | 625941ea67a9b606de4a838d |
def rmfile(path): <NEW_LINE> <INDENT> if osp.isfile(path): <NEW_LINE> <INDENT> if is_win: <NEW_LINE> <INDENT> os.chmod(path, 0o777) <NEW_LINE> <DEDENT> os.remove(path) | Ensure file deleted also on *Windows* where read-only files need special treatment. | 625941ea32920d7e50b286aa |
def icao_engine(df: pd.DataFrame) -> pd.DataFrame: <NEW_LINE> <INDENT> sel_401 = bool_df(df, [("mfg", "AIR TRACTOR"), ("model", "(401){1}")]).all(axis=1) <NEW_LINE> sel_turbine_ag = ((df.mfg == "AIR TRACTOR") & -sel_401) | ( df.mfg == "THRUSH AIRCRAFT" ) <NEW_LINE> df.loc[(sel_turbine_ag), "icao_type_desc"] = "L1T" <NE... | Normalize the icao_type_desc to the following for ag aircraft:
- L1T: Land Plane, Single Engine, Turboprop
- L1P: Land Plane, Single Engine, Piston | 625941ea498bea3a759b9f84 |
def deregister_instances(self, load_balancer_name, instances): <NEW_LINE> <INDENT> params = {'LoadBalancerName': load_balancer_name} <NEW_LINE> self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') <NEW_LINE> return self.get_list('DeregisterInstancesFromLoadBalancer', params, [('member', InstanceI... | Remove Instances from an existing Load Balancer.
:type load_balancer_name: string
:param load_balancer_name: The name of the Load Balancer
:type instances: List of strings
:param instances: The instance ID's of the EC2 instances to remove.
:rtype: List of strings
:return: An updated list of instances for this Load Bala... | 625941ea38b623060ff0b2c3 |
def mwGetIndex(config={}): <NEW_LINE> <INDENT> if config['mwapi']: <NEW_LINE> <INDENT> mwapi = config['mwapi'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mwapi = mwGetAPI(config=config) <NEW_LINE> <DEDENT> index = '' <NEW_LINE> html = wikiteam.getURL(url=config['wiki']) <NEW_LINE> m = re.findall(r'<li id="ca-viewsou... | Returns Index.php for a MediaWiki wiki, if available | 625941eaf8510a7c17cf9bd6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.