code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def close(self): <NEW_LINE> <INDENT> return self._df["close"] | [float] 收盘价 | 625941b221bff66bcd6846fa |
def longestPalindrome(self, s): <NEW_LINE> <INDENT> result = "" <NEW_LINE> if len(set(s))==1: <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> l = len(s) <NEW_LINE> for i in range(l): <NEW_LINE> <INDENT> temp = self.checkPal(s, i, l, 0, 0) <NEW_LINE> if len(temp) > len(result): <NEW_LINE> <INDENT> result = temp <NEW_L... | :type s: str
:rtype: str | 625941b291f36d47f21ac292 |
def get_principal_axis_3D(points): <NEW_LINE> <INDENT> coord= numpy.array(points, float) <NEW_LINE> center= numpy.mean(coord, 0) <NEW_LINE> coord= coord - center <NEW_LINE> inertia = numpy.dot(coord.transpose(), coord) <NEW_LINE> e_values, e_vectors = numpy.linalg.eig(inertia) <NEW_LINE> order = numpy.argsort(e_values)... | Compute principal axes
:param points: 3D point cloud. | 625941b2cad5886f8bd26d7f |
def handle_keyboard_interrupt(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = func(*args, **kwargs) <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> logger.debug( "Running %s: Received KeyboardInterrupt, " ... | Decorator for handling keyboard interrupt.
It is assumed that this decorator is used in subprocesses.
(the debug message is formulated accordingly) | 625941b23346ee7daa2b2b05 |
def game_action_to_str(action): <NEW_LINE> <INDENT> def convert(o): <NEW_LINE> <INDENT> if o is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif isinstance(o, bool): <NEW_LINE> <INDENT> return int(o) <NEW_LINE> <DEDENT> elif isinstance(o, Card): <NEW_LINE> <INDENT> return o.ident <NEW_LINE> <DEDENT> elif ... | Serialize a GameAction as a string. | 625941b2fbf16365ca6f5f60 |
def __update_mouse(self): <NEW_LINE> <INDENT> if not self.__stats.running: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> x, y = ctypes.c_int(0), ctypes.c_int(0) <NEW_LINE> state = sdl2.mouse.SDL_GetMouseState(ctypes.byref(x), ctypes.byref(y)) <NEW_LINE> world_unit = 1 / min(self.__systems.window.size) <NEW_LINE> self.... | Updates 'mouse_pos'. | 625941b2507cdc57c6306a6f |
def __init__(self, url): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36', } | 初始化参数
:param url:需要爬取的公交路线的网址url | 625941b2fb3f5b602dac3434 |
@app.route('/train', methods=['GET','POST']) <NEW_LINE> def trainAPI(): <NEW_LINE> <INDENT> if not request.json: <NEW_LINE> <INDENT> print("ERROR: No request data received") <NEW_LINE> return jsonify(False) <NEW_LINE> <DEDENT> test = False <NEW_LINE> if 'mode' in request.json and request.json['mode'] == 'test': <NEW_LI... | train API | 625941b226238365f5f0ec0a |
def assign_bins_fix_width(self, lim, wid, num, include_max=False): <NEW_LINE> <INDENT> self.lim = lim <NEW_LINE> self.wid = self.get_bin_width(lim, wid, num) <NEW_LINE> self.mins = ut_array.arange_safe(self.lim, self.wid, include_max) <NEW_LINE> if include_max: <NEW_LINE> <INDENT> self.mids = self.mins[:-1] + 0.5 * sel... | Import bin limits, number of bins, bin width,
whether to include limit maximum in bin minnima.
If limit is infinite, set width to infinity.
If number defined, set width to give that number of bins. | 625941b25e10d32532c5eccd |
def get_key_run(self, machine, day_index): <NEW_LINE> <INDENT> if self.machine_runs is None: <NEW_LINE> <INDENT> raise ArgumentError("report not initialized") <NEW_LINE> <DEDENT> if day_index >= self.num_prior_days_to_include: <NEW_LINE> <INDENT> raise ArgumentError("invalid day index") <NEW_LINE> <DEDENT> runs = self.... | get_key_run(machine, day_index) -> Run or None
Get the "key" run for the given machine and day index, or None if there
are no runs for that machine and day.
The key run is an arbitrarily selected run from all the available runs
that reported for the reported run order, for that machine and day. | 625941b2e8904600ed9f1cc6 |
def find_collection_usager(self, user_id: str): <NEW_LINE> <INDENT> filtre = { ConstantesGrosFichiers.DOCUMENT_FICHIER_UUID_DOC: user_id, } <NEW_LINE> collection = self.get_collection() <NEW_LINE> collection_usager = collection.find_one(filtre) <NEW_LINE> if collection_usager is None: <NEW_LINE> <INDENT> filtre = { Con... | Trouve la collection correspondant au user_id
:param user_id:
:return: | 625941b2091ae35668666d04 |
def cancel(self, subscription): <NEW_LINE> <INDENT> customer_obj = self.conekta.Customer.find(subscription.customer.id) <NEW_LINE> customer_obj.subscription.cancel() <NEW_LINE> return True | Delete cancel | 625941b215baa723493c3d0f |
def clear(self): <NEW_LINE> <INDENT> for i in reversed(range(self.layout().count())): <NEW_LINE> <INDENT> self.layout().itemAt(i).widget().deleteLater() | Removes the widgets attached to the main window.
| 625941b2435de62698dfd9f2 |
def attach_physics_node(self, physics_node_name=DEFAULT_PHYSICS_NODE_NAME, physics_model=DEFAULT_PHYSICS_MODEL_NAME, node_name=DEFAULT_NODE_NAME, inline_parameters=None): <NEW_LINE> <INDENT> assert isinstance(node_name, NodeName) <NEW_LINE> physics_node = { 'body': physics_model, 'target': str(node_name) } <NEW_LINE> i... | Attach a physics node to the JSON representation. | 625941b2462c4b4f79d1d46d |
def test_boblight_client_get_lights(self, boblightd, tested_client): <NEW_LINE> <INDENT> tested_client.say_hello() <NEW_LINE> tested_client.get_lights() <NEW_LINE> assert sorted([light.name for light in tested_client.lights.values()]) == sorted(['right', 'left']) <NEW_LINE> assert tested_client.lights['left'].left == 0... | Check that client handles light configuration | 625941b24a966d76dd550da8 |
def test_events(): <NEW_LINE> <INDENT> tempdir = _TempDir() <NEW_LINE> raw = read_raw_brainvision(vhdr_path, eog=eog, preload=True) <NEW_LINE> events = raw.get_brainvision_events() <NEW_LINE> assert_array_equal(events, [[487, 1, 253], [497, 1, 255], [1770, 1, 254], [1780, 1, 255], [3253, 1, 254], [3263, 1, 255], [4936,... | Test reading and modifying events | 625941b2d7e4931a7ee9dcbe |
def remove_file_if_exists(path): <NEW_LINE> <INDENT> if os.path.isfile(path): <NEW_LINE> <INDENT> logging.info('Found file %s, removing...' % path) <NEW_LINE> os.remove(path) | Check if a file exists, and remove if it does. This also logs any action to the root logger.
Args:
path (string): the path to the file to check and/or remove. | 625941b2d10714528d5ffa83 |
def create_subscription(driver, time_value='5d'): <NEW_LINE> <INDENT> email, name = generate_email_name() <NEW_LINE> email_field = get_email_field(driver) <NEW_LINE> email_field.send_keys(email) <NEW_LINE> username_field = get_username_field(driver) <NEW_LINE> username_field.send_keys(name) <NEW_LINE> time_field = get_... | utility to create new subscription
:return: tuple(email, name) | 625941b26e29344779a623b4 |
def check_state(self): <NEW_LINE> <INDENT> for floor in self.floors: <NEW_LINE> <INDENT> chips = {chip.element for chip in floor if isinstance(chip, Chip)} <NEW_LINE> gens = {gen.element for gen in floor if isinstance(gen, Gen)} <NEW_LINE> irradiated = len(gens) <NEW_LINE> unprotected = False <NEW_LINE> for chip in chi... | >>> state = State([[], [], []])
>>> state.check_state()
True
>>> State([[Gen('a')], [Chip('b')]]).check_state()
False
>>> State([[Gen('h'), Chip('h'), Gen('l')]]).check_state()
True
>>> State([[Gen('b'), Chip('b')]]).check_state()
True
>>> State([[Gen('h'), Chip('t'), Gen('l')]]).check_state()
Traceback (most recent ca... | 625941b28c0ade5d55d3e75d |
def download_file_helper(url, filename='', download=False): <NEW_LINE> <INDENT> if settings.DEBUG: <NEW_LINE> <INDENT> return redirect(url) <NEW_LINE> <DEDENT> response = HttpResponse() <NEW_LINE> response['Content-Type'] = '' <NEW_LINE> response['X-Accel-Redirect'] = url <NEW_LINE> if download: <NEW_LINE> <INDENT> res... | Set download to make browsers download instead of displaying inline. | 625941b232920d7e50b27f71 |
def run(self): <NEW_LINE> <INDENT> print("M - manual control; R - distance, A - Control all legs") <NEW_LINE> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> char = getch() <NEW_LINE> if char == "a": self.move_all() <NEW_LINE> if char == "f": self.walk() <NEW_LINE> if char == "g": self.crawl(.02, 0, True) <NEW... | Main loop for keyboard control | 625941b26fece00bbac2d4d8 |
def _input(self, name, value='', attrs=[], comment=None): <NEW_LINE> <INDENT> element_type = self._called_method <NEW_LINE> a = self.attrs(attrs, ' ') <NEW_LINE> attrs2 = [('type', element_type), ('name', name)] <NEW_LINE> if element_type != 'file': <NEW_LINE> <INDENT> attrs2.append(('value', value)) <NEW_LINE> <DEDENT... | generates a text/hidden/checkbox/radio input
@type name: str
@param name: name of field
@type value: basestring
@param value: default value of field
@type attrs: basestring|list|tuple|dict|OrderedDict
@param attrs: attributes
@type comment: None|basestring
@param comment: <!-- /something --> behind the tag
@rtype: bas... | 625941b27c178a314d6ef1f5 |
def get_contour_line_style(self): <NEW_LINE> <INDENT> return self.contour_line_style | Returns the line style for contour lines as a string.
Default is a solid line as "-". | 625941b250812a4eaa59c0c4 |
def get_hashtags(s): <NEW_LINE> <INDENT> hashtags=[] <NEW_LINE> s=s.split() <NEW_LINE> for word in s: <NEW_LINE> <INDENT> if word[0]=='#': <NEW_LINE> <INDENT> if validate_hashtag(word) == True: <NEW_LINE> <INDENT> hashtags.append(word) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return(hashtags) | Takes in string as arguement
splits string by spaces
tests for hashtag for every word
returns list of valid hashtags | 625941b24f88993c3716be13 |
def max(self,x): <NEW_LINE> <INDENT> while x.right != self.nil: <NEW_LINE> <INDENT> x = x.right <NEW_LINE> <DEDENT> return x | Calculates maximun element of the tree
@return node x
time-complexity: O(h)
space-complexity: O(1) | 625941b20a50d4780f666c2c |
def _register_build(manifest, keeper_url, keeper_token): <NEW_LINE> <INDENT> data = {'git_refs': manifest.refs} <NEW_LINE> if manifest.build_id is not None: <NEW_LINE> <INDENT> data['slug'] = manifest.build_id <NEW_LINE> <DEDENT> if manifest.requester_github_handle is not None: <NEW_LINE> <INDENT> data['github_requeste... | Register this documentation build with LTD Keeper
This registration step tells ltd-mason where to upload the documentation
files (bucket and directory).
Raises
------
KeeperError
Any anomaly with LTD Keeper interaction. | 625941b2627d3e7fe0d68bec |
def get_possible_tabkeys_lengths(self): <NEW_LINE> <INDENT> if self.rules: <NEW_LINE> <INDENT> max_len = self.rules["above"] <NEW_LINE> return [len(self.rules[x]) for x in range(2, max_len+1)][:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> least_commit_len = int(self.ime_properties.get('least... | Return a list of the possible lengths for tabkeys in this table.
Example:
If the table source has rules like:
RULES = ce2:p11+p12+p21+p22;ce3:p11+p21+p22+p31;ca4:p11+p21+p31+p41
self._rules will be set to
self._rules={2: [(1, 1), (1, 2), (2, 1), (2, 2)], 3: [(1, 1), (1, 2), (2, 1), (3, 1)], 4: [(1, 1), (2,... | 625941b266656f66f7cbbf4f |
def sh_no_block(cmd, *args, **kwargs): <NEW_LINE> <INDENT> if isinstance(cmd, str): <NEW_LINE> <INDENT> cmd = cmd.split() <NEW_LINE> <DEDENT> return subprocess.Popen(cmd, *args, **kwargs) | Run sh command without blocking output. | 625941b24527f215b584c202 |
def calc_modtran_max_water(paths: Pathnames) -> float: <NEW_LINE> <INDENT> max_water = None <NEW_LINE> xdir = { 'linux': 'linux', 'darwin': 'macos', 'windows': 'windows' } <NEW_LINE> name = 'H2O_bound_test' <NEW_LINE> filebase = os.path.join(paths.lut_h2o_directory, name) <NEW_LINE> with open(paths.h2o_template_path, '... | MODTRAN may put a ceiling on "legal" H2O concentrations. This function calculates that ceiling. The intended
use is to make sure the LUT does not contain useless gridpoints above it.
Args:
paths: object containing references to all relevant file locations
Returns:
max_water - maximum MODTRAN H2OSTR value f... | 625941b297e22403b379cd3a |
def topKFrequent(self, nums, k): <NEW_LINE> <INDENT> dict = {} <NEW_LINE> for num in nums: <NEW_LINE> <INDENT> if num in dict.keys(): <NEW_LINE> <INDENT> dict[num] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dict[num] = 1 <NEW_LINE> <DEDENT> <DEDENT> sorted_dict = sorted(dict.items(), key=lambda x: x[1], reverse... | :type nums: List[int]
:type k: int
:rtype: List[int] | 625941b250485f2cf553cb36 |
def requires(self): <NEW_LINE> <INDENT> return [SanityTestUICollection(output_base_path=self.output_base_path, mongodb_output_collection_name=self.mongodb_output_collection_name)] | Tell Luigi that the SanityTestUICollection task needs to be completed
before running this task. | 625941b260cbc95b062c62e7 |
def lightSuccess(self): <NEW_LINE> <INDENT> def f(): <NEW_LINE> <INDENT> def g(): <NEW_LINE> <INDENT> pr.set_color(r=0, g=255, b=0) <NEW_LINE> <DEDENT> thread = Thread(target=g) <NEW_LINE> thread.daemon = True <NEW_LINE> thread.start() <NEW_LINE> self.turnLightOff = False <NEW_LINE> time.sleep(2) <NEW_LINE> self.turnLi... | Green light signaling the transcript matched a command | 625941b2a4f1c619b28afdea |
def createRoundKey(expandedKey, roundKeyPointer): <NEW_LINE> <INDENT> roundKey = [0] * 16 <NEW_LINE> for i in range(4): <NEW_LINE> <INDENT> for j in range(4): <NEW_LINE> <INDENT> roundKey[j*4+i] = expandedKey[roundKeyPointer + i*4 + j] <NEW_LINE> <DEDENT> <DEDENT> return roundKey | Create a round key.
Creates a round key from the given expanded key and the
position within the expanded key. | 625941b27c178a314d6ef1f6 |
def get_messages(self): <NEW_LINE> <INDENT> self.logger.info('Loading messages') <NEW_LINE> try: <NEW_LINE> <INDENT> sqs = boto3.resource('sqs') <NEW_LINE> queue = sqs.Queue(self.queue_url) <NEW_LINE> return queue.receive_messages( MaxNumberOfMessages=10, VisibilityTimeout=600) <NEW_LINE> <DEDENT> except boto3.exceptio... | Gets the next few messages | 625941b230dc7b7665901710 |
def state_def(self): <NEW_LINE> <INDENT> return iter([]) | Yields tuples of (key, cell) which are to be part of the object's exported state.
These cells are in addition to to those defined by decorators, not replacing them. | 625941b216aa5153ce36221a |
def sobel(image): <NEW_LINE> <INDENT> sobelx = cv2.Sobel(image, cv2.CV_64F, 1, 0, -1) <NEW_LINE> sobelx = cv2.convertScaleAbs(sobelx) <NEW_LINE> sobely = cv2.Sobel(image, cv2.CV_64F, 0, 1, -1) <NEW_LINE> sobely = cv2.convertScaleAbs(sobely) <NEW_LINE> sobelxy = cv2.Sobel(image, cv2.CV_64F, 1, 1) <NEW_LINE> sobelxy = cv... | sobel算子是一种模拟计算梯度的差分算子,也是一种基于一阶导数的边缘检测算子,由于有局部平均的作用,也能很好的消除噪声
参数dx表示水平方向求导,dy表示垂直方向求导,ddepth表示图像深度 | 625941b2099cdd3c635f09fc |
def test_list_pop_with_incorrect_policy(self): <NEW_LINE> <INDENT> key = ('test', 'demo', 1) <NEW_LINE> policy = { 'timeout': 0.5 } <NEW_LINE> try: <NEW_LINE> <INDENT> TestListPop.client.list_pop(key, "contact_no", 0, {}, policy) <NEW_LINE> <DEDENT> except e.ParamError as exception: <NEW_LINE> <INDENT> assert exception... | Invoke list_pop() with incorrect policy | 625941b21b99ca400220a84f |
def on_about(self): <NEW_LINE> <INDENT> dialog = CloppyButtonWindow(self.master.editor_window) <NEW_LINE> dialog.set_message( f'This program was made by:\n' f'LargeKnome, Hanyuone, and Meta\n' ) <NEW_LINE> dialog.add_choice('Ok') <NEW_LINE> dialog.show() | Called when the 'About' action is selected from the Help menu. | 625941b2adb09d7d5db6c532 |
def run_partition(data, smallk, largek, method, max_depth): <NEW_LINE> <INDENT> print('run partition: data shape={0}, smallk={1}, largek={2}'.format(data.shape, smallk, largek)) <NEW_LINE> genes = uncurl.max_variance_genes(data, nbins=1, frac=1.0) <NEW_LINE> results, ll = method.run(data[genes,:]) <NEW_LINE> w = result... | Very simple recursive partitioning-based state estimation system.
Args:
data
smallk (int): k for each individual clustering
largek (int): k for the whole global clustering | 625941b22c8b7c6e89b3556a |
def updateWeights(self, gradient): <NEW_LINE> <INDENT> if self.adagradG is None: <NEW_LINE> <INDENT> self.adagradG = self.buildEmptyGradient() <NEW_LINE> self.adagradG.dL = np.zeros(self.L.shape) <NEW_LINE> <DEDENT> self.adagradG.dV += gradient.dV * gradient.dV <NEW_LINE> self.adagradG.dW += gradient.dW * gradient... | Update the weights according to the gradient | 625941b2925a0f43d2549c11 |
def doctest_compareDictsHTML_recursive(): <NEW_LINE> <INDENT> pass | Tests for compareDicts
>>> old = dict(a=1, b=dict(x=2, y=5), c=3, d=42, e=dict(x=42))
>>> new = dict(a=1, b=dict(x=3, y=5), d=dict(x=42), e=42, f=dict(x=4))
>>> print(compareDictsHTML(new, old))
<div class="diff">
<div class="diffitem changed">
<strong>b</strong>: dictionary changed:
<div class="diff">
... | 625941b2de87d2750b85fb2c |
def __rshift__(*args, **kwargs): <NEW_LINE> <INDENT> pass | x.__rshift__(y) <==> x>>y | 625941b263b5f9789fde6e84 |
def getselector(self): <NEW_LINE> <INDENT> return self.selector | Returns the selector we are handling. | 625941b23346ee7daa2b2b06 |
def __getitem__(self, index): <NEW_LINE> <INDENT> self._range_check(index) <NEW_LINE> return self.y(index) | if type(index) is slice:
return self._content()[index] | 625941b221bff66bcd6846fc |
def call(self, input_images, input_labels): <NEW_LINE> <INDENT> pass <NEW_LINE> return out | MANN
Args:
input_images: [B, K+1, N, 784] flattened images
labels: [B, K+1, N, N] ground truth labels
Returns:
[B, K+1, N, N] predictions | 625941b2bf627c535bc12f75 |
def filter(self, resource_manager, **params): <NEW_LINE> <INDENT> m = self.resolve(resource_manager.resource_type) <NEW_LINE> parents = resource_manager.get_parent_manager() <NEW_LINE> results = [] <NEW_LINE> for parent in parents.resources(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> vault_url = None <NEW_LINE> if ... | Query a set of resources. | 625941b291f36d47f21ac294 |
def update(self, path): <NEW_LINE> <INDENT> os.system(r'tortoiseproc.exe /command:update /path:"'+path+'" /closeonend:1') | 更新SVN目录,获取最新的文件 | 625941b2adb09d7d5db6c533 |
def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.collection.save(self, *args, **kwargs) | save the document into the db.
`save()` follow the pymongo.collection.save arguments | 625941b23346ee7daa2b2b07 |
def is_zipfile(file): <NEW_LINE> <INDENT> return zipfile.is_zipfile(file) | Wrapper function for detecting if file is a true ZIP archive | 625941b2627d3e7fe0d68bed |
def test_scope_dir_exists(self): <NEW_LINE> <INDENT> self.assertTrue(os.path.isdir(scope_path), scope_path + ' does not exist') | Verify the scope's directory exists here: /home/phablet/.local/share/unity-scopes/SCOPE | 625941b2fff4ab517eb2f1de |
@hook.command(autohelp=False) <NEW_LINE> def reddit(text): <NEW_LINE> <INDENT> id_num = None <NEW_LINE> if text: <NEW_LINE> <INDENT> parts = text.lower().strip().split() <NEW_LINE> if len(parts) > 1: <NEW_LINE> <INDENT> url = base_url.format(parts[0].strip()) <NEW_LINE> try: <NEW_LINE> <INDENT> id_num = int(parts[1]) -... | <subreddit> [n] - gets a random post from <subreddit>, or gets the [n]th post in the subreddit | 625941b29f2886367277a639 |
def pyflakes_report(code): <NEW_LINE> <INDENT> flakes_stdout = StreamList() <NEW_LINE> flakes_stderr = StreamList() <NEW_LINE> rep = pyflakes_reporter.Reporter( flakes_stdout.reset(), flakes_stderr.reset()) <NEW_LINE> pyflakes_api.check(code, filename="kale", reporter=rep) <NEW_LINE> if rep._stderr(): <NEW_LINE> <INDEN... | Inspect code using PyFlakes to detect any 'missing name' report.
Args:
code: A multiline string representing Python code
Returns: a list of names that have been reported missing by Flakes | 625941b2be383301e01b5236 |
def as_json(obj: Union[Dict, JsonObj, List], indent: Optional[str] = ' ', filtr: Callable[[dict], dict] = None, **kwargs) -> str: <NEW_LINE> <INDENT> if isinstance(obj, JsonObj) and '_root' in obj: <NEW_LINE> <INDENT> obj = obj._root <NEW_LINE> <DEDENT> default_processor = obj._default if isinstance(obj, JsonO... | Convert obj to json string representation.
:param obj: pseudo 'self'
:param indent: indent argument to dumps
:param filtr: filter to remove unwanted elements
:param kwargs: other arguments for dumps
:return: JSON formatted string | 625941b2236d856c2ad4457f |
def keyPressEvent(self, QKeyEvent): <NEW_LINE> <INDENT> cursor=self.texts[self.name].textCursor() <NEW_LINE> if QKeyEvent.key() == QtCore.Qt.Key_Return: <NEW_LINE> <INDENT> cursor.select(QtGui.QTextCursor.LineUnderCursor) <NEW_LINE> self.texts[self.name].moveCursor(QtGui.QTextCursor.End, QtGui.QTextCursor.MoveAnchor) <... | Extend the QTextEdit key press event, add routines, then call the original method. | 625941b24a966d76dd550daa |
def get_array_connections( self, references=None, remotes=None, continuation_token=None, filter=None, ids=None, limit=None, offset=None, remote_ids=None, remote_names=None, sort=None, async_req=False, _return_http_data_only=False, _preload_content=True, _request_timeout=None, ): <NEW_LINE> <INDENT> kwargs = dict( conti... | List connected arrays for replication.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids keyword arguments.
remotes (list[FixedReference], optional):
A list of remotes to query for. Overrides remote_ids and remote_names keyword arguments.
c... | 625941b25510c4643540f19a |
def admin(): <NEW_LINE> <INDENT> driver = webdriver.Chrome() <NEW_LINE> driver.get(hotel_url) <NEW_LINE> driver.maximize_window() <NEW_LINE> hotel_login(driver) | hotel系统购买操作 | 625941b26e29344779a623b6 |
def ray_x_polygon(r0, rd, poly_verts, pn, tol=1e-6): <NEW_LINE> <INDENT> t = ray_x_plane(r0, rd, poly_verts[0], pn, tol) <NEW_LINE> ri = r0 + rd*t <NEW_LINE> is_inside = point_in_polygon(ri, poly_verts, pn) <NEW_LINE> return ri, is_inside | Parameters
----------
r0, rd, pn, tol: check function `ray_x_plane()` parameters.
poly_verts: check function `point_in_polygon()` parameters.
Returns
-------
A 2-tuple where the first element represents the coordinates of the
intersection point, and the second one a boolean set to True if the ray
intersects th... | 625941b24e696a04525c91f5 |
@app.route("/users/logs", methods=['GET']) <NEW_LINE> @log_user_action <NEW_LINE> @login_required <NEW_LINE> @update_user_token <NEW_LINE> def list_all_user_actions(): <NEW_LINE> <INDENT> data = _get_request_args() <NEW_LINE> _filter_timestamp(data) <NEW_LINE> return utils.make_json_response( 200, user_log_api.list_act... | List all users actions. | 625941b28c0ade5d55d3e75f |
def gen_bot_name(): <NEW_LINE> <INDENT> name = choice(letters) + randint(0,10) + choice(letters) + randint(0,10) <NEW_LINE> if name not in robot_names: <NEW_LINE> <INDENT> robot_names += name <NEW_LINE> return name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return gen_bot_name() | returns unique robot__name | 625941b24527f215b584c204 |
@secure_required <NEW_LINE> @permission_required_or_403('change_profile', (get_profile_model(), 'user__username', 'username')) <NEW_LINE> def profile_edit(request, username, edit_profile_form=EditProfileForm, template_name='userena/profile_form.html', success_url=None, extra_context=None): <NEW_LINE> <INDENT> user = ge... | Edit profile.
Edits a profile selected by the supplied username. First checks
permissions if the user is allowed to edit this profile, if denied will
show a 404. When the profile is succesfully edited will redirect to
``success_url``.
:param username:
Username of the user which profile should be edited.
:param e... | 625941b26aa9bd52df036b42 |
def setup(): <NEW_LINE> <INDENT> size(800, 600) <NEW_LINE> global production <NEW_LINE> production = csgrammar.repeat(5, AXIOM, RULES, IGNORE) <NEW_LINE> fill(0, 200, 0) <NEW_LINE> noStroke() | processing setup | 625941b263b5f9789fde6e85 |
def ampsToXML(self,amps=None,save=True): <NEW_LINE> <INDENT> codes = amps['code'].unique() <NEW_LINE> psacols = amps.columns[amps.columns.str.startswith('psa')].tolist() <NEW_LINE> imts = ['pga','pgv'] + psacols <NEW_LINE> shakemap_data_tag = Tag('shakemap-data') <NEW_LINE> atts = {'id':self._id, 'lat':self._origin['la... | Save a DataFrame of peak amplitudes to a ShakeMap compatible XML station data file.
:param amps:
DataFrame containing the following columns:
- netid
- name
- code
- loc
- lat
- lon
- dist
- source
- insttype
- commtype
- intensity
and then a number of intensity measure... | 625941b250485f2cf553cb38 |
def import_third_party(modname): <NEW_LINE> <INDENT> with sys_modules_saved(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return importlib.import_module(modname) <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> return None | Import a third-party module we need, but might not be installed.
This also cleans out the module after the import, so that coverage won't
appear to have imported it. This lets the third party use coverage for
their own tests.
Arguments:
modname (str): the name of the module to import.
Returns:
The imported ... | 625941b2b7558d58953c4cc3 |
def check_managed_changes( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, keep_mode=False, seuser=None, serole=None, setype=None, serange=None, verify_ssl=True, **kwargs ): <NEW_LINE> <INDENT> source, source_hash = source_li... | Return a dictionary of what changes need to be made for a file
.. versionchanged:: 3001
selinux attributes added
verify_ssl
If ``False``, remote https file sources (``https://``) and source_hash
will not attempt to validate the servers certificate. Default is True.
.. versionadded:: 3002
CLI Exampl... | 625941b20fa83653e4656d65 |
@node.commandWrap <NEW_LINE> def NodeEditorToggleCreateNodePane(*args, **kwargs): <NEW_LINE> <INDENT> u <NEW_LINE> return cmds.NodeEditorToggleCreateNodePane(*args, **kwargs) | :rtype: list|str|basestring|DagNode|AttrObject|ArrayAttrObject|Components1Base | 625941b2f548e778e58cd31b |
def __setitem__(self, key, value): <NEW_LINE> <INDENT> self.add(key, value) | Overrides `[]` operator behavior
:param key: the CachedEntry's key
:type key: str
:param value: the CachedEntry's value
:type value: object | 625941b255399d3f05588455 |
def run(): <NEW_LINE> <INDENT> customized() | Main function of the example. Runs each demo and then exits. | 625941b2e5267d203edcda42 |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api_credit_app.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 y... | Run administrative tasks. | 625941b2de87d2750b85fb2d |
def trainClassifier(self): <NEW_LINE> <INDENT> features = self.updateHumanStatsAndGetFeatures() <NEW_LINE> features.extend( self.updateBotStatsAndGetFeatures() ) <NEW_LINE> category = self.validGuesses[self.playerOneGuess] <NEW_LINE> self.classifier.train(features, category) | Send features and category to the classifier.
Called by self.playGame() | 625941b245492302aab5e05f |
def get_xy_data(self, new_value): <NEW_LINE> <INDENT> if new_value is None: <NEW_LINE> <INDENT> return None, None, None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> data = getattr(self.module, '_' + self.attribute_name + '_object').data <NEW_LINE> name = getattr( self.module, '_' + self.attribute_name + '_object').para... | helper function to extract xy data from a curve object | 625941b260cbc95b062c62e9 |
def se_from_ui(p, lower, upper, method, confidence=0.95): <NEW_LINE> <INDENT> assert method in ['ratio', 'non-ratio'], "must specify whether to" "use the ratio method" <NEW_LINE> quantile = 1 - (1 - confidence) / 2 <NEW_LINE> if method == 'ratio': <NEW_LINE> <INDENT> n = np.log(upper) - np.log(lower) <NEW_LINE> ... | Calculates standard error from the uncertainty interval | 625941b2004d5f362079a0d9 |
def walk_stack(f): <NEW_LINE> <INDENT> if f is None: <NEW_LINE> <INDENT> f = sys._getframe().f_back.f_back <NEW_LINE> <DEDENT> while f is not None: <NEW_LINE> <INDENT> yield f, f.f_lineno <NEW_LINE> f = f.f_back | Walk a stack yielding the frame and line number for each frame.
This will follow f.f_back from the given frame. If no frame is given, the
current stack is used. Usually used with StackSummary.extract. | 625941b2d164cc6175782aed |
def ensure_jupyterhub_package(prefix): <NEW_LINE> <INDENT> conda.ensure_pip_packages(prefix, [ 'jupyterhub==0.9.4', 'jupyterhub-dummyauthenticator==0.3.1', 'jupyterhub-systemdspawner==0.11', 'jupyterhub-firstuseauthenticator==0.11', 'jupyterhub-ldapauthenticator==1.2.2', 'oauthenticator==0.8.0', ]) <NEW_LINE> traefik.e... | Install JupyterHub into our conda environment if needed.
We install all python packages from PyPI as much as possible in the
hub environment. A lot of spawners & authenticators do not have conda-forge
packages, but do have pip packages. Keeping all python packages in the
hub environment be installed with pip prevents ... | 625941b29b70327d1c4e0b74 |
def setup_method(self, method): <NEW_LINE> <INDENT> sparkConf = create_spark_conf().setMaster("local[4]").setAppName("test model") <NEW_LINE> self.sc = get_spark_context(sparkConf) <NEW_LINE> init_engine() | setup any state tied to the execution of the given method in a
class. setup_method is invoked for every test method of a class. | 625941b282261d6c526ab243 |
def isValid(self): <NEW_LINE> <INDENT> errors = {} <NEW_LINE> self.Schema().validate(self, self.REQUEST, errors, 1, 1) <NEW_LINE> if errors: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True | Check if the response is valid.
Meaning: a response has been filled in. | 625941b2f7d966606f6a9da9 |
def test_add_multiple_effects(self): <NEW_LINE> <INDENT> effect_1 = (EffectBuilder() .with_effect_name('spell') .build()) <NEW_LINE> effect_2 = (EffectBuilder() .with_effect_name('curse') .build()) <NEW_LINE> self.character.add_effect(effect_1) <NEW_LINE> self.character.add_effect(effect_2) <NEW_LINE> assert_that(self.... | It should be possible to add multiple effects of different type | 625941b299cbb53fe6792988 |
def execute(self, db_name=None, sql='', close_conn=True): <NEW_LINE> <INDENT> execute_result = ReviewSet(full_sql=sql) <NEW_LINE> conn = self.get_connection(db_name=db_name) <NEW_LINE> cursor = conn.cursor() <NEW_LINE> split_reg = re.compile('^GO$', re.I | re.M) <NEW_LINE> sql = re.split(split_reg, sql, 0) <NEW_LINE> s... | 执行sql语句 返回 Review set | 625941b2d58c6744b4257a03 |
def get_ip_serialuuids(user_org, user_end=None, ips=None, status=None): <NEW_LINE> <INDENT> db_conn = PostgreSQLDB(CONFIG.PostgreSQLDB.host, CONFIG.PostgreSQLDB.port, CONFIG.PostgreSQLDB.user, CONFIG.PostgreSQLDB.pwd, CONFIG.PostgreSQLDB.dbname) <NEW_LINE> sqls = [] <NEW_LINE> sql = "select '['||WM_CONCAT(''''||serialn... | :param user_org:一级用户ID
:param user_end: 二级用户ID
:param ips: 字符串,IP记录,多个IP记录之间用逗号隔开
:param status: IP状态,open--在用,close--已关闭
:return: T_IP表的serialuuids组成的列表以及对应的字符串,ip组成的列表以及对应的字符串
:返回示例:['a61068ae-782e-11e7-9eb8-000ec6c6d278', 'f97637c7-798c-11e7-a854-f45c899a7eaf'] "a61068ae-782e-11e7-9eb8-000ec6c6d278","f97637c7-798c-1... | 625941b2f9cc0f698b1403a7 |
def make_history(self, session): <NEW_LINE> <INDENT> self.create_transaction_log_entry(session) <NEW_LINE> self.create_history_objects(session) <NEW_LINE> self.create_association_versions(session) <NEW_LINE> self.create_transaction_changes_entries(session) <NEW_LINE> self.create_transaction_meta_entries(session) <NEW_L... | Create transaction, transaction changes records, history objects.
:param session: SQLAlchemy session object | 625941b2d268445f265b4c15 |
def normalize_env(env, keys, force=False): <NEW_LINE> <INDENT> normenv = {} <NEW_LINE> if env: <NEW_LINE> <INDENT> for k in list(env.keys()): <NEW_LINE> <INDENT> normenv[k] = copy.deepcopy(env[k]) <NEW_LINE> <DEDENT> for k in keys: <NEW_LINE> <INDENT> if k in os.environ and (force or not k in normenv): <NEW_LINE> <INDE... | Given a dictionary representing a shell environment, add the variables
from os.environ needed for the processing of .bat files; the keys are
controlled by the keys argument.
It also makes sure the environment values are correctly encoded.
If force=True, then all of the key values that exist are copied
into the return... | 625941b2ff9c53063f47bf9f |
def check_destination_path(self, path, mkdir_destination=None, ssh=None): <NEW_LINE> <INDENT> ssh = ssh if ssh else self.ssh <NEW_LINE> if path[0:1] == b'~' or path[0:1] == '~': <NEW_LINE> <INDENT> _, stdout, _ = ssh.exec_command("pwd") <NEW_LINE> path = join(stdout.readlines()[0].strip(), path.replace('~/', '')) <NEW_... | Returns the destination_dir or raises an Exception if destination_dir does
not exist on the remote host.
@param path: path on remote host
@type path: byte or str
@param mkdir_destination: if True attempts to create the remote folder.
@type mkdir_destination: boolean
@raise FileNotFoundError: if path does not exist an... | 625941b256ac1b37e6263f83 |
def _get_state(ipaclient, idnsname): <NEW_LINE> <INDENT> current = set() <NEW_LINE> result = ipaclient.get_dns_record(idnsname) <NEW_LINE> for record in result.get('srvrecord', []): <NEW_LINE> <INDENT> _w, _p, port, host = record.split() <NEW_LINE> current.add('{}:{}'.format(host.rstrip('.'), port)) <NEW_LINE> <DEDENT>... | Return set of currently defined SRV records. | 625941b216aa5153ce36221b |
def cast(*args): <NEW_LINE> <INDENT> return _itkCastImageFilterPython.itkCastImageFilterID2IUL2_cast(*args) | cast(itkLightObject obj) -> itkCastImageFilterID2IUL2 | 625941b2462c4b4f79d1d470 |
def testSplitNamespacesPresent(self): <NEW_LINE> <INDENT> TestEntity().put() <NEW_LINE> for i in range(5): <NEW_LINE> <INDENT> namespace_manager.set_namespace(str(i)) <NEW_LINE> TestEntity().put() <NEW_LINE> <DEDENT> namespace_manager.set_namespace(None) <NEW_LINE> readers = input_readers.NamespaceInputReader.split_inp... | Test reader with multiple namespaces present. | 625941b266673b3332b91e37 |
def stop(self): <NEW_LINE> <INDENT> self.times.append(time.time() - self.tik) <NEW_LINE> return self.times[-1] | 停止计时器并将时间记录在列表中 | 625941b24d74a7450ccd3f66 |
def is_numeric(self): <NEW_LINE> <INDENT> return javabridge.call(self.jobject, "isNumeric", "()Z") | Returns whether the attribute is a numeric one (date or numeric).
:return: whether numeric attribute
:rtype: bool | 625941b2925a0f43d2549c13 |
@api.route('/issues/search/<issue_category>') <NEW_LINE> def get_category_from_search(issue_category): <NEW_LINE> <INDENT> category_list = ['contactready', 'needscontact', 'needsdiagnosis', 'sitewait'] <NEW_LINE> params = request.args.copy() <NEW_LINE> if issue_category in category_list: <NEW_LINE> <INDENT> query_strin... | XHR endpoint to get issues categories from GitHub's Search API.
It's also possible to use /issues/category/<issue_category> for a category
that maps to a label. This uses the Issues API, which is less costly than
the Search API. | 625941b2de87d2750b85fb2e |
def test_revise_section_with_rules_revise_with_rules(self): <NEW_LINE> <INDENT> pass | Test case for revise_section_with_rules_revise_with_rules
Update an Existing Section with Rules # noqa: E501 | 625941b299fddb7c1c9de13c |
@method(process_properties, 'export') <NEW_LINE> def _(row: list) -> list: <NEW_LINE> <INDENT> properties = get_properties(shlex.split(row[4])) <NEW_LINE> return [ *row[:2], *export_split(row[2]), row[3], properties['rw'], properties['root'], properties['access'] ] | Extracts rw, root and access properties for an export row
:param row:
:return: | 625941b291f36d47f21ac296 |
def __init__(self, *args): <NEW_LINE> <INDENT> _vnl_vector_refPython.vnl_vector_ref_vcl_complexD_swiginit(self,_vnl_vector_refPython.new_vnl_vector_ref_vcl_complexD(*args)) | __init__(self, unsigned int n, vcl_complexD space) -> vnl_vector_ref_vcl_complexD
__init__(self, vnl_vector_ref_vcl_complexD v) -> vnl_vector_ref_vcl_complexD | 625941b2bf627c535bc12f77 |
@parser_node_rule <NEW_LINE> def p_NTYPE_GT_EXPR_node(psr_val): <NEW_LINE> <INDENT> pass | node : NODE NTYPE_GT_EXPR TYPE_ATTR OP0_ATTR OP1_ATTR attr_list | 625941b2e1aae11d1e749a58 |
def generate_probability_key(prob_table, length, encoding, message): <NEW_LINE> <INDENT> pass | Given a probability and encoding along with a message generate a random key
that follows the bias provided
TODO:
Implement when I have time this weekend | 625941b2cad5886f8bd26d83 |
def get(self, request, provider_uuid, identity_uuid, machine_id): <NEW_LINE> <INDENT> core_machine = ProviderMachine.objects.filter( provider__uuid=provider_uuid, identifier=machine_id) <NEW_LINE> if not core_machine: <NEW_LINE> <INDENT> return failure_response( status.HTTP_400_BAD_REQUEST, "Machine id %s does not exis... | Lookup the machine information
(Lookup using the given provider/identity)
Update on server (If applicable) | 625941b2ab23a570cc24ff28 |
def test_RunPrivmsgOfOneWord(self): <NEW_LINE> <INDENT> if 'privmsg' in self.module.listen: <NEW_LINE> <INDENT> self.mock_privmsg_data['msg'] = 'word' <NEW_LINE> runnable = self.run_module(self.module, self.mock_privmsg_data) <NEW_LINE> if not runnable[0]: <NEW_LINE> <INDENT> self.assertTrue(False,runnable[1]) | Run test [listen: privmsg, words: one] | 625941b2507cdc57c6306a73 |
@main.route('/', methods=['GET', 'POST']) <NEW_LINE> def index(): <NEW_LINE> <INDENT> global room_dict <NEW_LINE> global i <NEW_LINE> form = LoginForm() <NEW_LINE> if form.validate_on_submit(): <NEW_LINE> <INDENT> session['name'] = form.name.data <NEW_LINE> session['room'] = i <NEW_LINE> if str(i) not in room_dict.keys... | Login form to enter a room. | 625941b2fb3f5b602dac3438 |
def Reposition(self, slice_data): <NEW_LINE> <INDENT> ren = slice_data.renderer <NEW_LINE> size = ren.GetSize() <NEW_LINE> ren.ResetCamera() <NEW_LINE> ren.GetActiveCamera().Zoom(1.0) <NEW_LINE> self.interactor.Render() | Based on code of method Zoom in the
vtkInteractorStyleRubberBandZoom, the of
vtk 5.4.3 | 625941b25e10d32532c5ecd1 |
def getSkinWeightsMap(*skins): <NEW_LINE> <INDENT> skinWeights = {} <NEW_LINE> for skin in skins: <NEW_LINE> <INDENT> weights = getSkinWeights(skin) <NEW_LINE> skinWeights[skin.nodeName()] = weights <NEW_LINE> <DEDENT> return skinWeights | Return a dict containing weights for multiple skin clusters
Args:
*skins (PyNode): One or more skin cluster nodes
Returns:
A dict of {skinName: weights} for all the skin clusters | 625941b2462c4b4f79d1d471 |
def _handle_password_hashes(self, obj: ListenerUserAddModifyObject) -> Dict[str, Any]: <NEW_LINE> <INDENT> if ( self.school_authority.plugin_configs[self.plugin_name].get("sync_password_hashes", False) and obj.user_passwords ): <NEW_LINE> <INDENT> hashes = obj.user_passwords.dict_krb5_key_base64_encoded() <NEW_LINE> re... | If password hashed should be sent, return them here. | 625941b215baa723493c3d13 |
def add(self, *words): <NEW_LINE> <INDENT> words = get_words(words) <NEW_LINE> with open(self._wordfile, 'r', encoding=self._encoding) as file: <NEW_LINE> <INDENT> lines = file.readlines() <NEW_LINE> <DEDENT> lines = set(i.strip() for i in lines) | words <NEW_LINE> if self._case: <NEW_LINE> <INDENT> self._words |= word... | Adds one or more words to the Checker and it's word file. | 625941b2091ae35668666d08 |
def __call__(self, service_name, version=None): <NEW_LINE> <INDENT> kw = {} <NEW_LINE> if version: <NEW_LINE> <INDENT> kw['version'] = version <NEW_LINE> <DEDENT> return self._connection.get(api_path('service', service_name, **kw)) | Load the configuration for a given service
Required:
service_name: Name of the service to get the info
Optional:
version : Specific version of the service to get
Throws a Client exception if the service does not exist. | 625941b28a43f66fc4b53e13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.