code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def fit(self, X, y=None, eval_data=None, eval_metric='acc', epoch_end_callback=None, batch_end_callback=None, kvstore='local', logger=None): <NEW_LINE> <INDENT> X = self._init_iter(X, y, is_train=True) <NEW_LINE> eval_data = self._init_eval_iter(eval_data) <NEW_LINE> if not X.iter_next(): <NEW_LINE> <INDENT> X.reset() ... | Fit the model.
Parameters
----------
X : DataIter, or numpy.ndarray/NDArray
Training data.
y : numpy.ndarray/NDArray, optional
Training set label.
If X is numpy.ndarray/NDArray, y is required to be set.
While y can be 1D or 2D (with 2nd dimension as 1), its 1st dimension must be
the same as X,... | 625941f4ac7a0e7691ed46e4 |
def insert(self, position: int, node: MatrixNode): <NEW_LINE> <INDENT> if not isinstance(node, (MatrixNodeCollection, MatrixNode, )): <NEW_LINE> <INDENT> raise TypeError("Unsupported data type for 'insert' operation.") <NEW_LINE> <DEDENT> if not node.parent() == self: <NEW_LINE> <INDENT> node._parent = self <NEW_LINE> ... | :param position:
:type position: int
:param node:
:type node: `morphologicalmatrix.matrixnode.MatrixNode` or
`morphologicalmatrix.matrixnodecollection.MatrixNodeCollection`
:raises TypeError: Raised if the supplied node data type is not valid | 625941f4442bda511e8bea34 |
def t360001_1(): <NEW_LINE> <INDENT> t360001_x4() <NEW_LINE> Quit() | State 0,1 | 625941f44428ac0f6e5bae1d |
def antiParallelMotion(self): <NEW_LINE> <INDENT> if not self.contraryMotion(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.vIntervals[0].simpleName == self.vIntervals[1].simpleName: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Returns true if the simple interval before is the same as the simple interval after
and the motion is contrary
>>> n11 = Note("C4")
>>> n12 = Note("D3") # descending 7th
>>> n21 = Note("G4")
>>> n22 = Note("A4") # ascending 2nd
>>> vlq1 = VoiceLeadingQuartet(n11, n12, n21, n22)
>>> vlq1.antiParallelMotion()
True | 625941f4ab23a570cc2507ad |
def test_third_book(): <NEW_LINE> <INDENT> book_3 = jsonpath.jsonpath(response, '$.store.book[2]') <NEW_LINE> assert book_3[0]['title'] == "Moby Dick!" | '$..book[2]'表示根节点下递归查找所有book属性中第3个对象, | 625941f407d97122c4178ec0 |
def getRobotPose(self): <NEW_LINE> <INDENT> pose = p.getBasePositionAndOrientation(self.robot) <NEW_LINE> return (pose[0], p.getEulerFromQuaternion(pose[1])) | Gets the robot (origin) position
Returns:
(tuple(3), tuple(3)) -- (x,y,z), (roll, pitch, yaw) | 625941f4adb09d7d5db6cdb1 |
def _handlePrivacyChanged(self, user_will_be_subscribed): <NEW_LINE> <INDENT> if user_will_be_subscribed: <NEW_LINE> <INDENT> notification_text = ( "Since you marked this bug as private you have " "automatically been subscribed to it. " "If you don't want to receive email about " "this bug you can <a href=\"%s\">mute y... | Handle the case where the privacy of the bug has been changed.
If the bug has been made private and the user is not a direct
subscriber, they will be subscribed. If the bug is being made
public or the user is already directly subscribed, this is a
no-op. | 625941f4be7bc26dc91cdc19 |
def test_bad_options(self): <NEW_LINE> <INDENT> self.run_check(101, 'Error: keyfile and certfile must both be specified ' 'if one of them is when calling b10-certgen in write ' 'mode.\n', '', [self.TOOL, '-w', '-c', 'foo']) <NEW_LINE> self.run_check(101, 'Error: keyfile and certfile must both be specified ' 'if one of ... | Tests some combinations of commands that should fail. | 625941f456b00c62f0f14c83 |
def __add_random_rooms(network, amount, depth): <NEW_LINE> <INDENT> for _ in range(depth): <NEW_LINE> <INDENT> for node in random.choices(network.get_nodes(), k=amount): <NEW_LINE> <INDENT> direction = random.choice(constants.DIRECTIONS) <NEW_LINE> pos = tuple(node.pos[i]+direction[i] for i in range(2)) <NEW_LINE> if n... | Add random rooms coming off of the rooms already placed.
amount is amount of attempted room additions to do on the current rooms.
depth is the amount of times to repeat this process.
High amount, low depth: lots of short extra paths.
Low amount, high depth: fewer but longer extra paths. | 625941f4167d2b6e312191b9 |
def reproject_geometry_to_target( vector_path, feature_id, target_sr_wkt, target_path): <NEW_LINE> <INDENT> vector = gdal.OpenEx(vector_path, gdal.OF_VECTOR) <NEW_LINE> layer = vector.GetLayer() <NEW_LINE> feature = layer.GetFeature(feature_id) <NEW_LINE> geom = feature.GetGeometryRef() <NEW_LINE> geom_wkb = geom.Expor... | Reproject a single OGR DataSource feature.
Transforms the features of the base vector to the desired output
projection in a new ESRI Shapefile.
Args:
vector_path (str): path to vector
feature_id (int): feature ID to reproject.
target_sr_wkt (str): the desired output projection in Well Known Text
(... | 625941f41b99ca400220b0d9 |
def access_token(self, code, redirect_uri, params=None, secret_type=None, endpoint='access_token', payload_type='urlencode'): <NEW_LINE> <INDENT> if code is None: <NEW_LINE> <INDENT> raise ValueError("Code must be set.") <NEW_LINE> <DEDENT> if redirect_uri is None: <NEW_LINE> <INDENT> raise ValueError("Redirect_uri mus... | Get an access token from the supplied code
https://svn.tools.ietf.org/html/draft-hammer-oauth2-00#section-3.5.2.2 | 625941f407f4c71912b11aaa |
def variable_summaries(variable, name): <NEW_LINE> <INDENT> with tf.name_scope('summaries'): <NEW_LINE> <INDENT> mean = tf.reduce_mean(variable) <NEW_LINE> tf.scalar_summary('mean/' + name, mean) <NEW_LINE> with tf.name_scope('stddev'): <NEW_LINE> <INDENT> stddev = tf.sqrt(tf.reduce_sum(tf.square(variable - mean))) <NE... | Attach a lot of summaries to a Tensor | 625941f4d268445f265b5494 |
def __init__(self, rom_file, viz=0, frame_skip=4, nullop_start=30, live_lost_as_eoe=True, max_num_frames=0): <NEW_LINE> <INDENT> super(AtariPlayer, self).__init__() <NEW_LINE> if not os.path.isfile(rom_file) and '/' not in rom_file: <NEW_LINE> <INDENT> rom_file = get_dataset_path('atari_rom', rom_file) <NEW_LINE> <DEDE... | Args:
rom_file: path to the rom
frame_skip: skip every k frames and repeat the action
viz: visualization to be done.
Set to 0 to disable.
Set to a positive number to be the delay between frames to show.
Set to a string to be a directory to store frames.
nullop_start: start with r... | 625941f4d268445f265b5495 |
def __init__(self, parent): <NEW_LINE> <INDENT> super(MenuBar, self).__init__() <NEW_LINE> self.parent = parent <NEW_LINE> self._options = {} <NEW_LINE> self._generated_menu = False <NEW_LINE> self.MENUS = { self.MENU_FILE: 'File', self.MENU_WIZARD: 'Wizard', self.MENU_INPUT: 'Input', self.MENU_OUTPUT: 'Output' } <NEW_... | Create the menu
Arguments:
parent {QWidget} -- Parent widget | 625941f473bcbd0ca4b2c69b |
def init_host(self, **kwargs): <NEW_LINE> <INDENT> ctxt = context.get_admin_context() <NEW_LINE> self.setup_backup_backend(ctxt) <NEW_LINE> try: <NEW_LINE> <INDENT> self._cleanup_incomplete_backup_operations(ctxt) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> LOG.exception("Problem cleaning incomplete backu... | Run initialization needed for a standalone service. | 625941f4a79ad161976cc76b |
def _update(self): <NEW_LINE> <INDENT> self.task.update() <NEW_LINE> self._A_eq = self.task.A <NEW_LINE> self._b_eq = self.task.b | Update the task by computing the A matrix and b vector that will be used by the task solver. | 625941f4a05bb46b383ece41 |
def test_prob_threshold_on_unit_test_data(): <NEW_LINE> <INDENT> X_train, y_train = load_unit_test(split="train", return_X_y=True) <NEW_LINE> X_test, y_test = load_unit_test(split="test", return_X_y=True) <NEW_LINE> indices = np.random.RandomState(0).choice(len(y_train), 10, replace=False) <NEW_LINE> pt = ProbabilityTh... | Test of ProbabilityThresholdEarlyClassifier on unit test data. | 625941f4283ffb24f3c55f1f |
def compute_features(papers, stringHasher, verbosity=1): <NEW_LINE> <INDENT> sc = StringCleaner() <NEW_LINE> sh = stringHasher <NEW_LINE> papers_feat = {} <NEW_LINE> total = len(papers) <NEW_LINE> start_time = time.time() <NEW_LINE> i = 1 <NEW_LINE> for p_id, p_title, p_abstract in papers: <NEW_LINE> <INDENT> title = s... | Computes the features of a list of papers, with a given list of ngrams.
Args:
papers (list of tuples): the list of papers (each element is a tuple of 3 strings: id, title, abstract)
stringHasher (:class:`string_tools.StringHasher`): the object which contains the list of ngrams
verbosity (int): 0: quiet; 1:... | 625941f401c39578d7e75461 |
def get( self, resource_name, scope, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = "2021-03-15-preview" <NEW_L... | Get the current usage of a resource.
:param resource_name: Resource name for a given resource provider. For example:
* SKU name for Microsoft.Compute
* SKU or TotalLowPriorityCores for Microsoft.MachineLearningServices
For Microsoft.Network PublicIPAddresses.
:type resource_name: str
:param scope: The target Az... | 625941f450812a4eaa59c940 |
def get_ls(self): <NEW_LINE> <INDENT> if hasattr(self, 'Kc') and self.Kc is not None: <NEW_LINE> <INDENT> ls = self.Kc.get_ls() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ls = np.array([np.nan] * self.K) <NEW_LINE> <DEDENT> return ls | Method to fetch ELBO-optimal length-scales | 625941f48c3a8732951589e8 |
def post(self: View, request: HttpRequest, slug: str) -> JsonResponse: <NEW_LINE> <INDENT> payload = json.loads(request.body.decode()) <NEW_LINE> content = str(payload.get('content', '')) <NEW_LINE> if not 1 <= len(content) <= 256: <NEW_LINE> <INDENT> return error('Content length must be between 1 and 256.') <NEW_LINE>... | Add a new message to the specified room. | 625941f4ad47b63b2c50a5a5 |
def download(url, output_dir="."): <NEW_LINE> <INDENT> import six <NEW_LINE> import os <NEW_LINE> file_name = url.split('/')[-1] <NEW_LINE> file_name = os.path.join(output_dir,file_name) <NEW_LINE> u = six.moves.urllib.request.urlopen(url) <NEW_LINE> f = open(file_name, 'wb') <NEW_LINE> meta = u.info() <NEW_LINE> file_... | Download a file given the URL
**Parameters**:
url: The URL
output_dir: The directory that stores the file | 625941f43c8af77a43ae3dcd |
def signUp_button(self): <NEW_LINE> <INDENT> search_input = self.driver.find_element(*MainPageLocators.SEARCH_SignUp) <NEW_LINE> search_input.click() | Triggers the search | 625941f49b70327d1c4e13fe |
def inverse_matrix(matrix): <NEW_LINE> <INDENT> return np.linalg.inv(matrix) | Return inverse of square transformation matrix.
>>> M0 = random_rotation_matrix()
>>> M1 = inverse_matrix(M0.T)
>>> np.allclose(M1, np.linalg.inv(M0.T))
True
>>> for size in range(1, 7):
... M0 = np.random.rand(size, size)
... M1 = inverse_matrix(M0)
... if not np.allclose(M1, np.linalg.inv(M0)): print(siz... | 625941f4596a89723608a0dd |
def signalmask(self): <NEW_LINE> <INDENT> pass | This method is typically invoked once when the trick is created.
It must return None or a dictionary whose keys are the symbolic names
of signals (e.g., 'SIGHUP'). In the latter case, signals not present
in the dictionary will not be followed with 'signal' invocations.
This method should return the same value every t... | 625941f4d8ef3951e3243b63 |
@set_module('numpy') <NEW_LINE> def tri(N, M=None, k=0, dtype=float): <NEW_LINE> <INDENT> if M is None: <NEW_LINE> <INDENT> M = N <NEW_LINE> <DEDENT> m = greater_equal.outer(arange(N, dtype=_min_int(0, N)), arange(-k, M-k, dtype=_min_int(-k, M - k))) <NEW_LINE> m = m.astype(dtype, copy=False) <NEW_LINE> return m | An array with ones at and below the given diagonal and zeros elsewhere.
Parameters
----------
N : int
Number of rows in the array.
M : int, optional
Number of columns in the array.
By default, `M` is taken equal to `N`.
k : int, optional
The sub-diagonal at and below which the array is filled.
`k` ... | 625941f456ac1b37e62647e8 |
def uninstall(packages, options=None): <NEW_LINE> <INDENT> manager = MANAGER <NEW_LINE> if options is None: <NEW_LINE> <INDENT> options = [] <NEW_LINE> <DEDENT> elif isinstance(options, str): <NEW_LINE> <INDENT> options = [options] <NEW_LINE> <DEDENT> if not isinstance(packages, str): <NEW_LINE> <INDENT> packages = " "... | Remove one or more packages.
Extra *options* may be passed to ``yum`` if necessary. | 625941f48a43f66fc4b54683 |
def _contentExistsCheck(self, content): <NEW_LINE> <INDENT> content = content.lower() <NEW_LINE> content = ( content.replace("\n", "") .replace(" ", "") .replace("\t", "") .replace('"', "") .replace("'", "") .replace("`", "") ) <NEW_LINE> md5 = j.data.hash.md5_string(content) <NEW_LINE> if md5 in self._contentAddedChec... | checks if content was already added if ues return True | 625941f4460517430c394799 |
def setCenterValue(self, centerValue): <NEW_LINE> <INDENT> self.centerValue = centerValue | Sets the calibration of the zero
for the joint. This can also be passed
in the constructor. | 625941f46fb2d068a760f6cd |
def get_db(): <NEW_LINE> <INDENT> if 'db' not in g: <NEW_LINE> <INDENT> g.db = sqlite3.connect( current_app.config['DATABASE'], detect_types=sqlite3.PARSE_DECLTYPES ) <NEW_LINE> g.db.row_factory = sqlite3.Row <NEW_LINE> <DEDENT> return g.db | 'g' -is a unique object used to store data that might be accessed by multiple functions during the request
:return: | 625941f4099cdd3c635f127d |
def discover(self, disc_fun): <NEW_LINE> <INDENT> eq_(disc_fun(*self.discover_args), True) | Call the discover function | 625941f421bff66bcd684f72 |
def pmml_row(**columns): <NEW_LINE> <INDENT> r = pmml.row() <NEW_LINE> for name, value in columns.items(): <NEW_LINE> <INDENT> el = bds().createChildElement(name) <NEW_LINE> bds().appendTextChild(value, el) <NEW_LINE> r.append(el) <NEW_LINE> <DEDENT> return r | Creates pmml.row element with columns
:param columns: key-value pairs to be inserted into the row
:return: pmml.row element | 625941f432920d7e50b287fb |
def is_string_set(x): <NEW_LINE> <INDENT> return (isinstance(x, Set) and all(isinstance(a, str) for a in x)) | Tests if something is a set | 625941f4ad47b63b2c50a5a6 |
def calculate(self): <NEW_LINE> <INDENT> logger.warn("Not implemented in the base class") | Calculate and return the Mandelbrot set. | 625941f47cff6e4e81117fab |
def result(self, message): <NEW_LINE> <INDENT> self._print_message('{0}: result: {1}\n'.format(self.prog, str(message)), sys.stdout) | Prints command execution result in a common format | 625941f4bde94217f3683411 |
def prior(target, label): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for t in target: <NEW_LINE> <INDENT> if t == label: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> <DEDENT> return count / len(target) | Calculate prior probability for a label | 625941f4ab23a570cc2507ae |
def Update(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('Update') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params) | Creates or updates the specified log sink resource.
Args:
request: (LoggingProjectsLogsSinksUpdateRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(LogSink) The response message. | 625941f4099cdd3c635f127e |
def pc_input_buffers_full(self, *args): <NEW_LINE> <INDENT> return _ccsds_swig.dll_cc_sptr_pc_input_buffers_full(self, *args) | pc_input_buffers_full(dll_cc_sptr self, int which) -> float
pc_input_buffers_full(dll_cc_sptr self) -> pmt_vector_float | 625941f4090684286d50f317 |
def ninja_check(args, build_folder): <NEW_LINE> <INDENT> if args.check_targets: <NEW_LINE> <INDENT> ninja_check = ['ninja'] + ['check-%s' % s for s in args.check_targets] <NEW_LINE> show_command(args, ninja_check) <NEW_LINE> subprocess.run(ninja_check, check=True, cwd=build_folder) | Invoke ninja with check targets if they are present
:param args: The args variable generated by parse_parameters
:param build_folder: The build folder that ninja should be run in
:return: | 625941f499cbb53fe679320a |
def get_model_id(cursor, model_name): <NEW_LINE> <INDENT> model_query = "SELECT model_id from content_models WHERE model_name = '{model_name}';".format( model_name=model_name) <NEW_LINE> try: <NEW_LINE> <INDENT> cursor.execute(model_query.encode('utf-8')) <NEW_LINE> <DEDENT> except MySQLdb.Error as ex: <NEW_LINE> <INDE... | get the content model id for the model name specified, from content model table | 625941f45e10d32532c5f54b |
def __getattr__(self, item): <NEW_LINE> <INDENT> if item in ( "____id_pack__", "__name__", "____conn__", "stop", ): <NEW_LINE> <INDENT> raise AttributeError() <NEW_LINE> <DEDENT> return getattr(self.server_breakpoint, item) | Return attributes of the real breakpoint. | 625941f4f9cc0f698b140c1c |
def __init__(self, wrapped_class, msgfunc_1, msgfunc_2, *args, **kwargs): <NEW_LINE> <INDENT> self.pbuf = PrintBuf() <NEW_LINE> self.func1 = msgfunc_1 <NEW_LINE> self.func2 = msgfunc_2 <NEW_LINE> self.pbuf.start() <NEW_LINE> self.wrapped_inst = wrapped_class(*args, **kwargs) <NEW_LINE> stdout_msg, stderr_msg = self.pbu... | Arguments:
wrapped_class: the class to be wrapped
msgfunc_1: function to deal with msg from stdout(1)
msgfunc_2: function to deal with msg from stderr(2)
*args, **kwargs: the original args of wrapped_class | 625941f4bf627c535bc137f6 |
def apply_sliding_window(df, window_size, stride_len): <NEW_LINE> <INDENT> print("sliding window search started...") <NEW_LINE> tmp_chunked_seq = pd.DataFrame( df['sequence'].apply( lambda x: window_search(x, window_size, stride_len) )) <NEW_LINE> expanded_seq = tmp_chunked_seq['sequence'].apply( lambda x: pd.Series(x)... | Predicts parts of sequences for AMP-like activity.
Arguments:
window_size: length of sub-region in the sequence to be tested
model: a trained model to be used for AMP prediction | 625941f4fb3f5b602dac3cc0 |
def write_nh_workflow_file(sim_name): <NEW_LINE> <INDENT> workflow_fname = get_nh_workflow_filename(sim_name) <NEW_LINE> f = open(workflow_fname,'w') <NEW_LINE> f.write ('NH_Import $inFile\n\n') <NEW_LINE> f.write ('NH_Calculate 0 $traverser\n') <NEW_LINE> f.write ('NH_Calculate 0 $espImage $traverser\n') <NEW_LINE> f.... | Writes the Nano-Hive Workflow file, which is a TCL script used by Nano-Hive to
run the simulation. It describes the workflow of the simulation. | 625941f43d592f4c4ed1d682 |
def copy_raw_links(in_stream, out_stream, allowed_shas, copied_shas): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> hdr = checked_read(in_stream, LINK_HEADER_LEN, True) <NEW_LINE> if hdr == '': <NEW_LINE> <INDENT> return count <NEW_LINE> <DEDENT> length, age, parent = struct.unpack(LINK_HEADE... | Copy any links with SHA1 hashes in allowed_shas from in_instream to
out_stream. | 625941f4498bea3a759ba0d3 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, DestinyDefinitionsDestinyItemSetBlockEntryDefinition): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941f4bd1bec0571d90c55 |
def ponComa( numero ): <NEW_LINE> <INDENT> entero, punto, decimales = str( numero ).partition('.') <NEW_LINE> cadenaNumero = str(entero) <NEW_LINE> indiceCadena = len( cadenaNumero ) <NEW_LINE> if cadenaNumero[0:1] == '-': <NEW_LINE> <INDENT> indiceCadena = indiceCadena - 1 <NEW_LINE> <DEDENT> if indiceCadena < 3: <NE... | Regresa numero como cadena con comas.
numero es un entero
ya maneja punto decimal
pero signo todavia no. | 625941f44a966d76dd55163c |
def __setitem__(self, key, value): <NEW_LINE> <INDENT> rows = self._get_rows(key) <NEW_LINE> if len(rows) == 0: <NEW_LINE> <INDENT> raise KeyError(f'No matches found for key {key}') <NEW_LINE> <DEDENT> elif len(rows) == 1: <NEW_LINE> <INDENT> self.table[rows[0]] = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if ... | Assign Table row's by value slice.
Parameters
----------
key : column element, list, ndarray, slice or tuple
Can be a value of the table primary index, a list/ndarray
of such values, or a value slice (both endpoints are included).
If a tuple is provided, the first element must be
an index to us... | 625941f4be8e80087fb2125d |
def simplify(n,d): <NEW_LINE> <INDENT> g=gcd(n,d) <NEW_LINE> return (n//g,d//g) | the most simplified fraction form
| 625941f444b2445a339326b7 |
def getRespVy(self,preprocessor): <NEW_LINE> <INDENT> return typical_materials.defElasticMaterial(preprocessor,self.respVyName(),5/6.0*self.b*self.h*self.concrType.Gcm()) | Material for modeling Y shear response of section | 625941f4c432627299f05271 |
def add_matrices2D(mat1, mat2): <NEW_LINE> <INDENT> s = len(mat1) <NEW_LINE> s2 = len(mat1[0]) <NEW_LINE> if abs(s - len(mat2)) != 0 or abs(s2 - len(mat2[0])) != 0: <NEW_LINE> <INDENT> return(None) <NEW_LINE> <DEDENT> tab = [] <NEW_LINE> j = 0 <NEW_LINE> for i in range(s): <NEW_LINE> <INDENT> tab2 = [] <NEW_LINE> for j... | add function | 625941f432920d7e50b287fc |
@app.route('/store/add', methods=['GET', 'POST']) <NEW_LINE> def store_add(): <NEW_LINE> <INDENT> form = AddStoreForm(request.form) <NEW_LINE> if request.method == 'POST' and form.validate_on_submit(): <NEW_LINE> <INDENT> phone_number = form.phone_number.data <NEW_LINE> parsed_number = phonenumbers.parse(phone_number, ... | Create a new store from the web data form
:return: store ID | 625941f450485f2cf553d3c2 |
def set_global_debug(self, state): <NEW_LINE> <INDENT> if self.site_comm.is_connected and "set_global_debug" in self.site_comm.call( "list_functions" ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.site_comm.call_no_response("set_global_debug", state) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> logge... | Attempts to tell a project subprocess to set the state of
the global debug logging setting. This will never raise
an exception, but a warning message will be logged if something
causes the RPC call to raise.
:param bool state: The debug to set. | 625941f4b57a9660fec33eb4 |
def set_action(self, action): <NEW_LINE> <INDENT> if not isinstance(action, URL): <NEW_LINE> <INDENT> raise TypeError('The action of a Form must be of ' 'url.URL type.') <NEW_LINE> <DEDENT> self._action = action | >>> f = Form()
>>> f.set_action('http://www.google.com/')
Traceback (most recent call last):
...
TypeError: The action of a Form must be of url.URL type.
>>> f = Form()
>>> action = URL('http://www.google.com/')
>>> f.set_action(action)
>>> f.get_action() == action
True | 625941f496565a6dacc8fcef |
def _get_solution_details(solution_id): <NEW_LINE> <INDENT> db_session = get_db_session(create_new_instance=True) <NEW_LINE> solution = db_session.query(Solution).filter_by(id=solution_id).one() <NEW_LINE> db_session.close() <NEW_LINE> return solution | Retrieves solution base on their Id
Args:
solution_id(int) : id of the solution to receive
Returns:
solution(Solution): solution row obtained from the database | 625941f4a79ad161976cc76c |
def simple_test_bboxes(self, x, img_metas, proposals, rcnn_test_cfg, rescale=False): <NEW_LINE> <INDENT> rois = bbox2roi(proposals) <NEW_LINE> bbox_cls_feats = self.bbox_roi_extractor( x[:self.bbox_roi_extractor.num_inputs], rois) <NEW_LINE> bbox_reg_feats = self.bbox_roi_extractor( x[:self.bbox_roi_extractor.num_input... | Test only det bboxes without augmentation. | 625941f421a7993f00bc8322 |
def CurveDim(curve_id, segment_index=-1): <NEW_LINE> <INDENT> return curve.Dimension | Returns the dimension of a curve object
Parameters:
curve_id = identifier of a curve object.
segment_index [opt] = the curve segment if curve_id identifies a polycurve.
Returns:
The dimension of the curve if successful. None on error. | 625941f4b5575c28eb68e62d |
def _enter(self): <NEW_LINE> <INDENT> raise NotImplementedError() | Enter the context. Subclasses should override this instead of
the true ``__enter__`` method. | 625941f42eb69b55b151cedf |
def user(): <NEW_LINE> <INDENT> first_name = fake.first_name() <NEW_LINE> last_name = fake.last_name() <NEW_LINE> username = (first_name + last_name).lower() <NEW_LINE> scrim = 1 <NEW_LINE> while User.objects.filter(username=username): <NEW_LINE> <INDENT> username = username + str(scrim) <NEW_LINE> scrim += 1 <NEW_LINE... | Create a user with a unique username and email. | 625941f430c21e258bdfaacb |
def registration_update_or_create(self): <NEW_LINE> <INDENT> if self.is_eligible: <NEW_LINE> <INDENT> return super().registration_update_or_create() | Creates or Updates the registration model with attributes
from this instance.
Called from the signal | 625941f421a7993f00bc8323 |
@utf8_decode <NEW_LINE> def command_nodistractions(data, current_buffer, args): <NEW_LINE> <INDENT> global hide_distractions <NEW_LINE> hide_distractions = not hide_distractions <NEW_LINE> channels = [ channel for channel in EVENTROUTER.weechat_controller.buffers.values() if channel in config.distracting_channels ] <NE... | /slack nodistractions
Hide or unhide all channels marked as distracting. | 625941f4956e5f7376d71492 |
def __init__(self): <NEW_LINE> <INDENT> self._table_dict = {} | (Table) -> NoneType
Initializes this Table to have a to have an empty dictionary | 625941f40c0af96317bb880d |
def get_item_id(url): <NEW_LINE> <INDENT> return re.findall(const.PT_ITEM_ID, url) | 获取item的id编号
:param url: item第一页的链接
:return: 编号 | 625941f4cad5886f8bd275fe |
def get_indexer_for(self, target, **kwargs): <NEW_LINE> <INDENT> if self.is_unique: <NEW_LINE> <INDENT> return self.get_indexer(target, **kwargs) <NEW_LINE> <DEDENT> indexer, _ = self.get_indexer_non_unique(target, **kwargs) <NEW_LINE> return indexer | guaranteed return of an indexer even when non-unique
This dispatches to get_indexer or get_indexer_nonunique as appropriate | 625941f466656f66f7cbc7d4 |
def filled(self, value='None'): <NEW_LINE> <INDENT> pass | a.filled([value]) --> Array
Returns a copy (deepcopy) of a, filled with value for a's shape. If no value is given, a is filled with the class default.
value will be expended with the class default values to the nearest matching sub array of a, then repeated.
value can't be truncated and will raise an error if of a siz... | 625941f4460517430c39479a |
def setStyles(self, faces): <NEW_LINE> <INDENT> self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "face:%(mono)s,size:%(size)d,back:%(backcol)s" % faces) <NEW_LINE> self.StyleClearAll() <NEW_LINE> self.SetSelForeground(True, wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)) <NEW_LINE> self.SetSe... | Configure font size, typeface and color for lexer. | 625941f4d4950a0f3b08c96c |
@verbose <NEW_LINE> def compute_maxwell_basis(info, origin='auto', int_order=8, ext_order=3, calibration=None, coord_frame='head', regularize='in', ignore_ref=True, bad_condition='error', mag_scale=100., extended_proj=(), verbose=None): <NEW_LINE> <INDENT> from ..io import RawArray <NEW_LINE> _validate_type(info, Info,... | Compute the SSS basis for a given measurement info structure.
Parameters
----------
%(info_not_none)s
%(maxwell_origin)s
%(maxwell_int)s
%(maxwell_ext)s
%(maxwell_cal)s
%(maxwell_coord)s
%(maxwell_reg)s
%(maxwell_ref)s
%(maxwell_cond)s
%(maxwell_mag)s
%(maxwell_extended)s
%(verbose)s
Returns
-------
S : ndarray, shap... | 625941f450485f2cf553d3c3 |
def logout(self): <NEW_LINE> <INDENT> self.session.pop('username', None) | Log the user out. | 625941f4f548e778e58cdba7 |
def test_cirle_creation(example_circle): <NEW_LINE> <INDENT> assert example_circle.radius == 4 | when user initiates a circle with no keyword
and object is created with equivalent radius | 625941f4925a0f43d254a4a4 |
def __str__(self): <NEW_LINE> <INDENT> surface = '' <NEW_LINE> for morph in self.morphs: <NEW_LINE> <INDENT> surface += morph.surface <NEW_LINE> <DEDENT> return '{}\tsrcs{}\tdst[{}]'.format(surface, self.srcs, self.dst) | オブジェクトの文字列表現
実際に表示される文字列の形を定義する | 625941f4507cdc57c6307311 |
def wrap_angle(a): <NEW_LINE> <INDENT> while a > pi: <NEW_LINE> <INDENT> a -= two_pi <NEW_LINE> <DEDENT> while a < -pi: <NEW_LINE> <INDENT> a += two_pi <NEW_LINE> <DEDENT> return a | Wrap an angle so that it is between -pi and pi. | 625941f410dbd63aa1bd31c8 |
def main(argv=None): <NEW_LINE> <INDENT> (_psr, args) = parse_args.parse((argv if argv else sys.argv)[1:]) <NEW_LINE> args = process_args_or_run_command(args) <NEW_LINE> cnf = os.environ.copy() if args.env else {} <NEW_LINE> if args.extra_opts: <NEW_LINE> <INDENT> args.extra_opts = parser.parse(args.extra_opts) <NEW_LI... | :param argv: Argument list to parse or None (sys.argv will be set). | 625941f41f037a2d8b946823 |
def test_message(self): <NEW_LINE> <INDENT> self.assertIs( _somethingOld, self.getDeprecatedModuleAttribute( __name__, "somethingOld", self.version, message="It's old", ), ) <NEW_LINE> self.assertEqual([], self.flushWarnings()) | The I{message} argument to L{getDeprecatedModuleAttribute} matches the
prefix of the deprecation message. | 625941f4adb09d7d5db6cdb2 |
@staff_member_required <NEW_LINE> def check_update_registry(request): <NEW_LINE> <INDENT> if request.method == "GET": <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> update_info = [] <NEW_LINE> registries = oai_registry_api.get_all() <NEW_LINE> for registry in registries: <NEW_LINE> <INDENT> last_update = None <NEW_LINE> ... | Check if a registry is updating.
Args:
request:
Returns: | 625941f43539df3088e2e972 |
def _read_dig_point_struct(fid, tag, shape, rlims): <NEW_LINE> <INDENT> return dict( kind=int(np.fromstring(fid.read(4), dtype=">i4")), ident=int(np.fromstring(fid.read(4), dtype=">i4")), r=np.fromstring(fid.read(12), dtype=">f4"), coord_frame=FIFF.FIFFV_COORD_UNKNOWN) | Read dig point struct tag | 625941f463b5f9789fde770d |
def test_user_credentials_api3(self): <NEW_LINE> <INDENT> pass | Test case for user_credentials_api3
get API 3 credential | 625941f4aad79263cf391071 |
def search(self, nums, target): <NEW_LINE> <INDENT> low = 0 <NEW_LINE> high = len(nums) - 1 <NEW_LINE> while low <= high: <NEW_LINE> <INDENT> mid = (low + high) >> 1 <NEW_LINE> if nums[mid] < target: <NEW_LINE> <INDENT> low = mid + 1 <NEW_LINE> <DEDENT> elif nums[mid] > target: <NEW_LINE> <INDENT> high = mid - 1 <NEW_L... | :type nums: List[int]
:type target: int
:rtype: int | 625941f426238365f5f0f49d |
def deleteEdge(self, vertex1, vertex2): <NEW_LINE> <INDENT> edge_deleted = False <NEW_LINE> print("=" * 41) <NEW_LINE> print(f"Deleting edge {vertex1} --> {vertex2}...") <NEW_LINE> if self.hasEdge(vertex1, vertex2): <NEW_LINE> <INDENT> for vertex in self.graph: <NEW_LINE> <INDENT> if vertex.get_head() == vertex1: <NEW_... | Deletes an edge between two provided vertices.
:param vertex1: Starting vertex
:param vertex2: Destination vertex
:return: True if edge is deleted, False otherwise | 625941f45510c4643540f9fb |
def remove_child(self, child, index, logical_block_size): <NEW_LINE> <INDENT> if not self.initialized: <NEW_LINE> <INDENT> raise pycdlibexception.PyCdlibInternalError('Directory Record not initialized') <NEW_LINE> <DEDENT> if index < 0: <NEW_LINE> <INDENT> raise pycdlibexception.PyCdlibInternalError('Invalid child inde... | Remove a child from this Directory Record.
Parameters:
child - The child DirectoryRecord object to remove.
index - The index of the child into this DirectoryRecord children list.
logical_block_size - The size of a logical block on this volume
descriptor.
Returns:
True if removing this child c... | 625941f4aad79263cf391072 |
def main(): <NEW_LINE> <INDENT> if len(sys.argv) > 1: <NEW_LINE> <INDENT> fileName = os.getcwd() + "/" + sys.argv[1] <NEW_LINE> if len(sys.argv) == 3 and sys.argv[2].lower() == "-p": <NEW_LINE> <INDENT> print(wrapMarkdownParagraphsToColLimit(fileName, 70)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> writeToFile(fileN... | Checks command line input and calls the proper formatting
functions.
:return: | 625941f4e76e3b2f99f3ae28 |
def robust_method(self, method, uri, **kwargs): <NEW_LINE> <INDENT> resp = self.oneshot_method(method, uri, **kwargs) <NEW_LINE> if resp.status_code != 401: <NEW_LINE> <INDENT> return resp <NEW_LINE> <DEDENT> self.refresh_token() <NEW_LINE> return self.oneshot_method(method, uri, **kwargs) | Try method once; upon 401, refresh token and retry once. Return last response. | 625941f4be8e80087fb2125e |
def singleton(cls): <NEW_LINE> <INDENT> outer = locals() <NEW_LINE> def getinstance(*args, **kwargs): <NEW_LINE> <INDENT> if 'instance' not in outer: <NEW_LINE> <INDENT> outer['instance'] = cls(*args, **kwargs) <NEW_LINE> <DEDENT> return outer['instance'] <NEW_LINE> <DEDENT> return getinstance | Class decorator
TODO: use args and kwargs as key_s to instance dict | 625941f44e696a04525c9a75 |
def add(self, entity_id: int, component: object) -> None: <NEW_LINE> <INDENT> is_instance = isinstance(component, self.ctype) <NEW_LINE> is_inherited = self.ctype in type(component).__bases__ <NEW_LINE> if not is_instance and not is_inherited: <NEW_LINE> <INDENT> raise ValueError( ) <NEW_LINE> <DEDENT> self.components[... | Adds a key-value pair between an entity and the component to the
component dictionary. | 625941f4442bda511e8bea36 |
def anonymise(self, for_bulk=True): <NEW_LINE> <INDENT> if not getattr( self.model, app_settings.GDPR_PRIVACY_INSTANCE_NAME ).can_anonymise: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> bulk_objects = [] <NEW_LINE> bulk_log_objects = [] <NEW_LINE> for obj in self: <NEW_LINE> <INDENT> privacy_obj = obj.anonymise(for_b... | Anonymise all privacy-registered objects in this queryset | 625941f457b8e32f52483ac6 |
def _get_filtered_pools(self): <NEW_LINE> <INDENT> if self.configuration.safe_get('netapp_volume_list'): <NEW_LINE> <INDENT> msg = _LW("The option 'netapp_volume_list' is deprecated and " "will be removed in the future releases. Please use " "the option 'netapp_pool_name_search_pattern' instead.") <NEW_LINE> versionuti... | Return available pools filtered by a pool name search pattern. | 625941f407d97122c4178ec2 |
def render(self, screen_surf, offset=None): <NEW_LINE> <INDENT> for rend in reversed(self._renderers): <NEW_LINE> <INDENT> rend.render(screen_surf, offset) | Renders the world through the registered renderers.
:Parameters:
screen_surf : Surface
The surface to draw on.
offset : `Vec3`
Ignored, but it is there to keep render method signature the the same. | 625941f456b00c62f0f14c85 |
def make_coffee(coffee_chosen, money_in): <NEW_LINE> <INDENT> resources["water"] -= MENU[coffee_chosen]["ingredients"]["water"] <NEW_LINE> if "milk" in MENU[coffee_chosen]["ingredients"]: <NEW_LINE> <INDENT> resources["milk"] -= MENU[coffee_chosen]["ingredients"]["milk"] <NEW_LINE> <DEDENT> resources["coffee"] -= MENU[... | Makes desired coffee, deducts resources used from resources, gives change back to user,
returns money to be added to machine coffers | 625941f42eb69b55b151cee0 |
def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> if request.method in permissions.SAFE_METHODS: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return obj.user_profiles.id == request.user.id | Checks the user is trying to update their own status. | 625941f482261d6c526abad0 |
def __init__( self, name, implementation, outputDir=".", generator="cpp.component.pull", spdTemplateFile = SCAHOME+DEFAULT_SPD_TEMPLATE, scdTemplateFile = SCAHOME+DEFAULT_SCD_TEMPLATE, prfTemplateFile = SCAHOME+DEFAULT_PRF_TEMPLATE, loggingConfigUri = None): <NEW_LINE> <INDENT> SoftPackage.__init__(self, name, implemen... | Create a resource with no ports/properties. Use helper methods to add
additional elements.
Note, "implementation" argument must be "cpp", "java", or "python" | 625941f43cc13d1c6d3c799e |
def set_original(self, original: pd.DataFrame) -> "DataSteps": <NEW_LINE> <INDENT> self._original = original <NEW_LINE> return self | Set the original of the data.
This method is intended to to set original
data in case a DataSteps instnace is created
without the data. This helps to create instances
in modules and scripts, where the data will only be
set after import.
The method returns the DataSteps instance itself
such that it can coveniently be ... | 625941f4b545ff76a891443d |
@with_client <NEW_LINE> def test_model(client): <NEW_LINE> <INDENT> with client.application.test_request_context(): <NEW_LINE> <INDENT> response = request(client.get, url_for( 'model', document_type='test', document_name='First test')) <NEW_LINE> assert 'contenteditable' in response.data | Test the model page. | 625941f46aa9bd52df0373cf |
def generateTrees(self, n): <NEW_LINE> <INDENT> def dfs(l,r): <NEW_LINE> <INDENT> if r<l: <NEW_LINE> <INDENT> return [None] <NEW_LINE> <DEDENT> out = [] <NEW_LINE> for m in range(l,r+1): <NEW_LINE> <INDENT> left = dfs(l,m-1) <NEW_LINE> right = dfs(m+1,r) <NEW_LINE> for lnode in left: <NEW_LINE> <INDENT> for rnode in ri... | :type n: int
:rtype: List[TreeNode] | 625941f4287bf620b61d4087 |
def hash_password(password, request=None): <NEW_LINE> <INDENT> num_rounds = 12 <NEW_LINE> if request: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> num_rounds = int(request.registry.settings.get('salt_rounds', 12)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> if num_rounds < 4: <NEW_LINE> <I... | Hashes a password
:param unicode password: the password to hash
:param Request request: a pyramid request. If given this method will
attempt to retrieve a "salt_rounds" setting and use
that for the salt generation instead.
:returns: bcrypt hashed password | 625941f4a05bb46b383ece43 |
def test_pep8(self): <NEW_LINE> <INDENT> pep8style = pep8.StyleGuide(quiet=True) <NEW_LINE> result = pep8style.check_files(['models/city.py']) <NEW_LINE> self.assertEqual(result.total_errors, 0, "Fix Your PEP8 Style") | Test that models/base_model.py conforms to PEP8 | 625941f4711fe17d82542984 |
def ins(): <NEW_LINE> <INDENT> pass | Display game instructions. | 625941f41d351010ab856142 |
def create_cnn_model(base_arch, cut: Union[int, Callable] = None, pretrained: bool = True, lin_ftrs: Optional[Collection[int]] = None, ps: Floats = 0.5, custom_head: Optional[nn.Module] = None, bn_final: bool = False, concat_pool: bool = True): <NEW_LINE> <INDENT> print(type(base_arch), base_arch) <NEW_LINE> body = cre... | Create custom convnet architecture | 625941f43c8af77a43ae3dcf |
def minor_af(alt_af: np.ndarray): <NEW_LINE> <INDENT> maf = alt_af.copy() <NEW_LINE> maf[np.where(maf > 0.5)] = 1 - maf[np.where(maf > 0.5)] <NEW_LINE> return maf | Converts the alternate allele frequency to the minor allele frequency
>>> a = np.array([0.01, 0.2, 0.7, 0.9])
>>> res = minor_af(a)
>>> np.allclose(res, np.array([0.01, 0.2 , 0.3 , 0.1 ]))
True
:param alt_af:
:return: | 625941f4d7e4931a7ee9e547 |
def dict_snake_to_camel_case(snake_dict, convert_keys=True, convert_subkeys=False): <NEW_LINE> <INDENT> converted = {} <NEW_LINE> for key, value in snake_dict.items(): <NEW_LINE> <INDENT> if isinstance(value, dict): <NEW_LINE> <INDENT> new_value = dict_snake_to_camel_case(value, convert_keys=convert_subkeys, convert_su... | Recursively convert a snake_cased dict into a camelCased dict
:param snake_dict: Dictionary to convert
:param convert_keys: Whether the key should be converted
:param convert_subkeys: Whether to also convert the subkeys, in case they are named properties of the dict
:return: | 625941f4d18da76e23532b06 |
def run_postprocess(self, stream, mimetype, filepath, resources): <NEW_LINE> <INDENT> self.logger.info("running pdf conversion") <NEW_LINE> self._export_pdf(filepath) <NEW_LINE> return stream, filepath, resources | should not be called directly
Parameters
----------
stream: str
the main file contents
filepath: None or pathlib.Path
the path to the output file
Returns
-------
stream: str
filepath: None or pathlib.Path | 625941f49b70327d1c4e1400 |
def do_string_cast(self, connection, column_name): <NEW_LINE> <INDENT> return connection.ops.quote_name(column_name) | Casts the given column name to string. | 625941f455399d3f05588ce0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.