code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def product_of_array_except_itself(nums): <NEW_LINE> <INDENT> p = 1 <NEW_LINE> output = [] <NEW_LINE> for i in xrange(0, len(nums)): <NEW_LINE> <INDENT> output.append(p) <NEW_LINE> p = p * nums[i] <NEW_LINE> <DEDENT> p = 1 <NEW_LINE> for i in xrange(len(nums)-1,-1,-1): <NEW_LINE> <INDENT> output[i] = output[i] * p <NEW...
https://leetcode.com/problems/product-of-array-except-self/description/ 可以用数组预处理的方式来计算,也可以节省空间,第一轮处理 p: 1 n1 n1n2 n1n2n3 output: 1 n1 n1n2 n1n2n3 第二轮,逆序遍历 output: 1 n1 n1n2 n1n2n3 p: n2n3n4 n3n4 n4 1 output: n2n3n4 n1n3n4 n1n2n4 n1n2n3
625941f221a7993f00bc82d1
def get_menu_item(item_id): <NEW_LINE> <INDENT> item = session.query(MenuItem).filter_by(id=item_id).one() <NEW_LINE> return item
Retrieve all records from the Restaurant table
625941f20383005118ecfbb6
def print_directory_contents(sPath): <NEW_LINE> <INDENT> for childpath in os.listdir(sPath): <NEW_LINE> <INDENT> childpath = os.path.join(sPath,childpath) <NEW_LINE> if os.path.isdir(childpath): <NEW_LINE> <INDENT> print_directory_contents(childpath) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(childpath)
接受文件夹的名称作为输入参数, 返回该文件夹中文件的路径, 以及其包含文件夹中文件的路径。 :param sPath: :return:
625941f2566aa707497f4b35
def get_uploads(self, field_name=None): <NEW_LINE> <INDENT> if self.__uploads is None: <NEW_LINE> <INDENT> self.__uploads = {} <NEW_LINE> for key, value in self.controller.request.params.items(): <NEW_LINE> <INDENT> if isinstance(value, cgi.FieldStorage): <NEW_LINE> <INDENT> if 'blob-key' in value.type_options: <NEW_LI...
Get uploads sent to this controller. Args: field_name: Only select uploads that were sent as a specific field. Returns: A list of BlobInfo records corresponding to each upload. Empty list if there are no blob-info records for field_name.
625941f2e76e3b2f99f3add7
def minimumSwaps(arr): <NEW_LINE> <INDENT> annotated = [*enumerate(arr)] <NEW_LINE> annotated.sort(key = lambda it: it[1]) <NEW_LINE> count = 0 <NEW_LINE> i = 0 <NEW_LINE> while i < len(arr): <NEW_LINE> <INDENT> if annotated[i][0] == i: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> continue <NEW_LINE> <DEDENT> swap(annotated, ...
Final Solution based on enumarated array
625941f2e64d504609d74e15
@task <NEW_LINE> def deploy(git_ref, upgrade=False): <NEW_LINE> <INDENT> require('hosts', 'user', 'group', 'site_dir', 'django_settings') <NEW_LINE> message = white('Creating git archive from {0}'.format(git_ref), bold=True) <NEW_LINE> with cmd_msg(message): <NEW_LINE> <INDENT> repo = ulocal( 'basename `git rev-parse -...
Deploy the code of the given git reference to the previously selected environment. Pass ``upgrade=True`` to upgrade the versions of the already installed project requirements (with pip).
625941f263f4b57ef00016dd
def press_eight(): <NEW_LINE> <INDENT> tempnum = answer.get() <NEW_LINE> tempnum = tempnum + "8" <NEW_LINE> answer.set(tempnum)
Gets the current numbers in the entry field and adds the number eight to it when pressed.
625941f27d43ff24873a327b
def calculate_prody_normal_modes(self): <NEW_LINE> <INDENT> prody_molecule, chimera2prody = convert_chimera_molecule_to_prody(self.molecule) <NEW_LINE> modes = prody_modes(prody_molecule, self.max_modes, GROUPERS.get(self.group_by, self.group_by), **self.group_by_options) <NEW_LINE> samples = prody.sampleModes(modes=mo...
calculate normal modes, creates a diccionary between chimera and prody indices and calculate n_confs number of configurations using this modes
625941f2adb09d7d5db6cd61
def dump(self, filename=None, directory=None): <NEW_LINE> <INDENT> util.dump(self, filename, directory)
Write coverage to a file or stdout.
625941f2091ae3566866752a
def on_button_openwith_clicked(self, *_): <NEW_LINE> <INDENT> fname = self._app.save_and_return_path() <NEW_LINE> appchooser = OpenWithDialog() <NEW_LINE> self._view.run_dialog(appchooser) <NEW_LINE> appinfo = appchooser.appinfo <NEW_LINE> if appinfo is not None: <NEW_LINE> <INDENT> if appinfo.launch_uris(["file://"+fn...
Handle the "open with" button
625941f2ab23a570cc25075d
def season_exists(self, title, season): <NEW_LINE> <INDENT> title = re.sub(r'[?|$|!|:|#]', r'', title) <NEW_LINE> if self.show_exists(title) is False: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> show_entry = self.db[self.series_label][title] <NEW_LINE> return season in show_entry['seasons']
Checks if a season is present in the local DB Parameters ---------- title : :obj:`str` Title of the show season : :obj:`int` Season sequence number Returns ------- bool Season of show exists in DB
625941f24f6381625f115010
def get_albedo(self, wavelength): <NEW_LINE> <INDENT> albedo = self.mie[float_round(wavelength)].get_albedo(self.reff, self.veff) <NEW_LINE> return albedo
Get the optical single scattering albedo from microphysics and Mie scattering model for a given wavelength. Parameters ---------- wavelength: float Wavelength in microns. Returns ------- albedo: shdom.GridData A GridData with the optical single scattering albedo Notes ----- A Mie scattering model must be def...
625941f21b99ca400220b08a
def rmdir(self, path): <NEW_LINE> <INDENT> path = self._adjust_cwd(path) <NEW_LINE> self._log(DEBUG, 'rmdir({!r})'.format(path)) <NEW_LINE> self._request(CMD_RMDIR, path)
Remove the folder named ``path``. :param str path: name of the folder to remove
625941f2d18da76e23532ab4
def get_function_definition(self, fct_type, final=True, language=C_Code, arg_list=None): <NEW_LINE> <INDENT> return self.get_function_declaration(fct_type, final, language, arg_list)
C function definition prolog is the same as the function declaration
625941f24f6381625f115011
def main(): <NEW_LINE> <INDENT> pass
You should write your code for this program in this function. Make sure to delete the 'pass' line before starting to write your own code. You should also delete this comment and replace it with a better, more descriptive one.
625941f2a4f1c619b28b0600
def pasa_pasa(numeros): <NEW_LINE> <INDENT> a, b = numeros <NEW_LINE> b = int( str(b) + str(a % 10) ) <NEW_LINE> a = a // 10 <NEW_LINE> return [a, b]
Suprime la ult. cifra del primer num y lo añade al final del segundo Args: numeros -> List()
625941f2ec188e330fd5ad68
def make_daily(pgw_signal,nceptime): <NEW_LINE> <INDENT> f=interp1d(months_mid_doy,pgw_signal,axis=0) <NEW_LINE> return f(nceptime)
convert monthly data to daily for a given ncep year Applies a bilinear interpolation that wraps around the year (e.g. Jan 1st is interpolated between Jan. and Dec. means)
625941f27047854f462a19d8
def parse_date(self, value): <NEW_LINE> <INDENT> if isinstance(value, str): <NEW_LINE> <INDENT> return self.str2date(value) <NEW_LINE> <DEDENT> elif isinstance(value, int): <NEW_LINE> <INDENT> return date.fromordinal(value) <NEW_LINE> <DEDENT> elif isinstance(value, datetime): <NEW_LINE> <INDENT> return value.date() <N...
A lazy method to parse anything to date. Usage:: >>> from weatherlab.lib.timelib.timewrapper import timewrapper >>> from datetime import datetime >>> timewrapper.parse_date("12/25/1985") datetime.date(1985, 12, 25) >>> timewrapper.parse_date(725000) datetime.date(1985, 12, 25) >>> timewrap...
625941f2adb09d7d5db6cd62
def parse_option_custom_entry(entry: Custom, options: FavaOptions) -> None: <NEW_LINE> <INDENT> key = entry.values[0].value.replace("-", "_") <NEW_LINE> assert key in All_OPTS, f"unknown option `{key}`" <NEW_LINE> if key == "default_file": <NEW_LINE> <INDENT> options.default_file = entry.meta["filename"] <NEW_LINE> ret...
Parse a single custom fava-option entry and set option accordingly.
625941f2d268445f265b5445
def interface_hundredgigabitethernet_ip_icmp_unreachable(**kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> interface = ET.SubElement(config, "interface", xmlns="urn:brocade.com:mgmt:brocade-interface") <NEW_LINE> if kwargs.pop('delete_interface', False) is True: <NEW_LINE> <INDENT> delete_interfac...
Auto Generated Code
625941f2379a373c97cfb11d
def buttons_mouse_over_internal(window): <NEW_LINE> <INDENT> window.reset_mouse_over_flags() <NEW_LINE> if not window.is_visible: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if adjusted_mouse_rect_collision(window, window.border_rect): <NEW_LINE> <INDENT> window.m_border_rect = True <NEW_LINE> if window.can_be_min...
Checks if mouse is over any window part and if the part is clicked If a mouse click registers, posts an event that pywindowframes caught the click
625941f2b545ff76a89143ec
def _add_gradient_scope(track_blob_names, ops): <NEW_LINE> <INDENT> def f(name): <NEW_LINE> <INDENT> new_name = name <NEW_LINE> if '_grad' in name: <NEW_LINE> <INDENT> new_name = 'Gradients/{}'.format(new_name.replace('_grad','')) <NEW_LINE> <DEDENT> if '_momentum' in name: <NEW_LINE> <INDENT> new_name = 'Momentum/{}'....
Separate out gradient and momentum for names.
625941f257b8e32f52483a75
def stopLogger(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> global loggingService <NEW_LINE> print("stopping Graphyne Internal Logging Service") <NEW_LINE> loggingService.join(30.0) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass
Stop the internal logging service. The internal logging service is a seperate thread.
625941f2f8510a7c17cf9cd7
def hasBuyBullTrigger(self, recentHistory): <NEW_LINE> <INDENT> predictorValues = recentHistory.getValues("btc") <NEW_LINE> followerValues = recentHistory.getValues("bull") <NEW_LINE> triggered = predictorValues[4] - predictorValues[3] > 0.0012 * predictorValues[3] and followerValues[0] == followerValues[4] ...
Check whether the bullish buying condition has triggered.
625941f2f548e778e58cdb56
def update(j, parameters, deriv, iteration, mprev, vprev): <NEW_LINE> <INDENT> mnew = beta1 * mprev + (1 - beta1) * deriv <NEW_LINE> vnew = beta2 * vprev + (1 - beta2) * deriv**2 <NEW_LINE> mhat = mnew / (1 - beta1**iteration) <NEW_LINE> vhat = vnew / (1 - beta2**iteration) <NEW_LINE> parameters[j] -= self._eta * mhat ...
Updates the jth parameter according to the adaptive rule in the Adam optimizer [TODO: add citation to Adam optimizer paper] Args: j : int Index of parameter to update parameters : list Values of parameters. deriv : float Numerical value of the derivative of the jth parameter evaluate...
625941f24527f215b584ca27
def add_exercise(self, exercise, number_of_sets, target_weight): <NEW_LINE> <INDENT> pass
Add an exercise to this workout.
625941f229b78933be1e5c7b
def test_info_version_calls(): <NEW_LINE> <INDENT> cmd = ["scram", "--version"] <NEW_LINE> assert call(cmd) == 0
Test version information.
625941f2293b9510aa2c3866
def __init__(self, message=None, reason=None): <NEW_LINE> <INDENT> self.__discriminator_value = "DOCUMENT_ERROR" <NEW_LINE> self.object_type = self.__discriminator_value <NEW_LINE> super(DocumentRuntimeError, self).__init__(object_type=self.__discriminator_value, message=message) <NEW_LINE> self.reason = reason
This error type occurs when the cloud fails to render due to an incorrect or malformed document or data sources. :param message: A human-readable description of the error. :type message: (optional) str :param reason: :type reason: (optional) ask_sdk_model.interfaces.alexa.presentation.apla.document_error_reason.Docum...
625941f24d74a7450ccd479c
def flush(self): <NEW_LINE> <INDENT> counter = 0 <NEW_LINE> logging.info('LENGTH OF TEMP EDGES: %d', len(self.temp_edges)) <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> recipient, talk = self.temp_edges.popitem() <NEW_LINE> rec_id = self.nodes.setdefault(recipient, len(self.nodes)) <NEW_LINE> for ...
This function assumes that all edges directed to the same node are already in self.temp_edges. You can't add other edges to these nodes after calling flush(). For example you can call cumulate_edge twice with the same user, but in the meanwhile you can't call flush()
625941f2925a0f43d254a453
def pre_nms(params, cls_outputs, box_outputs, topk=True): <NEW_LINE> <INDENT> eval_anchors = anchors.Anchors(params['min_level'], params['max_level'], params['num_scales'], params['aspect_ratios'], params['anchor_scale'], params['image_size']) <NEW_LINE> cls_outputs, box_outputs = merge_class_box_level_outputs( params,...
Detection post processing before nms. It takes the multi-level class and box predictions from network, merge them into unified tensors, and compute boxes, scores, and classes. Args: params: a dict of parameters. cls_outputs: a list of tensors for classes, each tensor denotes a level of logits with shape [N, H...
625941f299cbb53fe67931bb
def field_flattening(image, filter_type = "gaussian", ksize = 31, sigma = 101): <NEW_LINE> <INDENT> if filter_type == "gaussian": <NEW_LINE> <INDENT> blurred_image = GaussianBlur(image.astype(np.uint8), ksize = (ksize, ksize), sigmaX = sigma) <NEW_LINE> <DEDENT> if filter_type == "median": <NEW_LINE> <INDENT> blurred_i...
Function that will field flatten a single channel image
625941f210dbd63aa1bd3178
def testOpenCloseInode(self): <NEW_LINE> <INDENT> self._TestOpenCloseInode(self._vhdi_path_spec)
Test the open and close functionality using an inode.
625941f2fb3f5b602dac3c70
def download_lectures(downloader, class_name, sections, file_formats, overwrite=False, skip_download=False, section_filter=None, lecture_filter=None, resource_filter=None, path='', verbose_dirs=False, preview=False, combined_section_lectures_nums=False, hooks=None, playlist=False, intact_fnames=False ): <NEW_LINE> <IND...
Downloads lecture resources described by sections. Returns True if the class appears completed.
625941f2ab23a570cc25075e
def EmailGen(tran): <NEW_LINE> <INDENT> borrower_name = tran.borrower.name <NEW_LINE> book_title = tran.book.name <NEW_LINE> due_date = str(tran.cal_due_date()) <NEW_LINE> from_email = os.environ.get('MY_GMAIL_ADDRESS','') <NEW_LINE> to = tran.borrower.email <NEW_LINE> if tran.is_overdue(): <NEW_LINE> <INDENT> subject=...
Returns an EmailMessage object for a particular transaction.
625941f2627d3e7fe0d69428
def scale_stream(root, prompt, row, default='', **kwargs): <NEW_LINE> <INDENT> assert isinstance(root, tk.Tk) <NEW_LINE> assert isinstance(prompt, rx.Observable) <NEW_LINE> assert isinstance(row, int) <NEW_LINE> string_var = tk.StringVar() <NEW_LINE> string_var.set(default) <NEW_LINE> subject = rx.subjects.ReplaySubjec...
Produce a stream of slider values on a scale root - a Tk root prompt - an observable of string values row - the row of the tk window to place the scale
625941f27047854f462a19d9
def count(self): <NEW_LINE> <INDENT> if hasattr(self, '_response'): <NEW_LINE> <INDENT> return self._response.hits.total <NEW_LINE> <DEDENT> es = connections.get_connection(self._using) <NEW_LINE> d = self.to_dict(count=True) <NEW_LINE> return es.count( index=self._index, doc_type=self._get_doc_type(), body=d, **self._...
Return the number of hits matching the query and filters. Note that only the actual number is returned.
625941f256b00c62f0f14c33
def do_exit(self, arg): <NEW_LINE> <INDENT> if arg: <NEW_LINE> <INDENT> raise CmdSyntaxError('Unknown argument %s' % arg) <NEW_LINE> <DEDENT> self.pprint('') <NEW_LINE> return True
Exits from the application. Syntax: exit|quit The 'exit' command is used to terminate the application. You can also use the standard UNIX Ctrl+D end of file sequence to quit.
625941f2e5267d203edce26b
def _socket_connected(self): <NEW_LINE> <INDENT> self.statusChanged.emit(self.status_connected, None) <NEW_LINE> if self._password: <NEW_LINE> <INDENT> self.send_to_weechat('\n'.join(_PROTO_INIT_CMD + _PROTO_SYNC_CMDS) % {'password': str(self._password), 'lines': self._lines}) <NEW_LINE> <DEDENT> self._hotlist_timer.st...
Slot: socket connected.
625941f2fff4ab517eb2fa16
def value(self, r: float) -> Point: <NEW_LINE> <INDENT> return self.p + r * self.v
Returns point for a certain value of r
625941f256b00c62f0f14c34
def connect(arguments, **keywords): <NEW_LINE> <INDENT> if arguments.no_verify: <NEW_LINE> <INDENT> keywords["verify"] = False <NEW_LINE> <DEDENT> elif arguments.verify is not None: <NEW_LINE> <INDENT> keywords["verify"] = arguments.verify <NEW_LINE> <DEDENT> return Connection(auth=(arguments.user, arguments.password),...
Factory function for client connections that takes an option parser as input. Parameters ---------- arguments: argument parser object, required Parsed command line arguments. keywords: dictionary, optional Additional options to pass to requests. Returns ------- connection: session for submitting requests to Slyc...
625941f2a17c0f6771cbe625
def train(self, X_train, y_train): <NEW_LINE> <INDENT> self.model.fit(X_train, y_train)
Train a specific model on the training data :param X_train: :param y_train: :return:
625941f28a43f66fc4b54634
@api_view(['POST']) <NEW_LINE> def createTransaction(request): <NEW_LINE> <INDENT> pass
Метод не реализован Метод требует авторизации Создает транзакции(займ денег, возврат долга)
625941f2851cf427c661aae0
def find_optimum_freq(freq_list): <NEW_LINE> <INDENT> diff_list = [] <NEW_LINE> for i in freq_list: <NEW_LINE> <INDENT> diff = abs(400.8 - i) <NEW_LINE> diff_list.append(diff) <NEW_LINE> <DEDENT> final_freq_location = diff_list.index(min(diff_list)) <NEW_LINE> final_freq = freq_list[final_freq_location] <NEW_LINE> retu...
This function finds the smallest deviation of final resonant frequency from 400.8 MHz Input -> List of frequencies from each sheet Output -> final resonant frequency closest to 400.8 MHz
625941f2287bf620b61d4036
def fake_emoji_unicode() -> str: <NEW_LINE> <INDENT> return random.choice(emoji_unicodes)
Returns a random unicode emoji's unicode codepoint
625941f23d592f4c4ed1d633
def _store_key(self, obj, interval): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> obj = obj.typeclass <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> dbobj = None <NEW_LINE> try: <NEW_LINE> <INDENT> dbobj = obj.dbobj <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> ...
Tries to create a store_key for the object. Returns a tuple (isdb, store_key) where isdb is a boolean True if obj was a database object, False otherwise.
625941f2eab8aa0e5d26e131
def get_led(self,color): <NEW_LINE> <INDENT> return self.leds[self.rang_color[color]]
retourne la led de couleur 'color'
625941f273bcbd0ca4b2c64c
def get_files(): <NEW_LINE> <INDENT> files = [] <NEW_LINE> for dirpath, dirnames, filenames in os.walk(ROOT): <NEW_LINE> <INDENT> for fname in filenames: <NEW_LINE> <INDENT> if fname.endswith(".html"): <NEW_LINE> <INDENT> path = os.path.join(dirpath, fname) <NEW_LINE> files.append(path) <NEW_LINE> <DEDENT> <DEDENT> <DE...
Gets the list of all hyde blog posts in the given directory.
625941f25f7d997b87175074
def gauss(M, b, d=1e-14): <NEW_LINE> <INDENT> m = len(M) <NEW_LINE> n = len(M[0]) <NEW_LINE> M = [M[q] + [b[q]] for q in range(m)] <NEW_LINE> q = 0 <NEW_LINE> for p in range(m): <NEW_LINE> <INDENT> M, b = rinse(M, d), rinse(b, d) <NEW_LINE> i, j = Rpivot(p, q, M) <NEW_LINE> q = q + 1 <NEW_LINE> M[p], M[i] = M[i], M[p] ...
Solves Mx = b and returns the augmented matrix M|b in reduced row echelon form. M is list of lists, and b is a list.
625941f24428ac0f6e5badce
def p_bool(self, p): <NEW_LINE> <INDENT> p[0] = self._value_class('bool', p[1])
bool : BOOL
625941f231939e2706e4d438
def create_src_dataset(input_dataset, word_vocab_index, word_max_length, word_pad, word_sos, word_eos, word_placeholder_enable, word_feat_enable, subword_vocab_index, subword_max_length, subword_pad, subword_size, subword_feat_enable, char_vocab_index, char_max_length, char_pad, char_feat_enable, num_parallel): <NEW_LI...
create word/subword/char-level dataset for input source data
625941f276e4537e8c351c4f
def process(plugin, context, instance=None, action=None): <NEW_LINE> <INDENT> if issubclass(plugin, (ContextPlugin, InstancePlugin)): <NEW_LINE> <INDENT> result = __explicit_process(plugin, context, instance, action) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = __implicit_process(plugin, context, instance, ac...
Produce a single result from a Plug-in Arguments: plugin(Plugin): Uninstantiated plug-in class context(Context): The current Context instance(Instance, optional): Instance to process action(str): Id of action to process, in place of plug-in. Returns: Dictionary of result
625941f2460517430c39474b
def register_interceptor(self, route: str, action: Callable): <NEW_LINE> <INDENT> if self._endpoint is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> route = self._append_base_route(self.fix_route(route)) <NEW_LINE> self._endpoint.register_interceptor(route, action)
Registers a middleware for a given route in HTTP endpoint. :param route: a command route. Base route will be added to this route :param action: an action function that is called when middleware is invoked.
625941f25fcc89381b1e1c9b
def compile_plan(self): <NEW_LINE> <INDENT> with open(self.target,'w') as target: <NEW_LINE> <INDENT> target.write("= " + self.date.strftime("%Y-%m-%d") + " =\n\n") <NEW_LINE> for section in self.sections: <NEW_LINE> <INDENT> target.write("== " + section + " ==\n") <NEW_LINE> sec_obj = self.sections[section] <NEW_LINE>...
Compile the plan for the specified date from all matching temp files
625941f23d592f4c4ed1d634
def check_users_in_db(): <NEW_LINE> <INDENT> sql="select * from User" <NEW_LINE> rows=cursor.execute(sql).fetchall() <NEW_LINE> if rows: <NEW_LINE> <INDENT> return (True,rows) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (False,rows)
Check if db is empty or not..if contains user return a tuple with True and rows else return False with empty row
625941f216aa5153ce362a50
def _jsonp(method): <NEW_LINE> <INDENT> @functools.wraps(method) <NEW_LINE> async def wrapper(self, *args, **kwargs): <NEW_LINE> <INDENT> callback = self.get_argument('callback', None) <NEW_LINE> if is_async: <NEW_LINE> <INDENT> res = await method(self, *args, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res...
带参数,综合了同步和异步的装饰器,必须带参数 :param method: :return:
625941f2091ae3566866752b
def send_error_msg(self, error_str, close_conn=True): <NEW_LINE> <INDENT> _LOGGER.info(error_str) <NEW_LINE> error_msg = {'_error': error_str, 'when': datetime.datetime.utcnow().isoformat()} <NEW_LINE> self.write_message(error_msg) <NEW_LINE> if close_conn: <NEW_LINE> <INDENT> _LOGGER.info('Closing connection.') <NEW_L...
Convenience method for logging and returning errors. Note: this method will close the connection after sending back the error, unless close_conn=False
625941f24c3428357757c8fb
def store_vote(self, vote): <NEW_LINE> <INDENT> pass
We said dummy
625941f2cb5e8a47e48b8077
def plot_histogram(image, title="Image Histogram", height=400, width=1000, view_in_browser=True, bins=25, remove_zeros=True): <NEW_LINE> <INDENT> image = get_nii_obj(image)[0] <NEW_LINE> data = image.get_data() <NEW_LINE> histogram = get_histogram_data(data,bins=bins,remove_zeros=remove_zeros) <NEW_LINE> bins = '"%s"' ...
plot interactive histogram (in browser)
625941f2a4f1c619b28b0601
def view_cancel(): <NEW_LINE> <INDENT> pass
Cancel show render view
625941f27b25080760e39a2c
def dump_matrices(stub, matrix_filenames, matrices): <NEW_LINE> <INDENT> for matrix_name in matrices: <NEW_LINE> <INDENT> if len(matrices[matrix_name].shape) <= 2: <NEW_LINE> <INDENT> filename = os.path.join(os.getcwd(), matrix_filenames[matrix_name]) <NEW_LINE> np.savetxt(filename, matrices[matrix_name]) <NEW_LINE> <D...
Save all of the matrices to disk.
625941f221bff66bcd684f24
def test_mapping_parse_colon_separated(): <NEW_LINE> <INDENT> stream = StringIO(initial_value=COLON_SEPARATED_MAPPING) <NEW_LINE> mapping = Mapping.load(stream) <NEW_LINE> assert len(mapping.grid) == 4
Excel in certain locales will save with colons. Make sure this works
625941f2b57a9660fec33e63
def memory(self,since=0.0): <NEW_LINE> <INDENT> return self._VmB('VmSize:') - since
Return memory usage in bytes.
625941f2ec188e330fd5ad69
def cleanup( self ): <NEW_LINE> <INDENT> for intfName in self.intfNames(): <NEW_LINE> <INDENT> if self.name in intfName: <NEW_LINE> <INDENT> quietRun( 'ip link del ' + intfName ) <NEW_LINE> <DEDENT> <DEDENT> self.shell = None
Help python collect its garbage.
625941f2f548e778e58cdb57
@admin.route('/employees/assign/<int:id>', methods=['GET', 'POST']) <NEW_LINE> @login_required <NEW_LINE> def assign_employee(id): <NEW_LINE> <INDENT> check_admin() <NEW_LINE> employee = Employee.query.get_or_404(id) <NEW_LINE> if employee.is_admin: <NEW_LINE> <INDENT> abort(403) <NEW_LINE> <DEDENT> form = EmployeeAssi...
Assign a department and a role to an employee
625941f2b57a9660fec33e64
def check_overdue(self, entry): <NEW_LINE> <INDENT> period = 7 * 2 <NEW_LINE> doc = entry.copy.get_doc() <NEW_LINE> if (entry.renewed == False): <NEW_LINE> <INDENT> period = entry.user.group.get_checkout_time(doc) * 7 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> period = entry.user.group.get_renew_time(doc) * 7 <NEW_L...
Returns fine for overdue (0 if no fine)
625941f2046cf37aa974d318
def psiMPSEval(MPS, config): <NEW_LINE> <INDENT> Matrix_chain = [T[config[i]] for i, T in enumerate(MPS)] <NEW_LINE> return reduce(np.matmul, Matrix_chain).reshape([])
Computes the coefficient of the configuration given an MPS state
625941f2bf627c535bc137a6
def test_write_control(self): <NEW_LINE> <INDENT> with self.plc: <NEW_LINE> <INDENT> self.plc.write_control(constants.ADSSTATE_IDLE, 0, 0, constants.PLCTYPE_INT)
Test write_control for AdvancedHandler.
625941f2d164cc6175783326
def available_clouds(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> clouds = config_proxy.CLOUDS <NEW_LINE> return clouds.keys() <NEW_LINE> <DEDENT> except (ConfigurationError, AttributeError): <NEW_LINE> <INDENT> return None
list of regions configured for the current cloud for argparse suggestions
625941f260cbc95b062c6b1b
def test_get_proc_like_prefix__bad_objtype(self): <NEW_LINE> <INDENT> actual_prefix = self.new_obj('bogus')._get_proc_like_prefix('foo') <NEW_LINE> self.assertEqual('', actual_prefix)
Verify weird case where sig matches, but objtype is incorrect.
625941f27c178a314d6efa41
def OnKick(self, opNick, kickedNick, channel, message): <NEW_LINE> <INDENT> self.debug_hook() <NEW_LINE> self.put_log('*** ' + kickedNick + ' was kicked by ' + opNick.GetNick() + ' (' + message + ')', channel.GetName())
Called when a nick is kicked from a channel. :type opNick: const CNick & :type kickedNick: const CString & :type channel: CChan & :type message: const CString & :rtype: None
625941f2be383301e01b5a51
def create_user(self, email, password, is_active=True, name = None, role = None): <NEW_LINE> <INDENT> if not email: <NEW_LINE> <INDENT> raise ValueError("User must have an email.") <NEW_LINE> <DEDENT> if not password: <NEW_LINE> <INDENT> raise ValueError("User must have a password.") <NEW_LINE> <DEDENT> user_obj = self...
Method to create a user record for the database. Throws vlaue error if no email is provided. Throws value error if no password is provided.
625941f2097d151d1a22342d
def remove_configurable(self, configurable_class, name): <NEW_LINE> <INDENT> configurable_class_name = configurable_class.__name__.lower() <NEW_LINE> logger.info("Removing %s: '%s'", configurable_class_name, name) <NEW_LINE> registry = self.registry_for(configurable_class) <NEW_LINE> if name not in registry: <NEW_LINE>...
Callback fired when a configurable instance is removed. Looks up the existing configurable in the proper "registry" and removes it. If a method named "on_<configurable classname>_remove" is defined it is called via the work pooland passed the configurable's name. If the removed configurable is not present, a warning...
625941f27d43ff24873a327c
def close(self): <NEW_LINE> <INDENT> if self.print_msg: <NEW_LINE> <INDENT> print(' ')
Prints a blank space at the end to ensure proper printing of future statements.
625941f2dd821e528d63b77b
def inference_from_folder(printing=True): <NEW_LINE> <INDENT> img_h = 32 <NEW_LINE> lbl_to_char_dict = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'} <NEW_LINE> num_chars = len(lbl_to_char_dict) <NEW_LINE> model = load_trained_model(img_h, num_chars) <NEW_LINE> pil_images = load_images...
Do inference on images in a folder and print to screen
625941f2b830903b967e9edb
def print_pgf(self, fname_or_fh, *args, **kwargs): <NEW_LINE> <INDENT> if kwargs.get("dryrun", False): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if is_string_like(fname_or_fh): <NEW_LINE> <INDENT> with codecs.open(fname_or_fh, "w", encoding="utf-8") as fh: <NEW_LINE> <INDENT> self._print_pgf_to_fh(fh, *args, **kwa...
Output pgf commands for drawing the figure so it can be included and rendered in latex documents.
625941f20c0af96317bb87be
@app.route("/job/<job_id>/data", methods=['GET']) <NEW_LINE> def job_data(job_id): <NEW_LINE> <INDENT> job_dict = db.get_job(job_id) <NEW_LINE> if not job_dict: <NEW_LINE> <INDENT> return json.dumps({'error': 'job_id not found'}), 404, headers <NEW_LINE> <DEDENT> if not is_authorized(job_dict): <NEW_LINE> <INDENT> retu...
Get the raw data that the job returned. The mimetype will be the value provided in the metdata for the key ``mimetype``. **Results:** :rtype: string :statuscode 200: no error :statuscode 403: not authorized to view the job's data :statuscode 404: job id not found :statuscode 409: an error occurred
625941f2293b9510aa2c3867
def _load_asset_dynamically(self, fname, code=None): <NEW_LINE> <INDENT> if code is None: <NEW_LINE> <INDENT> self._asset_names.append(fname) <NEW_LINE> <DEDENT> if code is None: <NEW_LINE> <INDENT> code = self._store.load_asset(fname).decode("utf-8") <NEW_LINE> <DEDENT> if not code: <NEW_LINE> <INDENT> return <NEW_LIN...
Load an asset (JS or CSS) in a running session.
625941f221a7993f00bc82d2
def get_value(self): <NEW_LINE> <INDENT> if self._value: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> t = self._value.getTime() / 1000 <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> debugger <NEW_LINE> <DEDENT> if t == self.ts: <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> <DEDENT> return self.set_value()
the js Date we return is based on the unixtime ts
625941f2cc40096d61595f25
def update_library( library_key, title=None, description=None, allow_public_learning=None, allow_public_read=None, library_type=None, library_license=None, ): <NEW_LINE> <INDENT> ref = ContentLibrary.objects.get_by_key(library_key) <NEW_LINE> changed = False <NEW_LINE> if allow_public_learning is not None: <NEW_LINE> <...
Update a library's metadata (Slug cannot be changed as it would break IDs throughout the system.) A value of None means "don't change".
625941f210dbd63aa1bd3179
def Get_Member(self, row): <NEW_LINE> <INDENT> self.Customer_data[u'備註'] = self.Read_Data('B'+str(row)) <NEW_LINE> self.Customer_data[u'姓名'] = self.Read_Data('C'+str(row)) <NEW_LINE> self.Customer_data[u'生日'] = self.Read_Data('D'+str(row)) <NEW_LINE> self.Customer_data[u'根數'] = self.Read_Data('E'+str(row)) <NEW_LINE> s...
Get member data by row
625941f2796e427e537b0ba2
def main(): <NEW_LINE> <INDENT> global update_id <NEW_LINE> bot = telegram.Bot('561832171:AAEqnmFS1W-yVDFdkUFSmRyY70OTQ_vqXMg') <NEW_LINE> try: <NEW_LINE> <INDENT> update_id = bot.get_updates()[0].update_id <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> update_id = None <NEW_LINE> <DEDENT> logging.basicConf...
Run the bot.
625941f230dc7b7665901f37
def is_friend(self): <NEW_LINE> <INDENT> r = self.relationship <NEW_LINE> if r is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return r.type is RelationshipType.friend
bool: Checks if the user is your friend.
625941f2956e5f7376d71442
def aprint(*args): <NEW_LINE> <INDENT> current_input = '' <NEW_LINE> print(*args) <NEW_LINE> print(''.join(("\n)))", current_input)), end='')
Attempts to print things with asynchronosity in mind to preserve and display current input. WIP
625941f2ad47b63b2c50a557
def click__Customer__function(self, choice): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> listOfFeatures = list(self.find_elements("function_list")) <NEW_LINE> choice = str(choice) <NEW_LINE> for feature in listOfFeatures: <NEW_LINE> <INDENT> if re.search(choice,self.get_text(feature)): <NEW_LINE> <INDENT> logger.info(...
this function helps us to select anyone functions of customer that they have like (incidents, locations,cameras,edgeDevice, alert) and get all the respective details :return:
625941f23cc13d1c6d3c794e
def _hit_from_citdl(self, expr, scoperef, defn_only=False): <NEW_LINE> <INDENT> self.eval_depth += 1 <NEW_LINE> self.log("_hit_from_citdl:: expr: %r, scoperef: %r", expr, scoperef) <NEW_LINE> try: <NEW_LINE> <INDENT> self._check_infinite_recursion(expr) <NEW_LINE> <DEDENT> except EvalError: <NEW_LINE> <INDENT> scoperef...
Resolve the given CITDL expression (starting at the given scope) down to a non-import/non-variable hit.
625941f20fa83653e465758e
@app.route('/predict_file',methods=["POST"]) <NEW_LINE> def predict_note_file(): <NEW_LINE> <INDENT> df_test=pd.read_csv(request.files.get("file")) <NEW_LINE> prediction=classifier.predict(df_test) <NEW_LINE> return "The prediction values for the csv is "+str(list(prediction))
Let's Authenticate the Banks Note This is using docstrings for specifications. --- parameters: - name: file in: formData type: file required: true responses: 200: description: The output values
625941f223849d37ff7b3662
def logSaveEventHandler(self, senderName, dest, text): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.pm.logSMS(senderName, dest, text) <NEW_LINE> <DEDENT> except exceptions.IOError: <NEW_LINE> <INDENT> QMessageBox.critical(self, "Errore di salvataggio", u"ermeSms non può salvare i messaggi inviati " + ...
Evento di scrittura del file di log
625941f2b830903b967e9edc
def saveToFile(wordVecDict): <NEW_LINE> <INDENT> with open('./Utilities/Result Vectors/word_vectors.bin', 'wb') as f: <NEW_LINE> <INDENT> f.write(pickle.dumps(wordVecDict))
Save the word vectors to a binary file
625941f2711fe17d82542935
def test_contained_spherical_shell(centers_spherical_shell): <NEW_LINE> <INDENT> d = np.linalg.norm(centers_spherical_shell - [1, 2, 3], axis=1) <NEW_LINE> r_max = max(d) + _RADIUS <NEW_LINE> r_min = min(d) - _RADIUS <NEW_LINE> assert r_max < 1 or r_max == pytest.approx(1) <NEW_LINE> assert r_min > 0.5 or r_min == pyte...
Make sure all spheres are entirely contained within the domain.
625941f2236d856c2ad44dbb
def constrain(value): <NEW_LINE> <INDENT> size = 2**m <NEW_LINE> return (value%size)
Returns a value modulo 2^m. Used to wrap the value between 0 and 2^m. :param value: Int :return: Int
625941f26aa9bd52df03737f
def _round2(x, d=None): <NEW_LINE> <INDENT> d = 0 if d is None else d <NEW_LINE> p = 10 ** d <NEW_LINE> return float(floor((x * p) + copysign(0.5, x)))/p
Return the result of Python 2.x rounding, which is to round the number to the nearest integer. Python 3.x uses banker's rounding, which is not applicable for nearest neighbor approaches with grid boxes. Args: x (:obj:`float`): A number, usually a float. d (:obj:`int`, optional): The number of digits. Defau...
625941f2e64d504609d74e17
def _validate_request(handler): <NEW_LINE> <INDENT> pass
Validates request prior to processing.
625941f2d18da76e23532ab5
def show_image(self, event=None): <NEW_LINE> <INDENT> bbox1 = self.canvas.bbox(self.container) <NEW_LINE> bbox1 = (bbox1[0] + 1, bbox1[1] + 1, bbox1[2] - 1, bbox1[3] - 1) <NEW_LINE> bbox2 = (self.canvas.canvasx(0), self.canvas.canvasy(0), self.canvas.canvasx(self.canvas.winfo_width()), self.canvas.canvasy(self.canvas.w...
Show image on the Canvas
625941f273bcbd0ca4b2c64d
def make_utf8_compliant(text): <NEW_LINE> <INDENT> if text is None: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> if is_utf8_compliant(text): <NEW_LINE> <INDENT> return text <NEW_LINE> <DEDENT> for codec in ISO_8859_CODECS + ISO_2022_CODECS: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> text = unicode(text, codec).e...
Return a UTF-8 compliant version of text
625941f263b5f9789fde76be
def update_cmd_server(gamedir,currentGame,file_str): <NEW_LINE> <INDENT> source_target_list = [] <NEW_LINE> rev_update_cmd = file_str.split('?') <NEW_LINE> source_dir = rev_update_cmd.pop() <NEW_LINE> len_rev_cmd = len(rev_update_cmd) <NEW_LINE> msg = '' <NEW_LINE> if len_rev_cmd == 1: <NEW_LINE> <INDENT> msg = backup...
更新 exe dll 命令 :param gamedir: :param currentGame: :param file_str: :return:
625941f207d97122c4178e71
def reverse(self, x): <NEW_LINE> <INDENT> m = str(abs(x)) <NEW_LINE> s = int( m[::-1]) <NEW_LINE> if (s < -2147483648) or (s > 2147483648): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if x < 0 : <NEW_LINE> <INDENT> s=-1*s <NEW_LINE> <DEDENT> return(s)
:type x: int :rtype: int
625941f28e7ae83300e4b5a7
def write_event(json_data): <NEW_LINE> <INDENT> db = get_db() <NEW_LINE> row_to_insert = [ json_data["client_side_id"], json_data["user"], json_data["event_type"], int(json_data["event_timestamp"]), json_data["gps_coord"] ] <NEW_LINE> db.execute("""INSERT OR REPLACE INTO events VALUES(?,?,?,?,?)""",row_to_insert) <NEW_...
Inserts data passed in argument.
625941f2851cf427c661aae1
def ip_blocking_exists(handle, **kwargs): <NEW_LINE> <INDENT> mo = IpBlocking(parent_mo_or_dn=_get_mgmt_if_dn(handle)) <NEW_LINE> mo = _get_mo(handle, dn=mo.dn) <NEW_LINE> if mo.check_prop_match(**kwargs): <NEW_LINE> <INDENT> return (True, mo) <NEW_LINE> <DEDENT> return (False, None)
Checks if IP blocking settings match according to the parameters specified. Args: handle (ImcHandle) kwargs: Key-Value paired arguments relevant to IpBlocking object Returns: (True, IpBlocking object) if exists, else (False, None) Examples: ip_blocking_exists(handle, fail_count='6', ...
625941f2adb09d7d5db6cd63
def test_lastCommonAncestor(self): <NEW_LINE> <INDENT> assert self.tx[9].lastCommonAncestor(self.tx[9]) is self.tx[9] <NEW_LINE> assert self.tx[9].lastCommonAncestor(self.tx[7]) is self.tx[7] <NEW_LINE> assert self.tx[9].lastCommonAncestor(self.tx[10]) is self.tx[6] <NEW_LINE> assert self.tx[9].lastCommonAncestor(self....
NcbiTaxonomy should support lastCommonAncestor()
625941f2d18da76e23532ab6
def evaluationFunction(self, currentGameState, action): <NEW_LINE> <INDENT> successorGameState = currentGameState.generatePacmanSuccessor(action) <NEW_LINE> newPos = successorGameState.getPacmanPosition() <NEW_LINE> newFood = successorGameState.getFood() <NEW_LINE> newGhostStates = successorGameState.getGhostStates() <...
Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving...
625941f2ec188e330fd5ad6a