code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def print_label_for_requisition(self, request, requisition): <NEW_LINE> <INDENT> if requisition.requisition_identifier: <NEW_LINE> <INDENT> self.print_label(request, requisition, 1)
Prints a requisition label.
625941b80a50d4780f666cdd
def _get_network_id(self): <NEW_LINE> <INDENT> return self.__network_id
Getter method for network_id, mapped from YANG variable /networks/network/network_id (network-id) YANG Description: Identifies a network.
625941b88e71fb1e9831d5fb
def rescale_by(self, factor): <NEW_LINE> <INDENT> for node in self.iter_descendants(): <NEW_LINE> <INDENT> node.length *= factor
Rescale the height of the tree by the given factor (equally on each branch). Args: factor (float): Scaling factor.
625941b8a8370b77170526ef
def test_recipients_to_addresses_with_groups_inactive_members(self): <NEW_LINE> <INDENT> group1 = self.create_review_group('group1') <NEW_LINE> group2 = self.create_review_group('group2') <NEW_LINE> user1 = User.objects.create(username='user1', first_name='User', last_name='One') <NEW_LINE> user2 = User.objects.create(username='user2', first_name='User', last_name='Two', is_active=False) <NEW_LINE> group1.users = [user1] <NEW_LINE> group2.users = [user2] <NEW_LINE> addresses = recipients_to_addresses([group1, group2]) <NEW_LINE> self.assertEqual(len(addresses), 1) <NEW_LINE> self.assertEqual(addresses, set([get_email_address_for_user(user1)]))
Testing generating addresses form recipients that are groups with inactive members
625941b87cff6e4e811177d4
@app.task(ignore_result=True) <NEW_LINE> def download_file(pk): <NEW_LINE> <INDENT> release_file = models.ReleaseFile.objects.get(pk=pk) <NEW_LINE> logger.info("Downloading %s", release_file.url) <NEW_LINE> proxies = None <NEW_LINE> if settings.LOCALSHOP_HTTP_PROXY: <NEW_LINE> <INDENT> proxies = settings.LOCALSHOP_HTTP_PROXY <NEW_LINE> <DEDENT> response = requests.get(release_file.url, stream=True, proxies=proxies) <NEW_LINE> filename = os.path.basename(release_file.url) <NEW_LINE> if 'content-length' in response.headers: <NEW_LINE> <INDENT> size = int(response.headers['content-length']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> size = len(response.content) <NEW_LINE> <DEDENT> default_content_type = 'application/octet-stream' <NEW_LINE> content_type = response.headers.get('content-type') <NEW_LINE> if content_type is None or content_type == default_content_type: <NEW_LINE> <INDENT> content_type = mimetypes.guess_type(filename)[0] or default_content_type <NEW_LINE> <DEDENT> with TemporaryUploadedFile(name=filename, size=size, charset='utf-8', content_type=content_type) as temp_file: <NEW_LINE> <INDENT> temp_file.write(response.content) <NEW_LINE> temp_file.seek(0) <NEW_LINE> md5_hash = md5_hash_file(temp_file) <NEW_LINE> if md5_hash != release_file.md5_digest: <NEW_LINE> <INDENT> logger.error("MD5 hash mismatch: %s (expected: %s)" % ( md5_hash, release_file.md5_digest)) <NEW_LINE> return <NEW_LINE> <DEDENT> release_file.distribution.save(filename, temp_file) <NEW_LINE> release_file.save() <NEW_LINE> <DEDENT> logger.info("Complete")
Download the file reference in `models.ReleaseFile` with the given pk.
625941b84d74a7450ccd4011
def _get_dataset_filename(split_name, shard_id): <NEW_LINE> <INDENT> output_filename = FLAGS.output_filename % ( split_name, shard_id, FLAGS._NUM_SHARDS) <NEW_LINE> return os.path.join(FLAGS.output_dataset_dir, output_filename)
return data_filename like that /home/mao/Documents/datasets/flowers_train_00000-of-00005.tfrecord /home/mao/Documents/datasets/flowers_validation_00000-of-00005.tfrecord
625941b8fb3f5b602dac34dd
def load_breast_cancer_data(): <NEW_LINE> <INDENT> dataset = load_breast_cancer() <NEW_LINE> X = pd.DataFrame(dataset.data, columns=dataset.feature_names) <NEW_LINE> y = pd.DataFrame(dataset.target, columns=['y']) <NEW_LINE> return X, y
データセットを取得する 乳がんの診断結果 classification
625941b8187af65679ca4f6b
def __init__(self, cosmo, bias_params): <NEW_LINE> <INDENT> self.__cosmo = cosmo <NEW_LINE> self.__bias_params = bias_params
Packages all parameters for the cosmology and BiasParams object. Parameters ---------- cosmo : Cosmology bias_params : BiasParams
625941b88e7ae83300e4ae19
@Operation.factory <NEW_LINE> def Log(a): <NEW_LINE> <INDENT> return np.log(a),
Logarithm op.
625941b88a349b6b435e7fc2
def strip_fixed(fstr): <NEW_LINE> <INDENT> Fi = cStringIO.StringIO() <NEW_LINE> Fi.write(fstr) <NEW_LINE> Fi.seek(0) <NEW_LINE> Fo = cStringIO.StringIO() <NEW_LINE> Fhead = None <NEW_LINE> for line in Fi: <NEW_LINE> <INDENT> if line[:4] == "FIX:": <NEW_LINE> <INDENT> Fhead = string.strip(line) <NEW_LINE> Fo.write('\n') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Fo.write(line) <NEW_LINE> <DEDENT> <DEDENT> Fo.seek(0) <NEW_LINE> return Fhead, Fo.read()
Take a psc file string and return two strings: (1) The file header containing the "FIX: " line and (2) the remainder of file. Parameters ---------- fstr : str String representation of psc file. Returns ------- tuple of str 1st element contains file header, second the remainder of the file. See also -------- psc_to_str mod_to_str
625941b88e05c05ec3eea1bf
def p_recursive(self, p): <NEW_LINE> <INDENT> if p[1] == "R": <NEW_LINE> <INDENT> p[0] = Recursive(None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p[0] = Recursive(p[1])
recursive : 'R' | number
625941b8046cf37aa974cb99
def get_bodyfat(self, base_date=None, user_id=None, period=None, end_date=None): <NEW_LINE> <INDENT> return self._get_body('fat', base_date, user_id, period, end_date)
https://dev.fitbit.com/docs/body/#get-body-fat-logs base_date should be a datetime.date object (defaults to today), period can be '1d', '7d', '30d', '1w', '1m', '3m', '6m', '1y', 'max' or None end_date should be a datetime.date object, or None. You can specify period or end_date, or neither, but not both.
625941b850812a4eaa59c174
def RIE(actives, scores, alpha): <NEW_LINE> <INDENT> N=len(actives) <NEW_LINE> n=sum(scores) <NEW_LINE> x = np.array(actives) <NEW_LINE> e = np.exp(-alpha*x) <NEW_LINE> summation = sum(e) <NEW_LINE> RIE = ((1/n)*summation)/((1/N)*((1-np.exp(-alpha))/np.exp(alpha/N-1))) <NEW_LINE> return RIE
Returns Robust Initial Enhancement
625941b866656f66f7cbbff8
def _evaluate(self,R,z,phi=0.,t=0.): <NEW_LINE> <INDENT> r2= R**2.+z**2. <NEW_LINE> r= nu.sqrt(r2) <NEW_LINE> return (0.5*nu.log(1+r2/self._a2) +self._a/r*nu.arctan(r/self._a))/self._a
NAME: _evaluate PURPOSE: evaluate the potential at R,z INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: Phi(R,z) HISTORY: 2015-12-04 - Started - Bovy (UofT)
625941b8d53ae8145f87a0c4
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, __props__=None, __name__=None, __opts__=None): <NEW_LINE> <INDENT> if __name__ is not None: <NEW_LINE> <INDENT> warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) <NEW_LINE> resource_name = __name__ <NEW_LINE> <DEDENT> if __opts__ is not None: <NEW_LINE> <INDENT> warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) <NEW_LINE> opts = __opts__ <NEW_LINE> <DEDENT> if opts is None: <NEW_LINE> <INDENT> opts = pulumi.ResourceOptions() <NEW_LINE> <DEDENT> if not isinstance(opts, pulumi.ResourceOptions): <NEW_LINE> <INDENT> raise TypeError('Expected resource options to be a ResourceOptions instance') <NEW_LINE> <DEDENT> if opts.version is None: <NEW_LINE> <INDENT> opts.version = _utilities.get_version() <NEW_LINE> <DEDENT> if opts.id is None: <NEW_LINE> <INDENT> if __props__ is not None: <NEW_LINE> <INDENT> raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') <NEW_LINE> <DEDENT> __props__ = dict() <NEW_LINE> <DEDENT> super(Provider, __self__).__init__( 'vpc', resource_name, __props__, opts)
Create a Vpc resource with the given unique name, props, and options. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource.
625941b8a17c0f6771cbdea2
def wvar(x,w=None,ddof=1,robust=False): <NEW_LINE> <INDENT> if (w!=None): <NEW_LINE> <INDENT> assert len(w) == len(x), 'w must be the same length as x' <NEW_LINE> <DEDENT> return wcov(x,x,w,ddof,robust)
Weighted variance Calculate the variance of x using weights w. If ddof=1 (default), then the result is the unbiased (sample) variance when w=1. Args: x : array of values w : array of weights for each element of x; can be ommitted if robust=True ddof : scalar differential degrees of freedom (Default ddof=1) robust : (boolean) robust weights will be internally calculated using FastMCD; only used if robust=True and w is empty Returns: scalar : weighted variance
625941b8dd821e528d63aff9
def apply_lighting_adjustment(self): <NEW_LINE> <INDENT> image = self.modification_information.image <NEW_LINE> min = -self.preference.lighting_factor <NEW_LINE> max = self.preference.lighting_factor <NEW_LINE> contrast_factor = int(min + random.random() * (max - min) + 1) <NEW_LINE> exposure_factor = int(min + random.random() * (max - min) + 1) <NEW_LINE> brightness_factor = int(min + random.random() * (max - min) + 1) <NEW_LINE> transformed_image = im.adjust_contrast_exposure(image, contrast_factor, exposure_factor) <NEW_LINE> transformed_image = im.adjust_brightness(transformed_image, brightness_factor) <NEW_LINE> self.modification_information.image = transformed_image
Adjust lighting of image by random factor in range specified by the user
625941b876e4537e8c3514c6
def run_service(self): <NEW_LINE> <INDENT> self.alerts_queue = Queue(maxsize=SERVICE_ALERT_QUEUE_SIZE) <NEW_LINE> self.thread_server = Thread(target=self._on_server_start) <NEW_LINE> self.thread_server.start() <NEW_LINE> try: <NEW_LINE> <INDENT> while self.thread_server.is_alive(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> new_alert = self.alerts_queue.get(timeout=1) <NEW_LINE> self.emit(**new_alert) <NEW_LINE> <DEDENT> except Empty: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> self.logger.debug("Caught KeyboardInterrupt, shutting service down gracefully") <NEW_LINE> raise <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> self.logger.exception(exc) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self._on_server_shutdown()
Run the service and start an alert processing queue. .. seealso:: Use :func:`on_server_start` and :func:`on_server_shutdown` for starting and shutting down your service
625941b8b5575c28eb68de4c
def send_message(chan, msg): <NEW_LINE> <INDENT> con.send(bytes("PRIVMSG {} :{}\r\n".format(chan, msg), "UTF-8"))
Send PRIVMSG to IRC.
625941b8bde94217f3682c4a
def parse_flow(self, flow): <NEW_LINE> <INDENT> fb = None <NEW_LINE> for k in self._flow_terms(flow): <NEW_LINE> <INDENT> fb = self.f_index(k) <NEW_LINE> if fb is not None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if fb is None: <NEW_LINE> <INDENT> fn = flow['Name'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self._f.cas(fb) is None: <NEW_LINE> <INDENT> fn = self._f.name(fb) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fn = self._f.cas(fb) <NEW_LINE> <DEDENT> <DEDENT> comp = self.c_mgr.find_matching(flow['Compartment']) <NEW_LINE> return fn, comp
Return a valid flowable name and a compartment object as a 2-tuple. To find the flowable: Start with the flow's link, then the flow's name, then the flow's cas. To return: preferentially return CAS number, then name if CAS is none. :param flow: :return:
625941b8d18da76e23532320
def get_NamespaceURI(self, index): <NEW_LINE> <INDENT> return super(IXMLNamespaces, self).get_NamespaceURI(index)
Method IXMLNamespaces.get_NamespaceURI INPUT index : long OUTPUT uri : BSTR*
625941b84f88993c3716bec2
def drawShadedContours(xlist, ylist, zmatrix, levels): <NEW_LINE> <INDENT> dislin.conshd(xlist, len(xlist), ylist, len(ylist), zmatrix, levels, len(levels))
Draws contours with colors between contour lines.
625941b8cad5886f8bd26e30
def put(self, local_file): <NEW_LINE> <INDENT> with open(local_file, "rb") as fd: <NEW_LINE> <INDENT> self.write(fd.read())
Copy a file from the controller to the instrument. :param local_file: :return:
625941b81f5feb6acb0c49a3
def getDict(self): <NEW_LINE> <INDENT> return { "name": self.name, "type": self.type, "time": self.formatTime(), "room": self.room }
return dictionary format notation for jsonifying the object
625941b88a43f66fc4b53eb8
def mayfly(x,b,t): <NEW_LINE> <INDENT> for i in range(t): <NEW_LINE> <INDENT> x = b*(1-x)*x <NEW_LINE> figure(num=1, figsize=(6, 5)) <NEW_LINE> plot(i,x,'c.') <NEW_LINE> title('Mayfly Population over Time') <NEW_LINE> xlabel('Time (Years)') <NEW_LINE> ylabel('Population (x)') <NEW_LINE> patch = mpatches.Patch(color='c', label='Growth Rate b: %s'%b) <NEW_LINE> legend(handles=[patch]) <NEW_LINE> <DEDENT> savefig('fig1.svg', dpi=1000)
Function in which mayfly(x,b,tmin,tmax): x, population as percent of max, b, ratio of surviving offspring to females, t, Generations
625941b88a349b6b435e7fc3
def getUrl(self): <NEW_LINE> <INDENT> return self.obj.o.getUrl(page=self.field.pageName, nav='no')
Returns the URL for going back to the initiator object, on the page showing self.field.
625941b8e1aae11d1e749b02
def move_files_in_dir(src, dst): <NEW_LINE> <INDENT> logger.debug(u'Move files to directory %s %s', src, dst) <NEW_LINE> for f in glob(src): <NEW_LINE> <INDENT> dst_path = os.path.join(dst, os.path.basename(f)) <NEW_LINE> shutil.move(f, dst_path)
Move files or directories :param str src: source files or directories :param str dst: destination directory
625941b8851cf427c661a369
@click.group() <NEW_LINE> def cli(): <NEW_LINE> <INDENT> pass
Manage EMS
625941b89c8ee82313fbb5c3
def centered_alignment(k1: np.ndarray, k2: np.ndarray) -> float: <NEW_LINE> <INDENT> k1_centered = center_kernel(k1) <NEW_LINE> k2_centered = center_kernel(k2) <NEW_LINE> return alignment(k1_centered, k2_centered)
Centered kernel alignment Cortes et al. (2012)
625941b8f9cc0f698b140454
def diagnostics(self): <NEW_LINE> <INDENT> super(GMM, self).diagnostics() <NEW_LINE> self.plot_results(self.x_train, self.labels, self.model.means_, self.model.covariances_) <NEW_LINE> scikit_mixin.plot_silhouette(data=self.x_train, cluster_labels=self.labels)
Diagnostics for GMM. Generates a silhouette plot and a biplot of the clusters on the first 2 features.
625941b85510c4643540f246
def on_save(self): <NEW_LINE> <INDENT> super(Users, self).on_save() <NEW_LINE> if self.settingsMode == 'tool': <NEW_LINE> <INDENT> for item in self.__editedItems__['added']: <NEW_LINE> <INDENT> item.itemObj.writeFile() <NEW_LINE> <DEDENT> for item in self.__editedItems__['edited']: <NEW_LINE> <INDENT> item.itemObj.writeFile() <NEW_LINE> <DEDENT> for item in self.__editedItems__['deleted']: <NEW_LINE> <INDENT> self.users.deleteUser(userObj=item.itemObj, archive=True) <NEW_LINE> <DEDENT> <DEDENT> elif self.settingsMode == 'project': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.__editedItems__ = dict(added=[], edited=[], deleted=[])
Command launched when 'Save' QPushButton is clicked Save data
625941b844b2445a33931eee
def find_word(line, n, option=None): <NEW_LINE> <INDENT> excelude = ".,-?!\t\n-;'/" <NEW_LINE> for char in excelude: <NEW_LINE> <INDENT> line = line.replace(char, " ") <NEW_LINE> <DEDENT> words = line.split(" ") <NEW_LINE> found = [] <NEW_LINE> for word in words: <NEW_LINE> <INDENT> if len(word) == n: <NEW_LINE> <INDENT> found.append(word) <NEW_LINE> <DEDENT> <DEDENT> if option is None: <NEW_LINE> <INDENT> return found[0] <NEW_LINE> <DEDENT> if isinstance(option, int): <NEW_LINE> <INDENT> return found[option-1] <NEW_LINE> <DEDENT> for word in found: <NEW_LINE> <INDENT> if word.startswith(option): <NEW_LINE> <INDENT> return word <NEW_LINE> <DEDENT> <DEDENT> return None
Assignment 3
625941b88e05c05ec3eea1c0
def movmean(X, n=1, axis=0, maskNAN=False): <NEW_LINE> <INDENT> ndim = X.ndim <NEW_LINE> if maskNAN: <NEW_LINE> <INDENT> mnan = np.isnan(X) <NEW_LINE> <DEDENT> if n==0: <NEW_LINE> <INDENT> return X <NEW_LINE> <DEDENT> if axis==1: <NEW_LINE> <INDENT> Xout = np.transpose( movmean( np.transpose(X), n)) <NEW_LINE> return Xout <NEW_LINE> <DEDENT> if n>1: <NEW_LINE> <INDENT> X = movmean(X, n=n-1) <NEW_LINE> <DEDENT> if ndim == 2 : <NEW_LINE> <INDENT> xleft = np.full( (X.shape[0], X.shape[1]), np.nan, dtype='f4') <NEW_LINE> xright = np.full( (X.shape[0], X.shape[1]), np.nan, dtype='f4') <NEW_LINE> xleft[:-1,:] = X[1:,:] <NEW_LINE> xright[1:,:] = X[:-1,:] <NEW_LINE> Xout = np.nanmean( np.concatenate( (np.tile(X,(1,1,1)), np.tile(xleft,(1,1,1)), np.tile(xright,(1,1,1))), axis=0), axis=0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> xleft = np.full( (X.shape[0], ), np.nan, dtype='f4') <NEW_LINE> xright = np.full( (X.shape[0], ), np.nan, dtype='f4') <NEW_LINE> xleft[:-1] = X[1:] <NEW_LINE> xright[1:] = X[:-1] <NEW_LINE> Xout = np.nanmean( np.concatenate( (np.tile(X,(1,1)), np.tile(xleft,(1,1)), np.tile(xright,(1,1))), axis=0), axis=0) <NEW_LINE> <DEDENT> if maskNAN: <NEW_LINE> <INDENT> Xout[mnan] = np.nan <NEW_LINE> <DEDENT> return Xout
This function generates a moving mean ignoring nan along the axis dimension of X of oder n
625941b873bcbd0ca4b2becc
def p_command_stack(p): <NEW_LINE> <INDENT> commands.append({'op' : p[1], 'args' : None})
command : POP | PUSH
625941b88e71fb1e9831d5fc
def f_z(X, T, p): <NEW_LINE> <INDENT> (Nt, Nx) = X.shape <NEW_LINE> Ny = len(yids) <NEW_LINE> Nz = 1 + Nx + Ny <NEW_LINE> columns = ["time"] + xids + yids <NEW_LINE> Z = np.empty(shape=(Nt, Nz)) <NEW_LINE> Z[:, 0] = T <NEW_LINE> Z[:, 1:(Nx+1)] = X <NEW_LINE> for kt in range(Nt): <NEW_LINE> <INDENT> y = f_y(x=X[kt, :], t=T[kt], p=p) <NEW_LINE> Z[kt, (Nx+1):] = y <NEW_LINE> <DEDENT> Z = pd.DataFrame(Z, columns=columns) <NEW_LINE> return Z
DataFrame of full timecourse of solution.
625941b832920d7e50b2801b
def filter_list_of_tuples_which_contained_values_from_current_list_of_lists(input_hash_list=None, constraints_hash_list=None): <NEW_LINE> <INDENT> out = input_hash_list <NEW_LINE> for val_lst in constraints_hash_list: <NEW_LINE> <INDENT> out = filter_list_of_tuples_which_contained_data_from_list(input_list=out, list_with_filter_keys=val_lst) <NEW_LINE> <DEDENT> return out
Ex: input_hash_list = [ (1, 2, 4), (1, 3, 4), (1, 9, 4), (3, 2, 5), (1, 7, 6), (7, 2, 1), (1, 2, 4), (7, 1, 2), (8, 7, 2), (0, 1, 7), (2, 1, 7), ] bb = [ [1, 7], [1, 0], ] pre-return: [(1, 7, 6), (7, 2, 1), (7, 1, 2), (0, 1, 7), (2, 1, 7)] return: [(0, 1, 7)] :param input_hash_list: :param constraints_hash_list: :return:
625941b8c432627299f04a93
def test_email_construction_without_optional_params(self): <NEW_LINE> <INDENT> listing = ( '1. Lead Data Scientist @ Brightwater Group\n' 'Link: http://ie.indeed.com/viewjob?jk=4da3f3ec1f781a3f\n' 'Location: Dublin\n' 'Snippet: Our client, a major, international banking brand, currently ' 'has a job opening for a lead data scientist. As a lead data Scientist ' 'sitting within the banks...\n' ) <NEW_LINE> expected_string = ( f'From: [email protected] <[email protected]>\n' f'To: [email protected]\n' f'Subject: Job opportunities: 1 new job posted\n' f'Hello test.recipient,\n\n' f'There is 1 new job listing to review.\n' f'The following job listing was found for {repr(self.query)} in ' f'{repr(self.location)}:\n\n' f'{listing}\n' ) <NEW_LINE> s = construct_email(self.cfg_no_opt, self.query, self.location, self.single_job_db) <NEW_LINE> self.assertEqual(expected_string, s)
Test we construct a valid email when optional params are missing.
625941b89f2886367277a6e0
def __init__(self, db_filename, interface): <NEW_LINE> <INDENT> self._interface = interface <NEW_LINE> self._sql_conn = sqlite3.connect(db_filename, check_same_thread=False) <NEW_LINE> self._sql = self._sql_conn.cursor()
Interface for the SQLite 3 Database that stores processed comments/submissions Args: db_filename (str): Filename of the SQLite 3 database interface (CLI): CLI for the bot to allow live updates.
625941b80a50d4780f666cde
def use_drone_imgs(self): <NEW_LINE> <INDENT> self.cam = ARDroneCamera() <NEW_LINE> im = cv2.imread('tests/test_imgs/drone_dataset/test{}.png'.format(self.viewset.numViews)) <NEW_LINE> return im
For the test and demonstration purposes only, replaces camera images and parameters with ones from the dataset.
625941b899cbb53fe6792a36
def install_requires(): <NEW_LINE> <INDENT> skip_install_requires = environ.get('SKIP_INSTALL_REQUIRES') <NEW_LINE> if not skip_install_requires: <NEW_LINE> <INDENT> with open('requirements.pip') as r: <NEW_LINE> <INDENT> return r.readlines() <NEW_LINE> <DEDENT> <DEDENT> return []
Check for required packages
625941b8090684286d50eb2f
def activityTimeInfo(self, *args): <NEW_LINE> <INDENT> return _ArNetworkingPy.ArServerInfoRobot_activityTimeInfo(self, *args)
activityTimeInfo(self, ArServerClient client, ArNetPacket packet)
625941b84e4d5625662d422c
def predict(self, x): <NEW_LINE> <INDENT> probs = sigmoid(self._exp_dot(x)) <NEW_LINE> return (probs > 0.5).astype(np.int)
Return the predicted classes. :param x: (batch_size, num_features) :return: (batch_size)
625941b891af0d3eaac9b863
@app_views.route('/states/', strict_slashes=False, methods=['POST']) <NEW_LINE> def create_state(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> states = request.get_json() <NEW_LINE> if states.get("name") is None: <NEW_LINE> <INDENT> return abort(400, 'Missing name') <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> return abort(400, 'Not a JSON') <NEW_LINE> <DEDENT> new_state = State(**states) <NEW_LINE> storage.new(new_state) <NEW_LINE> storage.save() <NEW_LINE> return jsonify(new_state.to_dict()), 201
define how to create a new state objects Returns: 201 on successful creation 400 "Not a JSON" if HTTP body request is not valid 404 if state_id is not linked to any State object
625941b8ab23a570cc24ffcf
def register_delete_thread_response(self, thread_id): <NEW_LINE> <INDENT> assert httpretty.is_enabled(), 'httpretty must be enabled to mock calls.' <NEW_LINE> httpretty.register_uri( httpretty.DELETE, "http://localhost:4567/api/v1/threads/{id}".format(id=thread_id), body=json.dumps({}), status=200 )
Register a mock response for DELETE on the CS thread instance endpoint
625941b831939e2706e4ccbf
def bt_save_favoris(user_current, id_produit, request): <NEW_LINE> <INDENT> produit = Produits.objects.get(id__exact=id_produit) <NEW_LINE> Favoris.objects.create( user=user_current, produits=produit, date_ajout=datetime.today, aff_index=False) <NEW_LINE> path_back = request.path <NEW_LINE> path_good = path_back.replace("save", "aliments") <NEW_LINE> info = "Vous avez bien enregistrer ce produit" <NEW_LINE> return [info, path_good]
Saving in faovris
625941b8adb09d7d5db6c5e2
def plotParticle(sequence,radar): <NEW_LINE> <INDENT> for i,item in enumerate(sequence): <NEW_LINE> <INDENT> z,p=item <NEW_LINE> z=Polar2Coor(z,radar) <NEW_LINE> plt.plot(p[:,0],p[:,1],'.',label='particles t%d'%(i)) <NEW_LINE> plt.plot(z[0],z[1],'*',label='measurement t%d'%(i)) <NEW_LINE> <DEDENT> plt.grid(linestyle='dotted') <NEW_LINE> plt.legend() <NEW_LINE> plt.show()
各时刻的量测值和粒子群位置 :param sequence: [[z0,p0]...[zt,pt]] z0[2] p0[500,2] :param radar: [2] 雷达位置
625941b8be383301e01b52dc
def test_follow_dont_allow_get_request(self): <NEW_LINE> <INDENT> foo = createUser("foo", "[email protected]", "example") <NEW_LINE> juan = createUser("juan", "[email protected]", "example") <NEW_LINE> c = Client() <NEW_LINE> c.login(username='foo', password='example') <NEW_LINE> response = c.get(f"/follow/juan") <NEW_LINE> self.assertEqual(response.status_code, 404) <NEW_LINE> response = c.put(f"/follow/juan") <NEW_LINE> self.assertEqual(response.status_code, 404)
*** Should a user follow another user via GET or PUT, return 404 response ***
625941b88da39b475bd64dc6
def create_tar_sr_il_abc(self): <NEW_LINE> <INDENT> self.create_tar_sr_il() <NEW_LINE> fragments_to_concat = [] <NEW_LINE> not_matched = self.tar_sr_il <NEW_LINE> for i in [self.abc_2, self.abc_1]: <NEW_LINE> <INDENT> entire_table = not_matched.merge(i, left_on=['icd_9'], right_on=['icd_9'], how='left', validate="m:1") <NEW_LINE> fragments_to_concat.append(entire_table[entire_table['abc'].notnull()]) <NEW_LINE> not_matched = entire_table[entire_table['abc'].isnull()] <NEW_LINE> not_matched = not_matched.drop(columns=['abc']) <NEW_LINE> <DEDENT> self.tar_sr_il_abc = pd.concat(fragments_to_concat + [not_matched], sort=True).reset_index(drop=True) <NEW_LINE> assert self.tar_sr_il_abc.shape[0] == self.tar_sr_il.shape[0] <NEW_LINE> self.tar_sr_il_abc['abc'] = self.tar_sr_il_abc['abc'].fillna('X') <NEW_LINE> self.tar_sr_il = self.tar_sr_il_abc
Creates tar_sr_il as normally should and adds ABC categories to procedures.
625941b81f5feb6acb0c49a4
def __mul__(self, other): <NEW_LINE> <INDENT> from datatypes.integers.UInt import UInt <NEW_LINE> if (isinstance(other, UInt8)): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for i in xrange(7, -1, -1): <NEW_LINE> <INDENT> arrayTemp = [] <NEW_LINE> result += [arrayTemp] <NEW_LINE> for k in xrange (0, 7-i): <NEW_LINE> <INDENT> result[7-i].insert(0, PlainBit(False)) <NEW_LINE> <DEDENT> for j in xrange(7, -1, -1): <NEW_LINE> <INDENT> result[7-i].insert(0, self.bits[i] * other.bits[j]) <NEW_LINE> <DEDENT> <DEDENT> for l in xrange(0, 8): <NEW_LINE> <INDENT> while (len(result[l]) < 16): <NEW_LINE> <INDENT> result[l].insert(0, PlainBit(False)) <NEW_LINE> <DEDENT> <DEDENT> result1a = UInt8(bits=result[0][8:]) <NEW_LINE> result1b = UInt8(bits=result[0][:8]) <NEW_LINE> result1UInt = UInt(ints = [result1b, result1a]) <NEW_LINE> result2a = UInt8(bits=result[1][8:]) <NEW_LINE> result2b = UInt8(bits=result[1][:8]) <NEW_LINE> result2UInt = UInt(ints = [result2b, result2a]) <NEW_LINE> result3a = UInt8(bits=result[2][8:]) <NEW_LINE> result3b = UInt8(bits=result[2][:8]) <NEW_LINE> result3UInt = UInt(ints = [result3b, result3a]) <NEW_LINE> result4a = UInt8(bits=result[3][8:]) <NEW_LINE> result4b = UInt8(bits=result[3][:8]) <NEW_LINE> result4UInt = UInt(ints = [result4b, result4a]) <NEW_LINE> result5a = UInt8(bits=result[4][8:]) <NEW_LINE> result5b = UInt8(bits=result[4][:8]) <NEW_LINE> result5UInt = UInt(ints = [result5b, result5a]) <NEW_LINE> result6a = UInt8(bits=result[5][8:]) <NEW_LINE> result6b = UInt8(bits=result[5][:8]) <NEW_LINE> result6UInt = UInt(ints = [result6b, result6a]) <NEW_LINE> result7a = UInt8(bits=result[6][8:]) <NEW_LINE> result7b = UInt8(bits=result[6][:8]) <NEW_LINE> result7UInt = UInt(ints = [result7b, result7a]) <NEW_LINE> result8a = UInt8(bits=result[7][8:]) <NEW_LINE> result8b = UInt8(bits=result[7][:8]) <NEW_LINE> result8UInt = UInt(ints = [result8b, result8a]) <NEW_LINE> resultFinal = result1UInt + result2UInt + result3UInt + result4UInt + result5UInt + result6UInt + result7UInt + result8UInt <NEW_LINE> return resultFinal
This method will multiply 2 UInt8. We override this operator to be able to write operations more easily The multiplication seems to work fine, however there may be a problem in the addition of two UInt Since the addition od two UInt is used in this method there may be some error see addition of UInts of different sizes. :param other: Right Operand :type other: UInt8 :returns: the product of the two UInt8 which is an UInt :rtype: UInt
625941b8e8904600ed9f1d78
def read_a_shift_file(filename, parameters, res_incl=None, res_excl=None): <NEW_LINE> <INDENT> data = sc.loadtxt(filename, dtype=[('resonance_id', 'S10'), ('shift_ppb', 'f8'), ('shift_ppb_err', 'f8')]) <NEW_LINE> data_points = list() <NEW_LINE> exp_type = parameters['experiment_type'].replace('_shift', '') <NEW_LINE> data_point = __import__(exp_type + '.data_point', globals(), locals(), ['DataPoint'], -1) <NEW_LINE> for resonance_id, shift_ppb, shift_ppb_err in data: <NEW_LINE> <INDENT> included = ( (res_incl is not None and resonance_id in res_incl) or (res_excl is not None and resonance_id not in res_excl) or (res_incl is None and res_excl is None) ) <NEW_LINE> if not included: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> parameters['resonance_id'] = resonance_id <NEW_LINE> data_points.append(data_point.DataPoint(shift_ppb, shift_ppb_err, parameters)) <NEW_LINE> <DEDENT> return data_points
Reads in the fuda file and spit out the intensities
625941b899fddb7c1c9de1e2
def get_operators( kspace_data, loc, mask, fourier_type=1, max_iter=80, regularisation=None, linear=None, ): <NEW_LINE> <INDENT> n_coils = 1 if kspace_data.ndim == 2 else kspace_data.shape[0] <NEW_LINE> shape = kspace_data.shape[-2:] <NEW_LINE> if fourier_type == 0: <NEW_LINE> <INDENT> kspace_generator = KspaceGeneratorBase( full_kspace=kspace_data, mask=mask, max_iter=max_iter ) <NEW_LINE> fourier_op = FFT(shape=shape, n_coils=n_coils, mask=mask) <NEW_LINE> <DEDENT> elif fourier_type == 1: <NEW_LINE> <INDENT> kspace_generator = Column2DKspaceGenerator( full_kspace=kspace_data, mask_cols=loc ) <NEW_LINE> fourier_op = FFT(shape=shape, n_coils=n_coils, mask=mask) <NEW_LINE> <DEDENT> elif fourier_type == 2: <NEW_LINE> <INDENT> kspace_generator = DataOnlyKspaceGenerator( full_kspace=kspace_data, mask_cols=loc ) <NEW_LINE> fourier_op = ColumnFFT(shape=shape, n_coils=n_coils) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> if linear is None: <NEW_LINE> <INDENT> linear_op = Identity() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lin_cls = linear.pop("class", None) <NEW_LINE> if lin_cls == "WaveletN": <NEW_LINE> <INDENT> linear_op = WaveletN(n_coils=n_coils, n_jobs=4, **linear) <NEW_LINE> linear_op.op(np.zeros_like(kspace_data)) <NEW_LINE> <DEDENT> elif lin_cls == "Identity": <NEW_LINE> <INDENT> linear_op = Identity() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> <DEDENT> prox_op = IdentityProx() <NEW_LINE> if regularisation is not None: <NEW_LINE> <INDENT> reg_cls = regularisation.pop("class") <NEW_LINE> if reg_cls == "LASSO": <NEW_LINE> <INDENT> prox_op = LASSO(weights=regularisation["weights"]) <NEW_LINE> <DEDENT> if reg_cls == "GroupLASSO": <NEW_LINE> <INDENT> prox_op = GroupLASSO(weights=regularisation["weights"]) <NEW_LINE> <DEDENT> elif reg_cls == "OWL": <NEW_LINE> <INDENT> prox_op = OWL( **regularisation, n_coils=n_coils, bands_shape=linear_op.coeffs_shape ) <NEW_LINE> <DEDENT> elif reg_cls == "IdentityProx": <NEW_LINE> <INDENT> prox_op = IdentityProx() <NEW_LINE> linear_op = Identity() <NEW_LINE> <DEDENT> <DEDENT> return kspace_generator, fourier_op, linear_op, prox_op
Create the various operators from the config file.
625941b8e64d504609d74690
def is_four_kind(self): <NEW_LINE> <INDENT> rank_freq = self.rank_freq() <NEW_LINE> return 4 in rank_freq.values()
See if there are four of a kind in the hand.
625941b8de87d2750b85fbdd
def rforest(self): <NEW_LINE> <INDENT> if self.smoteit: <NEW_LINE> <INDENT> self.train = SMOTE( self.train, atleast=500, atmost=500, resample=self.duplicate) <NEW_LINE> <DEDENT> clf = RandomForestClassifier(random_state=1) <NEW_LINE> train_df = formatData(self.train) <NEW_LINE> test_df = formatData(self.test) <NEW_LINE> features = train_df.columns[:-2] <NEW_LINE> klass = train_df[train_df.columns[-2]] <NEW_LINE> clf.fit(train_df[features].astype('float32'), klass.astype('float32')) <NEW_LINE> preds = clf.predict( test_df[test_df.columns[:-2]].astype('float32')).tolist() <NEW_LINE> return preds
RF
625941b8cb5e8a47e48b78ff
def __init__(self, x, y, pic_path, wid, hgt): <NEW_LINE> <INDENT> super().__init__(x, y, pic_path) <NEW_LINE> self.img = pg.transform.smoothscale(self.img, (wid, hgt))
int x: initial x coor of picture int y: initial y coor of picture str pic_path: relative path of object picture int wid: the width of the picture int hgt: the hight of the picture
625941b815baa723493c3dc1
def __init__(self: 'ConsoleController', number_of_cheeses: int, number_of_stools: int): <NEW_LINE> <INDENT> self.number_of_cheeses = number_of_cheeses <NEW_LINE> self.num_of_stools = number_of_stools <NEW_LINE> self.model = TOAHModel(number_of_stools) <NEW_LINE> self.model.fill_first_stool(number_of_cheeses)
Initialize a new 'ConsoleController'. number_of_cheeses - number of cheese to tower on the first stool number_of_stools - number of stools
625941b80c0af96317bb8039
def rotated(self, angle_degrees): <NEW_LINE> <INDENT> radians = -math.radians(angle_degrees) <NEW_LINE> cos = math.cos(radians) <NEW_LINE> sin = math.sin(radians) <NEW_LINE> x = self.x*cos - self.y*sin <NEW_LINE> y = self.x*sin + self.y*cos <NEW_LINE> return Vec2d(x, y)
Create and return a new vector by rotating this vector by angle_degrees degrees clockwise. :return: Rotated vector
625941b899fddb7c1c9de1e3
def create_db(connection): <NEW_LINE> <INDENT> driver = connection.engine.name <NEW_LINE> if driver == 'sqlite': <NEW_LINE> <INDENT> return create_sqlite_db(connection) <NEW_LINE> <DEDENT> def _execute(sql, *args, **kwargs): <NEW_LINE> <INDENT> engine = _get_admin_connection(connection) <NEW_LINE> engine.execute(text(sql).execution_options(autocommit=True), *args, **kwargs) <NEW_LINE> <DEDENT> test_database_name = connection.engine.url.database <NEW_LINE> try: <NEW_LINE> <INDENT> _execute('CREATE DATABASE %s' % test_database_name) <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> logger.warning('Got an error creating the test database: %s\n' % exc) <NEW_LINE> logger.info('Destroying old test database "%s"...' % unicode(connection.engine.url)) <NEW_LINE> try: <NEW_LINE> <INDENT> _execute('DROP DATABASE %s' % test_database_name) <NEW_LINE> _execute('CREATE DATABASE %s' % test_database_name) <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> logger.warning('Got an error recreating the test database: %s\n' % exc) <NEW_LINE> <DEDENT> <DEDENT> return test_database_name
Creates the test database tables.
625941b87047854f462a125d
def train_input_fn(data_dir_path, params): <NEW_LINE> <INDENT> with tf.name_scope("Data_Pipeline"): <NEW_LINE> <INDENT> dataset = train(data_dir_path) <NEW_LINE> dataset = dataset.shuffle(params["train_size"] + params["valid_size"]) <NEW_LINE> dataset = dataset.repeat(params["num_epochs"]) <NEW_LINE> dataset = dataset.batch(params["batch_size"]) <NEW_LINE> dataset = dataset.prefetch(1) <NEW_LINE> <DEDENT> return dataset
Train input function for the MNIST dataset. Args: data_dir_path: (string) path to the data directory params: (Params) contains hyperparameters of the model (ex: `params.num_epochs`)
625941b83c8af77a43ae35ee
def italic(dec_func): <NEW_LINE> <INDENT> def wrapper(): <NEW_LINE> <INDENT> return '<i>' + dec_func() + '</i>' <NEW_LINE> <DEDENT> return wrapper
Make input string italic
625941b83617ad0b5ed67d4f
def OnSelChanged(self, event=None): <NEW_LINE> <INDENT> x = event.GetItem() <NEW_LINE> self.master.check_active() <NEW_LINE> self.master.activate_item(x) <NEW_LINE> event.Skip()
zorgen dat het eerder actieve item onthouden wordt, daarna het geselecteerde tot nieuw actief item benoemen
625941b8d6c5a10208143e97
def __init__(self, allowed_keys=None): <NEW_LINE> <INDENT> self.allowed_keys = allowed_keys <NEW_LINE> self._valid_values = [{0: 1}]
Validator for dictionary keys Args: allowed_keys (List): if set, all keys must be in allowed_keys
625941b8b57a9660fec336d0
def game_loop(self): <NEW_LINE> <INDENT> while self.run: <NEW_LINE> <INDENT> self.cleanup_wait_thread() <NEW_LINE> if not self.msgs: <NEW_LINE> <INDENT> self.recv_msgs() <NEW_LINE> <DEDENT> msg = self.get_msg() <NEW_LINE> while msg: <NEW_LINE> <INDENT> self.process_msg(msg) <NEW_LINE> msg = self.get_msg()
Main loop. Receives messages, and processes them in order.
625941b8cc0a2c11143dcce8
@connect_on_app_finalize <NEW_LINE> def add_unlock_chord_task(app): <NEW_LINE> <INDENT> from celery.canvas import maybe_signature <NEW_LINE> from celery.exceptions import ChordError <NEW_LINE> from celery.result import allow_join_result, result_from_tuple <NEW_LINE> default_propagate = app.conf.chord_propagates <NEW_LINE> @app.task(name='celery.chord_unlock', max_retries=None, shared=False, default_retry_delay=1, ignore_result=True, lazy=False, bind=True) <NEW_LINE> def unlock_chord(self, group_id, callback, interval=None, propagate=None, max_retries=None, result=None, Result=app.AsyncResult, GroupResult=app.GroupResult, result_from_tuple=result_from_tuple): <NEW_LINE> <INDENT> propagate = default_propagate if propagate is None else propagate <NEW_LINE> if interval is None: <NEW_LINE> <INDENT> interval = self.default_retry_delay <NEW_LINE> <DEDENT> callback = maybe_signature(callback, app) <NEW_LINE> deps = GroupResult( group_id, [result_from_tuple(r, app=app) for r in result], app=app, ) <NEW_LINE> j = deps.join_native if deps.supports_native_join else deps.join <NEW_LINE> try: <NEW_LINE> <INDENT> ready = deps.ready() <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> raise self.retry( exc=exc, countdown=interval, max_retries=max_retries, ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not ready: <NEW_LINE> <INDENT> raise self.retry(countdown=interval, max_retries=max_retries) <NEW_LINE> <DEDENT> <DEDENT> callback = maybe_signature(callback, app=app) <NEW_LINE> try: <NEW_LINE> <INDENT> with allow_join_result(): <NEW_LINE> <INDENT> ret = j(timeout=3.0, propagate=propagate) <NEW_LINE> <DEDENT> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> culprit = next(deps._failed_join_report()) <NEW_LINE> reason = 'Dependency {0.id} raised {1!r}'.format( culprit, exc, ) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> reason = repr(exc) <NEW_LINE> <DEDENT> logger.error('Chord %r raised: %r', group_id, exc, exc_info=1) <NEW_LINE> app.backend.chord_error_from_stack(callback, ChordError(reason)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> callback.delay(ret) <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> logger.error('Chord %r raised: %r', group_id, exc, exc_info=1) <NEW_LINE> app.backend.chord_error_from_stack( callback, exc=ChordError('Callback error: {0!r}'.format(exc)), ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return unlock_chord
This task is used by result backends without native chord support. It joins chords by creating a task chain polling the header for completion.
625941b80a50d4780f666cdf
def _get_subproduct_factor(self, cr, uid, production_id, move_id=None, context=None): <NEW_LINE> <INDENT> return 1
Compute the factor to compute the qty of procucts to produce for the given production_id. By default, it's always equal to the quantity encoded in the production order or the production wizard, but if the module mrp_subproduct is installed, then we must use the move_id to identify the product to produce and its quantity. :param production_id: ID of the mrp.order :param move_id: ID of the stock move that needs to be produced. Will be used in mrp_subproduct. :return: The factor to apply to the quantity that we should produce for the given production order.
625941b863d6d428bbe4433f
def patch(self, pk, **kwargs): <NEW_LINE> <INDENT> args = '{}={}'.format(*kwargs.items()[0]) <NEW_LINE> for key, value in kwargs.items()[1:]: <NEW_LINE> <INDENT> args = '{}&{}={}'.format(args, key, value) <NEW_LINE> <DEDENT> return json.loads( self.conn.patch('{}/{}'.format(self.forms_ep, pk), None, args).text)
Update Form Properties
625941b8adb09d7d5db6c5e3
def has_property_value(self, property, value, name=None): <NEW_LINE> <INDENT> if name is None: <NEW_LINE> <INDENT> name = self._name + ".has_property_value({0}, {1})" .format(repr(property), repr(value)) <NEW_LINE> <DEDENT> return HasPropertyValue(name, property, value, self.datasources.entity)
Returns True if the specified property matches the provided value. :Parameters: property : `str` The name of a property (usually preceeded by "P") value : `mixed` The value to match name : `str` A name to associate with the Feature. If not set, the feature's name will be 'has_property_value(<property>, <value>)'
625941b85f7d997b871748eb
def testParseName(self): <NEW_LINE> <INDENT> value = "_test" <NEW_LINE> self.assertEqual(parseName(value, '_'), 'test') <NEW_LINE> value = "____test____" <NEW_LINE> self.assertEqual(parseName(value, '_'), '___test____') <NEW_LINE> self.assertEqual(parseName(value, '___'), '_test____') <NEW_LINE> self.assertEqual(parseName(value, 'test'), '____test____') <NEW_LINE> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> parseName(value, None) <NEW_LINE> <DEDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> parseName(None, '_') <NEW_LINE> <DEDENT> value = [] <NEW_LINE> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> parseName(value, '_') <NEW_LINE> <DEDENT> value = 1.44 <NEW_LINE> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> parseName(value, 'p') <NEW_LINE> <DEDENT> value = 100 <NEW_LINE> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> parseName(value, 'p')
test parse out a string from the beinning of a string
625941b894891a1f4081b8f8
def maxArea(self, height): <NEW_LINE> <INDENT> ans=0 <NEW_LINE> vol=0 <NEW_LINE> for i in range(len(height)): <NEW_LINE> <INDENT> for j in range(i+1,len(height)): <NEW_LINE> <INDENT> vol=min(height[i],height[j])*(j-i) <NEW_LINE> ans=max(ans,vol) <NEW_LINE> <DEDENT> <DEDENT> return ans
:type height: List[int] :rtype: int
625941b855399d3f05588503
def delete(self, model_id): <NEW_LINE> <INDENT> self.running_models.pop(model_id, None)
Delete the model whose ID matches ``model_id``. Using a model_id that does not exist in running_models is a no-op.
625941b8656771135c3eb6c2
def test_unadjusted_minutes_early_close(self): <NEW_LINE> <INDENT> day_before_thanksgiving = Timestamp('2015-11-25', tz='UTC') <NEW_LINE> xmas_eve = Timestamp('2015-12-24', tz='UTC') <NEW_LINE> market_day_after_xmas = Timestamp('2015-12-28', tz='UTC') <NEW_LINE> minutes = [self.market_closes[day_before_thanksgiving] - Timedelta('2 min'), self.market_closes[xmas_eve] - Timedelta('1 min'), self.market_opens[market_day_after_xmas] + Timedelta('1 min')] <NEW_LINE> sids = [1, 2] <NEW_LINE> data_1 = DataFrame( data={ 'open': [ 15.0, 15.1, 15.2], 'high': [17.0, 17.1, 17.2], 'low': [11.0, 11.1, 11.3], 'close': [14.0, 14.1, 14.2], 'volume': [1000, 1001, 1002], }, index=minutes) <NEW_LINE> self.writer.write(sids[0], data_1) <NEW_LINE> data_2 = DataFrame( data={ 'open': [25.0, 25.1, 25.2], 'high': [27.0, 27.1, 27.2], 'low': [21.0, 21.1, 21.2], 'close': [24.0, 24.1, 24.2], 'volume': [2000, 2001, 2002], }, index=minutes) <NEW_LINE> self.writer.write(sids[1], data_2) <NEW_LINE> reader = BcolzMinuteBarReader(self.dest) <NEW_LINE> columns = ['open', 'high', 'low', 'close', 'volume'] <NEW_LINE> sids = [sids[0], sids[1]] <NEW_LINE> arrays = reader.unadjusted_window( columns, minutes[0], minutes[-1], sids) <NEW_LINE> data = {sids[0]: data_1, sids[1]: data_2} <NEW_LINE> start_minute_loc = self.env.market_minutes.get_loc(minutes[0]) <NEW_LINE> minute_locs = [self.env.market_minutes.get_loc(minute) - start_minute_loc for minute in minutes] <NEW_LINE> for i, col in enumerate(columns): <NEW_LINE> <INDENT> for j, sid in enumerate(sids): <NEW_LINE> <INDENT> assert_almost_equal(data[sid].loc[minutes, col], arrays[i][j][minute_locs])
Test unadjusted minute window, ensuring that early closes are filtered out.
625941b826238365f5f0ecb9
def GetPath(self): <NEW_LINE> <INDENT> return self.path
Get the xml files path @return: string
625941b8460517430c393fde
def __init__(self, system_owned=None, display_name=None, description=None, tags=None, create_user=None, protection=None, create_time=None, last_modified_time=None, last_modified_user=None, id=None, resource_type=None, datasources=None, weight=None, icons=None, shared=None, footer=None, drilldown_id=None, is_drilldown=False, legend=None, *args, **kwargs): <NEW_LINE> <INDENT> self._system_owned = None <NEW_LINE> self._display_name = None <NEW_LINE> self._description = None <NEW_LINE> self._tags = None <NEW_LINE> self._create_user = None <NEW_LINE> self._protection = None <NEW_LINE> self._create_time = None <NEW_LINE> self._last_modified_time = None <NEW_LINE> self._last_modified_user = None <NEW_LINE> self._id = None <NEW_LINE> self._resource_type = None <NEW_LINE> self._datasources = None <NEW_LINE> self._weight = None <NEW_LINE> self._icons = None <NEW_LINE> self._shared = None <NEW_LINE> self._footer = None <NEW_LINE> self._drilldown_id = None <NEW_LINE> self._is_drilldown = None <NEW_LINE> self._legend = None <NEW_LINE> self.discriminator = 'resource_type' <NEW_LINE> if system_owned is not None: <NEW_LINE> <INDENT> self.system_owned = system_owned <NEW_LINE> <DEDENT> if display_name is not None: <NEW_LINE> <INDENT> self.display_name = display_name <NEW_LINE> <DEDENT> if description is not None: <NEW_LINE> <INDENT> self.description = description <NEW_LINE> <DEDENT> if tags is not None: <NEW_LINE> <INDENT> self.tags = tags <NEW_LINE> <DEDENT> if create_user is not None: <NEW_LINE> <INDENT> self.create_user = create_user <NEW_LINE> <DEDENT> if protection is not None: <NEW_LINE> <INDENT> self.protection = protection <NEW_LINE> <DEDENT> if create_time is not None: <NEW_LINE> <INDENT> self.create_time = create_time <NEW_LINE> <DEDENT> if last_modified_time is not None: <NEW_LINE> <INDENT> self.last_modified_time = last_modified_time <NEW_LINE> <DEDENT> if last_modified_user is not None: <NEW_LINE> <INDENT> self.last_modified_user = last_modified_user <NEW_LINE> <DEDENT> if id is not None: <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <DEDENT> self.resource_type = resource_type <NEW_LINE> if datasources is not None: <NEW_LINE> <INDENT> self.datasources = datasources <NEW_LINE> <DEDENT> if weight is not None: <NEW_LINE> <INDENT> self.weight = weight <NEW_LINE> <DEDENT> if icons is not None: <NEW_LINE> <INDENT> self.icons = icons <NEW_LINE> <DEDENT> if shared is not None: <NEW_LINE> <INDENT> self.shared = shared <NEW_LINE> <DEDENT> if footer is not None: <NEW_LINE> <INDENT> self.footer = footer <NEW_LINE> <DEDENT> if drilldown_id is not None: <NEW_LINE> <INDENT> self.drilldown_id = drilldown_id <NEW_LINE> <DEDENT> if is_drilldown is not None: <NEW_LINE> <INDENT> self.is_drilldown = is_drilldown <NEW_LINE> <DEDENT> if legend is not None: <NEW_LINE> <INDENT> self.legend = legend <NEW_LINE> <DEDENT> ManagedResource.__init__(self, *args, **kwargs)
WidgetConfiguration - a model defined in Swagger
625941b88e05c05ec3eea1c1
def test_closeness_centrality(): <NEW_LINE> <INDENT> g = GeneralGraph() <NEW_LINE> g.load("tests/TOY_graph.csv") <NEW_LINE> closeness_centrality = { '1': 0.0, '2': 0.05555555555555555, '3': 0.05555555555555555, '4': 0.07407407407407407, '5': 0.07407407407407407, '6': 0.1736111111111111, '7': 0.11574074074074076, '8': 0.11574074074074076, '9': 0.14327485380116958, '10': 0.12077294685990338, '11': 0.17386831275720163, '12': 0.1866925064599483, '13': 0.16055555555555556, '14': 0.1866925064599483, '15': 0.0, '16': 0.16071428571428573, '17': 0.125, '18': 0.17307692307692307, '19': 0.22299382716049382 } <NEW_LINE> np.testing.assert_array_almost_equal( np.asarray(sorted(closeness_centrality.values())), np.asarray(sorted(g.closeness_centrality.values())), err_msg="CLOSENESS CENTRALITY failure")
The following test checks closeness centrality before any perturbation.
625941b8d10714528d5ffb2f
def report(): <NEW_LINE> <INDENT> print(report_formatter(order_donations(donors)))
Gets the aggregate donations sorted by descending aggregate donations and formats them into a report
625941b8a17c0f6771cbdea4
def dog_detector_from_path(img_path): <NEW_LINE> <INDENT> prediction = ResNet50_predict_labels_from_path(img_path) <NEW_LINE> return ((prediction <= 268) & (prediction >= 151))
returns "True" if a dog is detected in the image stored at img_path
625941b8a79ad161976cbf96
def test_ShackHartmannWFS(n_lenslets=2): <NEW_LINE> <INDENT> wavelength = 635*u.nm <NEW_LINE> shwfs = sub_sampled_optics.ShackHartmannWavefrontSensor(n_lenslets=n_lenslets) <NEW_LINE> dm_size = shwfs.lenslet_pitch*24 <NEW_LINE> wf_flat = poppy.Wavefront(diam=dm_size, wavelength=wavelength, npix=int((shwfs.lenslet_pitch/shwfs.pixel_pitch).value*shwfs.n_lenslets*2)) <NEW_LINE> wf_flat *= poppy.CircularAperture(radius = dm_size/2) <NEW_LINE> shwfs.sample_wf(wf_flat) <NEW_LINE> shwfs.get_psfs() <NEW_LINE> flat_centroid_list = shwfs.get_centroids() <NEW_LINE> act_x = 2 <NEW_LINE> act_y = 2 <NEW_LINE> stroke = .3e-6 <NEW_LINE> dm_actuator_pitch = dm_size/4 <NEW_LINE> dm = poppy.dms.ContinuousDeformableMirror(dm_shape=(4,4), actuator_spacing=dm_actuator_pitch, radius=dm_size/2, include_factor_of_two = True) <NEW_LINE> dm.set_actuator(act_x, act_y, stroke) <NEW_LINE> wf = poppy.Wavefront(diam=dm_size, wavelength=wavelength, npix=int((shwfs.lenslet_pitch/shwfs.pixel_pitch).value*shwfs.n_lenslets*2)) <NEW_LINE> wf *= poppy.CircularAperture(radius = dm_size/2) <NEW_LINE> wf *= dm <NEW_LINE> shwfs.sample_wf(wf) <NEW_LINE> shwfs.get_psfs() <NEW_LINE> reconstruction = shwfs.reconstruct_wavefront(flat_centroid_list).value <NEW_LINE> assert np.count_nonzero(reconstruction)>0, "Wavefront reconstruction was not non-zero as expected for input DM actuation" <NEW_LINE> return np.count_nonzero(reconstruction)>0
Test Shack Hartmann Wavefront Sensor class functionality. Verifies that spot centroid measurement changes when optical system reflects off a deformed mirror Parameters ---------- n_lenslets = 2 n_lenslets parameter for ShackHartmannWavefrontSensor; the number of lenslets per side of a square grid.
625941b8dd821e528d63affb
def find_process_group(process_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> group_id = os.getpgid(process_id) <NEW_LINE> logging.info('Process (pid: {}) belongs to group (id: {})'.format(process_id, group_id)) <NEW_LINE> return group_id <NEW_LINE> <DEDENT> except ProcessLookupError: <NEW_LINE> <INDENT> logging.info('Unable to find group for process (pid: {})'.format(process_id)) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> logging.exception('Error in finding group for process (pid: {})'.format(process_id))
Return the process group id of the process with process id process_id. Parameters ---------- process_id: int The process id. Returns ------- The process group id of the process with process id process_id or None.
625941b89f2886367277a6e1
def get_surface_storage(self, comid, upcomids = [], tstep = 'daily', dates = None): <NEW_LINE> <INDENT> comids = self.get_upstream_comids(comid, upcomids = upcomids) <NEW_LINE> surss = self.get_subbasin_timeseries(['SURS'], comids, dates = dates) <NEW_LINE> areas = self.get_subbasin_areas(comids) <NEW_LINE> times = self.get_timeseries(tstep = 'daily', dates = dates) <NEW_LINE> surs = sum([s * a for s, a in zip(surss, areas)]) / sum(areas) <NEW_LINE> if tstep == 'monthly': <NEW_LINE> <INDENT> times, surs = self.aggregate_daily_monthly(times, surs, option = 'average') <NEW_LINE> <DEDENT> elif tstep != 'daily': <NEW_LINE> <INDENT> print('Warning: unknown time step specified for surface runoff') <NEW_LINE> return <NEW_LINE> <DEDENT> return times, surs
Returns a timeseries of surface storage for the area. Note this assumes a daily dataset in the WDM file for storage.
625941b8596a89723608991a
def load_environment(global_conf, app_conf): <NEW_LINE> <INDENT> root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) <NEW_LINE> paths = dict(root=root, controllers=os.path.join(root, 'controllers'), static_files=os.path.join(root, 'public'), templates=[os.path.join(root, 'templates')]) <NEW_LINE> config.init_app(global_conf, app_conf, package='calypso', paths=paths) <NEW_LINE> config['routes.map'] = make_map() <NEW_LINE> config['pylons.app_globals'] = app_globals.Globals() <NEW_LINE> config['pylons.h'] = calypso.lib.helpers <NEW_LINE> config['pylons.app_globals'].mako_lookup = TemplateLookup( directories=paths['templates'], error_handler=handle_mako_error, module_directory=os.path.join(app_conf['cache_dir'], 'templates'), input_encoding='utf-8', default_filters=['escape'], imports=['from webhelpers.html import escape']) <NEW_LINE> engine = engine_from_config(config, 'sqlalchemy.') <NEW_LINE> init_model(engine)
Configure the Pylons environment via the ``pylons.config`` object
625941b8c4546d3d9de72880
def warning(format, ): <NEW_LINE> <INDENT> utils.lib.zsys_warning(utils.to_bytes(format), )
Log warning condition - high priority
625941b832920d7e50b2801c
def update_routing_table(self, routes): <NEW_LINE> <INDENT> for route in routes: <NEW_LINE> <INDENT> if not self.is_neighbor(route.src): <NEW_LINE> <INDENT> print("update_routing_table: The entry does not come from its directly-connected neighbor!") <NEW_LINE> print("wrong route:", str(route)) <NEW_LINE> continue <NEW_LINE> <DEDENT> if not self.is_valid_router_id(route.neighbor): <NEW_LINE> <INDENT> print("update_routing_table: wrong neighbor router id") <NEW_LINE> print("wrong route:", str(route)) <NEW_LINE> continue <NEW_LINE> <DEDENT> if not self.is_valid_router_id(route.dest): <NEW_LINE> <INDENT> print("update_routing_table: wrong destinated router id") <NEW_LINE> print("wrong route:", str(route)) <NEW_LINE> continue <NEW_LINE> <DEDENT> if not self.is_valid_metric(route.metric): <NEW_LINE> <INDENT> print("update_routing_table: wrong metric value") <NEW_LINE> print("wrong route:", str(route)) <NEW_LINE> continue <NEW_LINE> <DEDENT> if route.dest == self.id: <NEW_LINE> <INDENT> if route.neighbor == self.id: <NEW_LINE> <INDENT> route_in_routing_table = self.get_route_destinating_to(route.src) <NEW_LINE> if route_in_routing_table == None: <NEW_LINE> <INDENT> self.add_new_route(route.src, route.src, route.metric) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if route_in_routing_table.neighbor == route.src: <NEW_LINE> <INDENT> if route.metric != INFINITE_METRIC: <NEW_LINE> <INDENT> route_in_routing_table.metric = route.metric <NEW_LINE> self.reset_timeout_timer(route.src, route.src) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if route.metric < route_in_routing_table.metric: <NEW_LINE> <INDENT> route_in_routing_table.neighbor = route.src <NEW_LINE> route_in_routing_table.metric = route.metric <NEW_LINE> self.reset_timeout_timer(route.src, route.dest) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> continue <NEW_LINE> <DEDENT> metric_to_neighbor = self.get_metric_to_neighbor(route.src) <NEW_LINE> metric = min(metric_to_neighbor + route.metric, INFINITE_METRIC) <NEW_LINE> route_in_routing_table = self.get_route_destinating_to(route.dest) <NEW_LINE> if route_in_routing_table == None: <NEW_LINE> <INDENT> if metric != INFINITE_METRIC: <NEW_LINE> <INDENT> self.add_new_route(route.src, route.dest, metric) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if route_in_routing_table.neighbor == route.src: <NEW_LINE> <INDENT> if route_in_routing_table.metric != INFINITE_METRIC: <NEW_LINE> <INDENT> route_in_routing_table.metric = metric <NEW_LINE> if metric == INFINITE_METRIC: <NEW_LINE> <INDENT> self.activate_triggered_updates_timer() <NEW_LINE> self.activate_garbage_collection_timer(route_in_routing_table.neighbor, route_in_routing_table.dest) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.reset_timeout_timer(route.src, route.dest) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if metric < route_in_routing_table.metric: <NEW_LINE> <INDENT> route_in_routing_table.neighbor = route.src <NEW_LINE> route_in_routing_table.metric = metric <NEW_LINE> self.reset_timeout_timer(route.src, route.dest) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> self.print_routing_table()
Update routring table entries. If there is new route, add it. If the existed metric can be updated, update it.
625941b8bde94217f3682c4c
def subtest_4(ctx): <NEW_LINE> <INDENT> symlink = ctx.pointless() + ctx.termslash() <NEW_LINE> f = ctx.no_file() + ctx.termslash() <NEW_LINE> ctx.open_file(symlink, rw=1, err=ENOENT) <NEW_LINE> ctx.open_file(f, ro=1, err=ENOENT)
Open(broken) O_RDWR
625941b84f88993c3716bec4
def conv2d(x: AbstractTensor, y: AbstractTensor, stride, padding) -> AbstractTensor: <NEW_LINE> <INDENT> with tf.name_scope('conv2d'): <NEW_LINE> <INDENT> h_filter, w_filter, _, n_filters = map(int, y.shape) <NEW_LINE> n_x, _, h_x, w_x = map(int, x.shape) <NEW_LINE> if padding == 'SAME': <NEW_LINE> <INDENT> h_out = int(math.ceil(float(h_x) / float(stride))) <NEW_LINE> w_out = int(math.ceil(float(w_x) / float(stride))) <NEW_LINE> <DEDENT> elif padding == 'VALID': <NEW_LINE> <INDENT> h_out = int(math.ceil(float(h_x - h_filter + 1) / float(stride))) <NEW_LINE> w_out = int(math.ceil(float(w_x - w_filter + 1) / float(stride))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Don't know padding method '{}'".format(padding)) <NEW_LINE> <DEDENT> x_col = x.im2col(h_filter, w_filter, padding, stride) <NEW_LINE> w_col = y.transpose([3, 2, 0, 1]).reshape([int(n_filters), -1]) <NEW_LINE> out = w_col.matmul(x_col) <NEW_LINE> out = out.reshape([n_filters, h_out, w_out, n_x]) <NEW_LINE> out = out.transpose([3, 0, 1, 2]) <NEW_LINE> return out
Generic convolution implementation with im2col over AbstractTensors.
625941b86aa9bd52df036bf2
def ansi_len(string): <NEW_LINE> <INDENT> return len(string) - wcswidth(re.compile(r'\x1b[^m]*m').sub('', string))
Extra length due to any ANSI sequences in the string.
625941b8851cf427c661a36b
def transfer_landmarks_onto(self, target): <NEW_LINE> <INDENT> from ..surface_regressor import apply_surface_regressor <NEW_LINE> from ..equality import have_same_topology <NEW_LINE> if not target.is_tri: <NEW_LINE> <INDENT> raise ValueError("Target mesh must be triangulated") <NEW_LINE> <DEDENT> if not have_same_topology(self.source_mesh, target): <NEW_LINE> <INDENT> raise ValueError("Target mesh must have the same topology") <NEW_LINE> <DEDENT> return dict( zip( self.landmarks.keys(), apply_surface_regressor(self._regressor, target.v), ) )
Transfer landmarks onto the given target mesh, which must be in the same topology as the source mesh. Args: target (lacecore.Mesh): Target mesh Returns: dict: A mapping of landmark names to a np.ndarray with shape `3x1`.
625941b8be8e80087fb20aa0
def itkDisplacementFieldJacobianDeterminantFilterIVF22D_cast(*args): <NEW_LINE> <INDENT> return _itkDisplacementFieldJacobianDeterminantFilterPython.itkDisplacementFieldJacobianDeterminantFilterIVF22D_cast(*args)
itkDisplacementFieldJacobianDeterminantFilterIVF22D_cast(itkLightObject obj) -> itkDisplacementFieldJacobianDeterminantFilterIVF22D
625941b856b00c62f0f144ae
def get_vertical_height(self, text, font_size): <NEW_LINE> <INDENT> self.draw.font = self.get_font(font_size) <NEW_LINE> size = 0 <NEW_LINE> for character in text: <NEW_LINE> <INDENT> size += self.draw.font.getsize(character)[1] <NEW_LINE> <DEDENT> return size
縦に並べた際の文字の高さを取得する :param text: :param font_size: :return:
625941b8956e5f7376d70ccb
@app.route('/slack/commands', methods=['POST']) <NEW_LINE> def slack_slash_commands(): <NEW_LINE> <INDENT> raw_data = flask.request.get_data() <NEW_LINE> if not verify_slack_request( flask.request.headers['X-Slack-Signature'], flask.request.headers['X-Slack-Request-Timestamp'], raw_data.decode('utf-8'), ): <NEW_LINE> <INDENT> return flask.Response(status=400) <NEW_LINE> <DEDENT> text = flask.request.form['text'] <NEW_LINE> if len(text) == 0: <NEW_LINE> <INDENT> return flask.jsonify({ "response_type": "ephemeral", "text": "I need a subcommand!\n```{}```".format(textwrap.dedent(slack_slash_commands.__doc__)) }) <NEW_LINE> <DEDENT> parts = text.split(' ') <NEW_LINE> command = parts[0] <NEW_LINE> args = parts[1:] <NEW_LINE> if command == 'watch': <NEW_LINE> <INDENT> if len(args) != 3: <NEW_LINE> <INDENT> return flask.jsonify({ "response_type": "ephemeral", "text": "Please use a format like `tuolumne DD/MM/YY <length>`." }) <NEW_LINE> <DEDENT> campground, start, length = args <NEW_LINE> try: <NEW_LINE> <INDENT> date = arrow.get(start, 'DD/MM/YY') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return flask.jsonify({ "response_type": "ephemeral", "text": "Could not parse your date, please use a DD/MM/YY format.", }) <NEW_LINE> <DEDENT> if date.format('DD/MM/YY') != start: <NEW_LINE> <INDENT> return flask.jsonify({ "response_type": "ephemeral", "text": "Could not parse your date, please use a DD/MM/YY format.", }) <NEW_LINE> <DEDENT> user_id = flask.request.form['user_id'] <NEW_LINE> return add_watcher(user_id, campground, start, int(length)) <NEW_LINE> <DEDENT> elif command == 'list': <NEW_LINE> <INDENT> return slack_list_watchers(flask.request.form['user_id']) <NEW_LINE> <DEDENT> elif command == 'list-all': <NEW_LINE> <INDENT> return slack_list_watchers() <NEW_LINE> <DEDENT> elif command == 'campgrounds': <NEW_LINE> <INDENT> return slack_list_campgrounds(args) <NEW_LINE> <DEDENT> elif command == 'help': <NEW_LINE> <INDENT> return flask.jsonify({ "response_type": "ephemeral", "text": "```{}```".format(textwrap.dedent(slack_slash_commands.__doc__)) }) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return flask.jsonify({ "response_type": "ephemeral", "text": "I haven't been implemented yet!", })
Handles responding to slash commands for reservations. Commands: /crush watch <campground-tag> <DD/MM/YY> <length> ------------------------------------------------------ Registers a new watcher for a reservation. This will begin a periodic scraping process against the recreation.gov website. When succesful we'll send you a slack message with results. Campgrounds are selected according to `campground-tag` you provide. The bot will attempt to find sites within any campground that matches the tag you provide. To list campgrounds and their tags, use the `campgrounds` command. /crush list ---------------------- Lists active watchers for the current user. /crush list-all ---------------------- Lists active watchers for all users. /crush campgrounds [tags...] ------------------ Lists known campgrounds, optionally filtered by those that match any of the provided tags. For example, if you wish to list what the bot considers a 'yosemite-valley' campground use `/crush campgrounds yosemite-valley`. Syntax: - Square brackets, as in `[param]`, denote optional parameters. - Angle brackets, as in `<param>`, denote required parameters. - Ellipsis, `...` following a parameter denote a space-separated list.
625941b8ab23a570cc24ffd0
def _trustedPeerLoginFailed(self, result, request): <NEW_LINE> <INDENT> return HTTPAuthResource.authenticate(self, request)
If the peer is not trusted, fallback to HTTP basic/digest authentication.
625941b8d164cc6175782b9e
def _store_array(self): <NEW_LINE> <INDENT> if self._mat_u is None: <NEW_LINE> <INDENT> self._mat_u = self.to_sparse_array().toarray()
Stores the matrix with counted time points in memory.
625941b8cdde0d52a9e52e7f
def create_folder(self, folder): <NEW_LINE> <INDENT> typ, data = self._imap.create(self._encode_folder_name(folder)) <NEW_LINE> self._checkok('create', typ, data) <NEW_LINE> return data[0]
Create a new folder on the server. @param folder: The folder name. @return: Server response.
625941b81d351010ab85596e
def onXYStagePositionChanged(self, *args): <NEW_LINE> <INDENT> return _MMCorePy.MMEventCallback_onXYStagePositionChanged(self, *args)
onXYStagePositionChanged(self, char name, double xpos, double ypos) Parameters: self: MMEventCallback * value name: char * value xpos: double value ypos: double value name: char * value xpos: double value ypos: double value
625941b8d10714528d5ffb30
def get(self, entry: DNSEntry) -> Optional[DNSRecord]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> list_ = self.cache[entry.key] <NEW_LINE> for cached_entry in list_: <NEW_LINE> <INDENT> if entry.__eq__(cached_entry): <NEW_LINE> <INDENT> return cached_entry <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> except (KeyError, ValueError): <NEW_LINE> <INDENT> return None
Gets an entry by key. Will return None if there is no matching entry.
625941b8435de62698dfdaa5
def get_nationality(nation): <NEW_LINE> <INDENT> with codecs.open("nationalities.txt", "r", "utf-8") as f: <NEW_LINE> <INDENT> nationalities = {} <NEW_LINE> for x in f.readlines(): <NEW_LINE> <INDENT> nationalities[x.strip().lower().split(',')[1]] = x.strip().lower().split(',')[0] <NEW_LINE> <DEDENT> <DEDENT> result = nation <NEW_LINE> for key,val in nationalities.items(): <NEW_LINE> <INDENT> if nation == key: <NEW_LINE> <INDENT> result = val <NEW_LINE> <DEDENT> <DEDENT> return result
Test id a word is a nationality adjective
625941b810dbd63aa1bd2a00
def display(self): <NEW_LINE> <INDENT> for r in range(1, 4): <NEW_LINE> <INDENT> print("+-+-+-+") <NEW_LINE> print("|", end="") <NEW_LINE> for c in range(1, 3): <NEW_LINE> <INDENT> print(self.gameState[r,c], end="") <NEW_LINE> print("|",end="") <NEW_LINE> <DEDENT> print(self.gameState[r,3], end="") <NEW_LINE> print("|") <NEW_LINE> <DEDENT> print("+-+-+-+")
A pleasant view of the current game state :return: nothing
625941b8ab23a570cc24ffd1
def isHangulLetter(S): <NEW_LINE> <INDENT> if isPrecomposedSyllable(S): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if isHangulJamo(S): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if isCompatibilityLetter(S): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if isParenthesizedLetter(S): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if isCircledLetter(S): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if isHalfwidthLetter(S): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Check S is a Hanggul-related character. :param char S Single character string
625941b86fece00bbac2d58c
def test_li_attr(): <NEW_LINE> <INDENT> con = "This is the second item" <NEW_LINE> li = Li(con, style="color: red") <NEW_LINE> file_contents = render_result(li) <NEW_LINE> print(file_contents) <NEW_LINE> assert '<li style="color: red">\n' in file_contents
a li with an attribute
625941b8d7e4931a7ee9dd6d
def name_of_month(month:int) -> str: <NEW_LINE> <INDENT> dct_month = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'Jule', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'} <NEW_LINE> return dct_month[month]
Возвращает название месяца согласно номеру
625941b8e1aae11d1e749b05
def ca(classLabels): <NEW_LINE> <INDENT> nCorrect = 0 <NEW_LINE> nTotal = 0 <NEW_LINE> for trueLabel, foundLabels in enumerate(classLabels): <NEW_LINE> <INDENT> foundLabels = np.asarray(foundLabels) <NEW_LINE> nCorrect += np.sum(foundLabels == trueLabel) <NEW_LINE> nTotal += len(foundLabels) <NEW_LINE> <DEDENT> return nCorrect/float(nTotal)
Compute the classification accuracy using predicted class labels with known true labels. Args: classLabels: A list with length equal to the number of classes with one element per class. Each element of this list contains a list of predictec class labels. Returns: Scalar classification accuracy as the fraction of correct labels over incorrect labels. Multiply by 100 to get percent correct.
625941b8dc8b845886cb5386
def _cmidrule(colindex, dataset_width): <NEW_LINE> <INDENT> rule = '\\cmidrule(%s){%d-%d}' <NEW_LINE> if colindex == 1: <NEW_LINE> <INDENT> return rule % ('r', colindex, colindex) <NEW_LINE> <DEDENT> if colindex == dataset_width: <NEW_LINE> <INDENT> return rule % ('l', colindex, colindex) <NEW_LINE> <DEDENT> return rule % ('lr', colindex, colindex)
Generates the `cmidrule` for a single column with appropriate trimming based on the column position. :param colindex: Column index :param dataset_width: width of the dataset
625941b8d486a94d0b98df9f