code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@app.route('/index.json', methods=['GET']) <NEW_LINE> @app.route('/', methods=['GET']) <NEW_LINE> @autodoc(['home', 'api']) <NEW_LINE> def home(): <NEW_LINE> <INDENT> workspace = get_workspace_details(flask.request.url) <NEW_LINE> running_datasets = get_job_list(dataset.DatasetJob, True, workspace['workspace_id']) <...
DIGITS home page Returns information about each job on the server Returns JSON when requested: { datasets: [{id, name, status},...], models: [{id, name, status},...] }
625941ed85dfad0860c3b396
def get_kfold_data(self): <NEW_LINE> <INDENT> allX = [] <NEW_LINE> ally = [] <NEW_LINE> for evidence, score in self.labeled_evidence.items(): <NEW_LINE> <INDENT> allX.append(evidence) <NEW_LINE> ally.append(int(score)) <NEW_LINE> assert ally[-1] in (True, False) <NEW_LINE> <DEDENT> allX = numpy.array(allX) <NEW_LINE> a...
Perform k-fold cross validation and return (scores, y_true) where scores is a numpy array with decision function scores and y_true is a numpy array with the true label for that evidence.
625941ed5f7d997b87174fd6
def get_page_scale(page_obj): <NEW_LINE> <INDENT> width = page_obj.mediaBox.getUpperRight_x() - page_obj.mediaBox.getLowerLeft_x() <NEW_LINE> height = page_obj.mediaBox.getUpperRight_y() - page_obj.mediaBox.getLowerLeft_y() <NEW_LINE> return width, height
获取页面大小 :param page_obj: :return:
625941ed57b8e32f524839d8
def WriteFromPkl(hdf5_file, movie_file, type_of_movie): <NEW_LINE> <INDENT> base = movie_file.split(".")[0] <NEW_LINE> pkl_file = ''.join([base, ".pkl"]) <NEW_LINE> ex = Extractor(pkl_file) <NEW_LINE> with h5.File(hdf5_file, 'a') as f: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> grp = f.create_group("{}/{}".format(typ...
After calling annotate, this function takes the pickled file and transforms it to hdf5. This function actually reads the video chunks that specified in the pickled file and writes that region. hdf5_file - The file to be written movie_file - The file from which to grab image cubes (the.pkl file must also be there). t...
625941edd18da76e23532a16
def validate(config): <NEW_LINE> <INDENT> vstatus = True <NEW_LINE> vmsg = "Valid beacon configuration" <NEW_LINE> if not isinstance(config, list): <NEW_LINE> <INDENT> vstatus = False <NEW_LINE> vmsg = "Configuration for wtmp beacon must be a list." <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> config = salt.utils.beac...
Validate the beacon configuration
625941ed23849d37ff7b35c5
def get_folders(self, project, path=None, query_order=None): <NEW_LINE> <INDENT> route_values = {} <NEW_LINE> if project is not None: <NEW_LINE> <INDENT> route_values['project'] = self._serialize.url('project', project, 'str') <NEW_LINE> <DEDENT> if path is not None: <NEW_LINE> <INDENT> route_values['path'] = self._ser...
GetFolders. [Preview API] Gets folders :param str project: Project ID or project name :param str path: :param str query_order: :rtype: [Folder]
625941ed3d592f4c4ed1d598
def all_jwt_signature_key_template_names() -> Iterable[str]: <NEW_LINE> <INDENT> for key_type in supported_key_types.JWT_SIGNATURE_KEY_TYPES: <NEW_LINE> <INDENT> for key_template_name in supported_key_types.KEY_TEMPLATE_NAMES[key_type]: <NEW_LINE> <INDENT> yield key_template_name
Yields all JWT signature key template names.
625941ed236d856c2ad44d1c
@cliutils.arg( '--tenant', metavar='<tenant-id>', default=None, help=_('ID of tenant to list the quotas for.')) <NEW_LINE> @cliutils.arg( '--user', metavar='<user-id>', default=None, help=_('ID of user to list the quotas for.')) <NEW_LINE> def do_quota_show(cs, args): <NEW_LINE> <INDENT> if args.tenant: <NEW_LINE> <IND...
List the quotas for a tenant/user.
625941ed71ff763f4b549bcf
@docstring.copy_dedent(Figure.waitforbuttonpress) <NEW_LINE> def waitforbuttonpress(*args, **kwargs): <NEW_LINE> <INDENT> return gcf().waitforbuttonpress(*args, **kwargs)
Blocking call to interact with the figure. This will wait for *n* key or mouse clicks from the user and return a list containing True's for keyboard clicks and False's for mouse clicks. If *timeout* is negative, does not timeout.
625941ed76d4e153a657f06c
def convert(conversions, start, end): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> start_root, start_rate = conversions[start] <NEW_LINE> end_root, end_rate = conversions[end] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if start_root != end_root: <NEW_LINE> <INDENT> return N...
Given a conversion structure, performs a constant-time conversion
625941eda8370b7717052dd7
def load_data(path): <NEW_LINE> <INDENT> path = os.path.join(path, 'fashion-mnist') <NEW_LINE> if not os.path.exists(path): <NEW_LINE> <INDENT> os.makedirs(path) <NEW_LINE> <DEDENT> base = 'http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/' <NEW_LINE> files = ['train-labels-idx1-ubyte.gz', 'train-images-idx3-...
Loads the Fashion-MNIST dataset. # Returns Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
625941ed2ae34c7f2600d66a
def test_get_model_for_url__with_custom_lookup(self): <NEW_LINE> <INDENT> retrieved_object = resolution.get_model_for_url_path( "/blogslug/2022/03/28/testpostslug/" ) <NEW_LINE> self.assertEqual(retrieved_object, self.blogpost)
Reverse URL lookup with custom resolve_from_url_kwargs implementation finds the correct object.
625941edbd1bec0571d90b69
def assertBisect(self, dirblocks, split_dirblocks, path, *args, **kwargs): <NEW_LINE> <INDENT> bisect_dirblock = self.get_bisect_dirblock() <NEW_LINE> self.assertIsInstance(dirblocks, list) <NEW_LINE> bisect_split_idx = bisect_dirblock(dirblocks, path, *args, **kwargs) <NEW_LINE> split_dirblock = (path.split('/'), []) ...
Assert that bisect_split works like bisect_left on the split paths. :param dirblocks: A list of (path, [info]) pairs. :param split_dirblocks: A list of ((split, path), [info]) pairs. :param path: The path we are indexing. All other arguments will be passed along.
625941ed379a373c97cfb081
def mutate_string(string, pos, change_to): <NEW_LINE> <INDENT> string_array = list(string) <NEW_LINE> string_array[pos] = change_to <NEW_LINE> return ''.join(string_array)
Fastest way I've found to mutate a string @ 736 ns >>> mutate_string('anthony', 0, 'A') 'Anthony' :param string: :param pos: :param change_to: :return:
625941ed92d797404e3046c6
def plot_area_points(pts, cx, cy, axes=None, **kwargs): <NEW_LINE> <INDENT> if axes is None: <NEW_LINE> <INDENT> axes = ['ap', 'ct'] <NEW_LINE> <DEDENT> dtype = [(k, 'f8') for k in 'ml dv ap ct cr'.split()] <NEW_LINE> ppts = numpy.empty(len(pts), dtype=dtype) <NEW_LINE> if ('ml' in axes) or ('dv' in axes) or ('ap' in a...
Project points onto the cylinder surface then plot Parameters ---------- pts : list of 3D lists List of area points (ML, DV, AP) kwargs : dict Keyword arguments to pass on to pylab.fill See Also -------- pylab.fill
625941ed442bda511e8be94a
def callback(age, resting_heart_rate, intensity): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> age = int(age) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return 'Age must be a number' <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> resting_heart_rate = int(resting_heart_rate) <NEW_LINE> <DEDENT> except Valu...
merge input streams to produce target heart rate output
625941edac7a0e7691ed45fc
def line_intersects_grid(xxx_todo_changeme5, xxx_todo_changeme6, grid, grid_cell_size=1): <NEW_LINE> <INDENT> (x0,y0) = xxx_todo_changeme5 <NEW_LINE> (x1,y1) = xxx_todo_changeme6 <NEW_LINE> grid_cell_size = float(grid_cell_size) <NEW_LINE> x0 = x0 / grid_cell_size <NEW_LINE> x1 = x1 / grid_cell_size <NEW_LINE> y0 = y0 ...
Performs a line/grid intersection, finding the "super cover" of a line and seeing if any of the grid cells are occupied. The line runs between (x0,y0) and (x1,y1), and (0,0) is the top-left corner of the top-left grid cell. >>> line_intersects_grid((0,0),(2,2),[[0,0,0],[0,1,0],[0,0,0]]) True >>> line_intersects_grid(...
625941edfff4ab517eb2f97a
def pdf(self, value, batch_size, num_particles): <NEW_LINE> <INDENT> raise NotImplementedError
Evaluate the density of this random variable at a value. Returns Tensor/Variable [batch_size, num_particles].
625941ed10dbd63aa1bd30dc
def __rmul__(self, n): <NEW_LINE> <INDENT> return self.__mul__(n)
Returns a new vector with coordinates that are n times.
625941ed462c4b4f79d1dc09
def testSplitNSByScatter_NotEnoughData(self): <NEW_LINE> <INDENT> _create_entities(range(2), {"1": 1}) <NEW_LINE> expected = [key_range.KeyRange(key_start=None, key_end=key("1"), direction="ASC", include_start=False, include_end=False, namespace="", _app=self.appid), key_range.KeyRange(key_start=key("1"), key_end=None,...
Splits should not intersect, if there's not enough data for each.
625941ede64d504609d74d7a
def connectH(self, *args, **kwargs): <NEW_LINE> <INDENT> width = kwargs['width'] if 'width' in kwargs else 0.016 <NEW_LINE> points = [] <NEW_LINE> for A, B in zip(args[:-1], args[1:]): <NEW_LINE> <INDENT> if not isinstance(A, BoundPin): A = Point(*A) <NEW_LINE> if not isinstance(B, BoundPin): B = Point(*B) <NEW...
Connects a set of pins or points, traveling first horizontally then vertically
625941ed5e10d32532c5f45f
def get_answerback(max_bytes=32, end=(BEL, ST, '\n'), timeout=defaults.READ_TIMEOUT): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with TermStack() as fd: <NEW_LINE> <INDENT> termios.tcflush(fd, termios.TCIFLUSH) <NEW_LINE> tty.setcbreak(fd, termios.TCSANOW) <NEW_LINE> sys.stdout.write(ENQ) <NEW_LINE> sys.stdout.flush(...
Returns the "answerback" string which is often empty, None if not available. Warning: Hangs unless max_bytes is a subset of the answer string *or* an explicit end character(s) given, due to inability to find end. https://unix.stackexchange.com/a/312991/159110
625941eddc8b845886cb5a71
def test_browserlayer_removed(self): <NEW_LINE> <INDENT> from crgis.content.interfaces import ICrgisContentLayer <NEW_LINE> from plone.browserlayer import utils <NEW_LINE> self.assertNotIn( ICrgisContentLayer, utils.registered_layers())
Test that ICrgisContentLayer is removed.
625941ed442bda511e8be94b
def add_cols(self, source) : <NEW_LINE> <INDENT> cols = source.get_cols() <NEW_LINE> types = source.get_types() <NEW_LINE> new_cols = [] <NEW_LINE> new_types = [] <NEW_LINE> for i in range(len(cols)) : <NEW_LINE> <INDENT> if cols[i] not in self.cols : <NEW_LINE> <INDENT> new_cols.append(cols[i]) <NEW_LINE> new_ty...
Add columns from a source. SOURCE is any object supporting the DataTableBase interface. The values from the source are inserted into the current datatable.
625941edcb5e8a47e48b7fdc
def __init__(self, n_events=1, max_rnd_delay=1): <NEW_LINE> <INDENT> super().__init__(n_events=n_events) <NEW_LINE> self.__max_rnd_delay = max_rnd_delay
max_rnd_delay -- Maximum number of seconds for the calculation of the random delay between two events
625941ed96565a6dacc8fc03
def partition(self, arr, start, end): <NEW_LINE> <INDENT> pivot = arr[end] <NEW_LINE> pIndex = start <NEW_LINE> for i in range(start, end): <NEW_LINE> <INDENT> if arr[i] <= pivot: <NEW_LINE> <INDENT> arr[pIndex], arr[i] = arr[i], arr[pIndex] <NEW_LINE> pIndex += 1 <NEW_LINE> <DEDENT> <DEDENT> arr[end], arr[pIndex] = ar...
TODO: Docstring for partition. :arr, start, end: TODO :returns: TODO
625941ed8c0ade5d55d3eefa
def tolist(self): <NEW_LINE> <INDENT> return _math.PySparseTensor_tolist(self)
tolist(self) -> PyObject *
625941edbde94217f3683326
def moveZeroes(self, nums): <NEW_LINE> <INDENT> zero_i = 0 <NEW_LINE> for j in range(len(nums)): <NEW_LINE> <INDENT> if nums[j] != 0: <NEW_LINE> <INDENT> nums[zero_i], nums[j] = nums[j], nums[zero_i] <NEW_LINE> zero_i += 1
:type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.
625941edcc40096d61595e88
def get_attention_vector(context_vector,current_target_hidden_state,aligned_encoder_hiden_state,input_knowledge,hidden_size): <NEW_LINE> <INDENT> with tf.variable_scope("attention_vector"): <NEW_LINE> <INDENT> concat_vector = [context_vector, current_target_hidden_state, aligned_encoder_hiden_state,input_knowledge] <NE...
get attention vector by concat context vector and current target hidden state, then use feed foward layer. attention_vector=tanh(Wc[c;h]) :param context_vector: [batch_size x attn_size] :param current_target_hidden_state: [batch_size x state_size] :param aligned_encoder_hiden_state:[batch_size x hidden_size] :return ge...
625941ed7c178a314d6ef9a3
def AddColumnDefn(self, defn): <NEW_LINE> <INDENT> self.columns.append(defn) <NEW_LINE> info = wx.ListItem() <NEW_LINE> info.m_mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_FORMAT <NEW_LINE> if isinstance(defn.headerImage, basestring) and self.smallImageList is not None: <NEW_LINE> <INDENT> info.m_image = self.smallImageList...
Append the given ColumnDefn object to our list of active columns. If this method is called directly, you must also call RepopulateList() to populate the new column with data.
625941ed7b25080760e39990
def run_datacal(self, data_dir='.'): <NEW_LINE> <INDENT> in_name = self._get_temp_file() <NEW_LINE> out_name = self._get_temp_file() <NEW_LINE> f = open(data_dir + os.sep + in_name, 'w') <NEW_LINE> f.write('a\n') <NEW_LINE> f.close() <NEW_LINE> curr_dir = os.getcwd() <NEW_LINE> os.system('cd ' + data_dir + ' && ' + sel...
Executes datacal. data_dir - Where the data is found.
625941edd486a94d0b98e681
def test__url_to_search_params_times_bad_clause_2(self): <NEW_LINE> <INDENT> q = QueryDict('time1_-1=2000-023T06:00:00') <NEW_LINE> (selections, extras) = url_to_search_params(q) <NEW_LINE> self.assertIsNone(selections)
[test_search.py] url_to_search_params: bad clause 2
625941ed7d847024c06be7fb
def test_pem_null_model(force=True, **kwargs): <NEW_LINE> <INDENT> dlong = sim_test_dataset_long() <NEW_LINE> testfit = survivalstan.fit_stan_survival_model( model_cohort = 'test model', model_code = model_code, df = dlong, sample_col = 'index', timepoint_end_col = 'end_time', event_col = 'end_failure', group_col = 'se...
Test NULL survival model on flchain dataset
625941edc432627299f05184
def Meta(): <NEW_LINE> <INDENT> return _DataModel.IntegerQuantity_Meta()
Meta() -> MetaObject
625941ed4c3428357757c85f
def get_fund_info(self, sec_name): <NEW_LINE> <INDENT> sec_name = str(sec_name) <NEW_LINE> info = {} <NEW_LINE> fund_url = self.keys['url']['fund'] + '/' + sec_name <NEW_LINE> page = requests.get(fund_url) <NEW_LINE> soup = BeautifulSoup(page.content, 'html.parser') <NEW_LINE> sec_name_found = soup.find(id='sec-name') ...
A function to get basic information of a given fund. The informations are: 1. the code name of the fund 2. fund's ID in morningstar.com 3. it's feeder fund (if any) 4. the fees (e.g. purchase fee, redemption fee, management fee, etc) **This function does NOT require logging in.** Args: sec_name (str): the fund's ...
625941ed7d43ff24873a31df
def multi_numeric_plotter( data, ax=None, colors=None, total_width=0.8, single_width=1, legend=True, figsize=( 12, 8), **kwargs): <NEW_LINE> <INDENT> if ax is None: <NEW_LINE> <INDENT> fig, ax = plt.subplots(figsize=(12, 8)) <NEW_LINE> retflag = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> retflag = False <NEW_LI...
Draws a bar plot with multiple bars per data point. Parameters ---------- ax : matplotlib.pyplot.axis The axis we want to draw our plot on. data: dictionary A dictionary containing the data we want to plot. Keys are the names of the data, the items is a list of the values. Example: data = { "x":[1,2,3], "y":[1,2,3], ...
625941eda8ecb033257d3605
def _consume_single_get(response_iterator) -> firestore.BatchGetDocumentsResponse: <NEW_LINE> <INDENT> all_responses = list(response_iterator) <NEW_LINE> if len(all_responses) != 1: <NEW_LINE> <INDENT> raise ValueError( "Unexpected response from `BatchGetDocumentsResponse`", all_responses, "Expected only one result", )...
Consume a gRPC stream that should contain a single response. The stream will correspond to a ``BatchGetDocuments`` request made for a single document. Args: response_iterator (~google.cloud.exceptions.GrpcRendezvous): A streaming iterator returned from a ``BatchGetDocuments`` request. Returns: ...
625941ed63f4b57ef0001644
def to_string(self, bib_data): <NEW_LINE> <INDENT> output = io.BytesIO() <NEW_LINE> writer = _PrettyXMLWriter(output, encoding='UTF-8', header=None) <NEW_LINE> self._write(bib_data, writer) <NEW_LINE> return output.getvalue().decode('UTF-8').strip()
Return a unicode XML string without encoding declaration. >>> from pybtex.database import BibliographyData >>> data = BibliographyData() >>> unicode_xml = Writer().to_string(data) >>> isinstance(unicode_xml, six.text_type) True >>> print(unicode_xml) <bibtex:file xmlns:bibtex="http://bibtexml.sf.net/"> <BLANKLINE> </b...
625941edb7558d58953c5443
def move(self): <NEW_LINE> <INDENT> head = self._elements[0] <NEW_LINE> if not self.enlarge: <NEW_LINE> <INDENT> self._elements.pop() <NEW_LINE> <DEDENT> self._elements.insert(0, (head[0] + self.direction[0], head[1] + self.direction[1])) <NEW_LINE> self.enlarge = False
direction = (0, 1)
625941ed44b2445a339325cc
def remove_gains(visibilities,gains): <NEW_LINE> <INDENT> updated_visibilities = [] <NEW_LINE> visibilities_ind = 0 <NEW_LINE> for i in xrange(len(gains)-1): <NEW_LINE> <INDENT> for j in range(i+1,len(gains)): <NEW_LINE> <INDENT> updated_visibilities.append(visibilities[visibilities_ind] / (gains[i]*conjugate(gains[j])...
Takes the real visibilities and estimated gains and removes the gains (divides by) from the visibilities
625941edde87d2750b8602d3
def get_proposed(self): <NEW_LINE> <INDENT> if self.timeout_interval: <NEW_LINE> <INDENT> self.proposed["timeout_interval"] = self.timeout_interval <NEW_LINE> <DEDENT> if self.timeout_type: <NEW_LINE> <INDENT> self.proposed["timeout_type"] = self.timeout_type <NEW_LINE> <DEDENT> if self.type: <NEW_LINE> <INDENT> self.p...
get proposed info
625941ed30dc7b7665901e9a
def test_set_up_and_tear_down(self): <NEW_LINE> <INDENT> mock_camera = MockCamera(self.config) <NEW_LINE> self.assertFalse(mock_camera.poll()) <NEW_LINE> mock_camera.set_up() <NEW_LINE> self.assertTrue(mock_camera.poll()) <NEW_LINE> mock_camera.tear_down() <NEW_LINE> self.assertFalse(mock_camera.poll())
If the camera behaves as expected in regards to it's state: Before the set up the camera should not be usable, only after. After tear down the camera should also not be usable anymore.
625941ed38b623060ff0b327
def colStubBrowseEp(self) -> str: <NEW_LINE> <INDENT> if not self.permissionF(): return self.http403() <NEW_LINE> count = self.colClass.count() <NEW_LINE> pag = paginate.Paginator(count) <NEW_LINE> h = self.browseTem.render( colClass = self.colClass, count = count, pag = pag, table = self.browseTableH(pag), addButton =...
This is the Flask endpoint for browsing a list of documents in a collection. If the collection class is Foo, this endpoint will have the url /foo
625941ed7b180e01f3dc4d2c
def is_primitive(cell): <NEW_LINE> <INDENT> _spglib_check_cell_and_coordSys(cell) <NEW_LINE> flag = None <NEW_LINE> primCell = spglib.find_primitive(cell.get_spglib_input(), symprec=Prec._symprec) <NEW_LINE> if primCell != None: <NEW_LINE> <INDENT> vol = np.linalg.det(primCell[0]) <NEW_LINE> if abs(vol - cell.vol) < 0....
Check if the cell is primitive by its volume Args: cell (``Cell``) Returns: None, if the primitive cell is not found, often due to bad input True, if the input cell is primitve, False otherwise
625941ed627d3e7fe0d6938c
def check_b64(b64): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if (base64.b64encode(base64.b64decode(b64)) == b64): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> logging.info('not recieving base64 input') <NEW_LINE> raise Ty...
Function checks if string is base64 and not empty :param b64: base64 string :raises TypeError: if input is not base64 :raises ValueError: if input is empty
625941ed3617ad0b5ed68431
def setup_view(self): <NEW_LINE> <INDENT> model = Gtk.TreeStore(GObject.TYPE_PYOBJECT) <NEW_LINE> self.set_model(model) <NEW_LINE> column = Gtk.TreeViewColumn(None, None) <NEW_LINE> selection = Gtk.CellRendererToggle() <NEW_LINE> selection.set_property('activatable', True) <NEW_LINE> column.pack_start(selection, False)...
Setup Group View
625941ed5166f23b2e1a5694
def test_add_default_result(self): <NEW_LINE> <INDENT> response = self.client.post(self.path, self.data) <NEW_LINE> self.assertEquals(response.status_code, 200) <NEW_LINE> self.assertEquals(response.content, "Result data saved succesfully") <NEW_LINE> e = Environment.objects.get(name='bigdog') <NEW_LINE> b = Benchmark....
Add result data using default options
625941edd99f1b3c44c67abf
def test_profile_correct_context(self): <NEW_LINE> <INDENT> response = self.authorized_client.get( reverse('profile', kwargs={'username': ProfileTests.test_user.username}) ) <NEW_LINE> post_text_0 = response.context.get('page')[0].text <NEW_LINE> post_author_0 = response.context.get('page')[0].author <NEW_LINE> post_gr...
Шаблон /<username>/ сформирован с правильными контекстом.
625941ede76e3b2f99f3ad3d
def image(name, d): <NEW_LINE> <INDENT> if d is None: <NEW_LINE> <INDENT> raise Exception("Images may not be declared to be None.") <NEW_LINE> <DEDENT> if not renpy.game.context().init_phase: <NEW_LINE> <INDENT> raise Exception("Images may only be declared inside init blocks.") <NEW_LINE> <DEDENT> if not isinstance(nam...
:doc: se_images Defines an image. This function is the Python equivalent of the image statement. `name` The name of the image to display, a string. `d` The displayable to associate with that image name. This function may only be run from inside an init block. It is an error to run this function once the gam...
625941edbe8e80087fb21175
def __init__(self, msg: Any = None, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> try: <NEW_LINE> <INDENT> if isinstance(msg, (list, str)): <NEW_LINE> <INDENT> self.extend(msg) <NEW_LINE> <DEDENT> elif isinstance(msg, dict): <NEW_LINE> <INDENT> self.append(msg) <NEW_LINE> <DEDENT> <...
``msg`` 参数为要转换为 `Message` 对象的字符串、列表或字典。
625941ed6fece00bbac2dc80
def load_protobuf(batch_size): <NEW_LINE> <INDENT> _parse_all = lambda dataset: sdl.load_tfrecords(dataset, [FLAGS.box_dims, FLAGS.box_dims], tf.float16, 'box_data', tf.float32, [21], pickle_dict=(tfrecords_dir + 'filetypes_tmp_pickle.p')) <NEW_LINE> files = sdl.retreive_filelist('tfrecords', False, path=tfrecords_dir)...
Loads the protocol buffer
625941ed091ae35668667490
def search_geo(self, **params): <NEW_LINE> <INDENT> return self.get('geo/search', params=params)
Search for places that can be attached to a statuses/update. Docs: https://developer.twitter.com/en/docs/geo/places-near-location/api-reference/get-geo-search
625941ed16aa5153ce3629b3
def test_link_topic_editing_permission(link_topic): <NEW_LINE> <INDENT> principals = principals_allowed_by_permission(link_topic, "edit") <NEW_LINE> assert not principals
Ensure that nobody has edit permission on a link topic.
625941ed3c8af77a43ae3ce2
def pycomplete(s, fname=None, imports=None): <NEW_LINE> <INDENT> return _PyCompleteDocument.instance(fname).complete(s, imports)
Complete the Python expression s. If multiple completions are found, a list of possible completions (names after the last dot) is returned. If one completion is found, a list with a string containing the remaining characters is returned. If no completion is found, None is returned.
625941edc4546d3d9de72f74
def _setupStorage(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.makedirs(ROOT_STORAGE_LOCATION) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> for requiredTablesName, requiredTableColumns in REQUIRED_TABLES.items(): <NEW_LINE> <INDENT> if not self.database.tableExists(requiredTablesNa...
called to ensure the environment is ready for storage, etc.
625941ed3317a56b8693a186
def _response_handler(self, data): <NEW_LINE> <INDENT> logger.debug('CP response: 0x{0}'.format(hexlify(bytearray(data)))) <NEW_LINE> if len(data) < 1: <NEW_LINE> <INDENT> logger.warning('Received response with no data!') <NEW_LINE> return <NEW_LINE> <DEDENT> command = data[0] & 0x7F <NEW_LINE> if command == CP_ACCEL_R...
Callback invoked when a circuit playground sysex command is received.
625941ed26068e7796caf222
@app.errorhandler(400) <NEW_LINE> def bad_request(err): <NEW_LINE> <INDENT> return jsonify( {'success': False, 'err_code': 400, 'error': 'Bad request!'})
400 - Bad request error handler. Returns: str: the json representation of the error
625941ed07d97122c4178dd3
def __init__(self, script=None, id=None, name=None, common_type=None, common_type_alt=None, score=None): <NEW_LINE> <INDENT> self._script = None <NEW_LINE> self._id = None <NEW_LINE> self._name = None <NEW_LINE> self._common_type = None <NEW_LINE> self._common_type_alt = None <NEW_LINE> self._score = None <NEW_LINE> se...
ProperNounCategorizedOut - a model defined in OpenAPI
625941ed16aa5153ce3629b4
def stop2p(): <NEW_LINE> <INDENT> if timer.is_running(): <NEW_LINE> <INDENT> timer.stop() <NEW_LINE> global result2pline, result2p <NEW_LINE> result2pline = 60 <NEW_LINE> if p1score > p2score: <NEW_LINE> <INDENT> result2p = "Player 1 wins!" <NEW_LINE> <DEDENT> elif p2score > p1score: <NEW_LINE> <INDENT> result2p = "Pla...
Stops the timer and updates the result for a 2-player game
625941ed0a50d4780f6673d2
def testDefaultDenyIngressCreation(self): <NEW_LINE> <INDENT> self.naming.GetNetAddr.return_value = ALL_IPV4_IPS <NEW_LINE> acl = gcp_hf.HierarchicalFirewall( policy.ParsePolicy(HEADER_NO_OPTIONS + TERM_DENY_INGRESS, self.naming), EXP_INFO) <NEW_LINE> expected = json.loads(EXPECTED_DENY_INGRESS_BETA) <NEW_LINE> self.as...
Test that the correct IP is correctly set on a deny all ingress term.
625941ed4527f215b584c98d
def batchHasNotBeenClosed(response_code): <NEW_LINE> <INDENT> if response_code == 'BatchHasNotBeenClosed': <NEW_LINE> <INDENT> print('You have attempted to refund a payment but the batch has not closed. You should void payment instead') <NEW_LINE> return response_code
Check for BatchHasNotBeenClosed response
625941edeab8aa0e5d26e095
def closeResolvers(): <NEW_LINE> <INDENT> if hasattr(context, 'resolvers_loaded'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for resolver in context.resolvers_loaded.values(): <NEW_LINE> <INDENT> if hasattr(resolver, 'close'): <NEW_LINE> <INDENT> resolver.close() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except Exceptio...
hook to close the resolvers at the end of the request
625941ed6fb2d068a760f5e1
def test_one_node(self): <NEW_LINE> <INDENT> node_1 = (0, 0) <NEW_LINE> graph = { node_1: {"neighbors": []} } <NEW_LINE> path, distance = dijkstra(graph, node_1, node_1) <NEW_LINE> self.assertEqual(path, [(0, 0)]) <NEW_LINE> self.assertEqual(distance, 0.0)
Graph with a unique vertice.
625941ed0a366e3fb873ed5a
def reduce_columns(columns, *clauses): <NEW_LINE> <INDENT> columns = util.OrderedSet(columns) <NEW_LINE> omit = util.Set() <NEW_LINE> for col in columns: <NEW_LINE> <INDENT> for fk in col.foreign_keys: <NEW_LINE> <INDENT> for c in columns: <NEW_LINE> <INDENT> if c is col: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT...
given a list of columns, return a 'reduced' set based on natural equivalents. the set is reduced to the smallest list of columns which have no natural equivalent present in the list. A "natural equivalent" means that two columns will ultimately represent the same value because they are related by a foreign key. \*cl...
625941ed8a349b6b435e86ae
@time_clock <NEW_LINE> def collect_detail(folder='./', namelist=('z', 'q', 'l')): <NEW_LINE> <INDENT> for s in namelist: <NEW_LINE> <INDENT> res = [] <NEW_LINE> z_file_names = [i for i in os.listdir(folder) if i.startswith(s)] <NEW_LINE> for name in z_file_names: <NEW_LINE> <INDENT> file_name = os.path.join(folder, nam...
收集文件夹中的信息,都存到一个文件中,并把其他的都删掉 :param folder: 指定文件夹的位置 :param namelist: :return:
625941ed6aa9bd52df0372e2
def test_array_parameter4(self): <NEW_LINE> <INDENT> t4 = TParModel([[1, 2], [3, 4]], [5, 6], model_set_axis=False) <NEW_LINE> assert len(t4) == 1 <NEW_LINE> assert t4.coeff.shape == (2, 2) <NEW_LINE> assert t4.e.shape == (2,) <NEW_LINE> assert np.issubdtype(t4.param_sets.dtype, np.object_) <NEW_LINE> assert np.all(t4....
Test multiple parameter model with array-valued parameters of the same size as the number of parameter sets.
625941ed046cf37aa974d27d
def des_encrypt(self, key, commit=False): <NEW_LINE> <INDENT> self.__open_check() <NEW_LINE> buffer = '' <NEW_LINE> for i in self.__plain_text: <NEW_LINE> <INDENT> buffer += i <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> algo = des_algo.DES() <NEW_LINE> buffer = algo.encrypt(key.key, buffer) <NEW_LINE> <DEDENT> except ...
des_encrypt() --------------- Encrypt a plain text with DES algorithm. Example:: from securefile import Encrypt from securefile.keyset import DES_KEY des_key = DES_KEY.genrate('12345678123456781234567812345678') enc = Encrypt('test.md') enc.open() enc.des_encrypt(des_ke...
625941ed4f6381625f114f76
def AssignImageList(self, imglist): <NEW_LINE> <INDENT> self._pages.AssignImageList(imglist) <NEW_LINE> self.SetAGWWindowStyleFlag(self.GetAGWWindowStyleFlag())
Assigns an image list to the control. :param `imglist`: an instance of :class:`ImageList`.
625941eda17c0f6771cbe58a
def pytest_addoption(parser): <NEW_LINE> <INDENT> text = "The device node path or the configuration files section names defining the power " "meters to run the tests for." <NEW_LINE> parser.addoption("--devspec", action="append", default=[], help=text) <NEW_LINE> parser.addoption("--loglevel", action="store",...
Add custom pytest options.
625941edaad79263cf390f84
def test_search_redirect_one_single_result(self): <NEW_LINE> <INDENT> Comment.objects.create( content_object=self.org_alpha, user=self.hermione, comment="Testing commenting system for Alpha Organization", submit_date=datetime.now(tz=timezone.utc), site=self.current_site, ) <NEW_LINE> Comment.objects.create( content_obj...
Regression test: make sure redirect doesn't happen if there's a singular result in one of the groups, but other groups contain >= 2 elements. https://github.com/carpentries/amy/issues/2014
625941edb5575c28eb68e540
def set_eip_status(self, status, error=False): <NEW_LINE> <INDENT> leap_assert_type(error, bool) <NEW_LINE> if error: <NEW_LINE> <INDENT> logger.error(status) <NEW_LINE> self.hide_eip_cancel_button() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.debug(status) <NEW_LINE> <DEDENT> self._eip_status = status <NEW_LI...
Set the status label at the VPN stage to status. :param status: status message :type status: str or unicode :param error: if the status is an erroneous one, then set this to True :type error: bool
625941ed9f2886367277adc4
def applyLayout(frame, name, layout, message=None): <NEW_LINE> <INDENT> import fsleyes.views.canvaspanel as canvaspanel <NEW_LINE> layout = deserialiseLayout(layout) <NEW_LINE> frameChildren = layout[0] <NEW_LINE> frameLayout = layout[1] <NEW_LINE> vpChildrens = layout[2] <NEW_LINE> vpLayouts = layout[3]...
Applies the given serialised layout string to the given :class:`.FSLeyesFrame`. :arg frame: The :class:`.FSLeyesFrame` instance. :arg name: The layout name. :arg layout: The serialised layout string. :arg message: A message to display (using the :mod:`.status` module).
625941edfbf16365ca6f670b
def max_admitted(self, rank, data_schools, year): <NEW_LINE> <INDENT> data_admitted = deepcopy(data_schools) <NEW_LINE> not_admitted = self.get_not_admitted(year) <NEW_LINE> data_admitted[not_admitted] = np.nan <NEW_LINE> worst_schools = np.array(data_admitted.idxmax(1)) <NEW_LINE> was_admitted = True - pd.isnull(worst...
Select maximum (worst) rank of admitted-to schools
625941ed956e5f7376d713a7
def sigusr1_handler(self, signl, frame): <NEW_LINE> <INDENT> print("\nINFO : " + str(datetime.datetime.now()) + " SIGUSR1 signal received!") <NEW_LINE> print("INFO: " + str(datetime.datetime.now()) + " Resetting stored counters.") <NEW_LINE> self.lock.acquire() <NEW_LINE> self.dante_thread.traffic_dict = defaultdict(la...
SIGUSR1 Handler
625941edcdde0d52a9e53573
def __init__(self, resource, use_container=False, **options): <NEW_LINE> <INDENT> if not hasattr(resource, "_meta"): <NEW_LINE> <INDENT> raise TypeError( "{!r} is not a valid type for a related field.".format(resource) ) <NEW_LINE> <DEDENT> self.of = resource <NEW_LINE> self.use_container = use_container <NEW_LINE> if ...
Initialisation of a CompositeField. :param resource: :param use_container: Special flag for codecs that support containers or just multiple instances of a sub element (ie XML). :param empty: This collection can be empty :param options: Additional options passed to :py:class:`odin.fields.Field` super class.
625941edd18da76e23532a18
def __init__(self, filename, instance_name): <NEW_LINE> <INDENT> self.events = Gtk.ListStore( str, bool, str, bool, int, int, int, int, int, int, bool, str, str, bool, str, int, int, int, int, int, int ) <NEW_LINE> self.instances = Gtk.ListStore(str, str) <NEW_LINE> self.__filename = filename <NEW_LINE> self.__json = C...
This requires the filename that is being read along with the instance name to bind to the event array
625941edd486a94d0b98e682
def test_privmsgPrivateMessage(self): <NEW_LINE> <INDENT> self.bot.privmsg(self._username, self._us, "hi") <NEW_LINE> self.assertEqual( 'PRIVMSG {username} :{quote}\r\n'.format( username=self._username, quote=QUOTE ), self.fake_transport.value() )
For private messages, should send quote directly to user
625941ed7d847024c06be7fc
def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.neighborhood = 10.0
initialize the alignment correction
625941ed498bea3a759b9fe9
def check_dir_empty(path): <NEW_LINE> <INDENT> with os.scandir(path) as it: <NEW_LINE> <INDENT> return not any(it)
Return True if a directory is empty.
625941ed23849d37ff7b35c6
def get_json_file(host, remote_file, local_file, is_root=False): <NEW_LINE> <INDENT> if CREDS.DRY_RUN: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> file_content = get_file_content(host, remote_file, local_file, is_root) <NEW_LINE> if file_content['rc'] > 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> i...
Get json file from remote host
625941ed23849d37ff7b35c7
def test_index(self): <NEW_LINE> <INDENT> url = self.host+"/douban/" <NEW_LINE> test = Public() <NEW_LINE> test.html(url,"首页")
验证豆瓣首页内容
625941ed24f1403a9260109d
def __decode(self, message): <NEW_LINE> <INDENT> message = message.decode("UTF-8") <NEW_LINE> try: <NEW_LINE> <INDENT> data = json.loads(message) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> data = None <NEW_LINE> <DEDENT> if type(data) is dict and 'event' in data: <NEW_LINE> <INDENT> return data['event']...
decode network packet to json and extract event name
625941edbaa26c4b54cb1656
def updateValue(self, iA): <NEW_LINE> <INDENT> iA = int(iA) <NEW_LINE> scoreA = self.dat[2][iA] <NEW_LINE> valA = self.dat[3][iA] <NEW_LINE> probA = self.prob(iA) <NEW_LINE> x = np.sum(probA) - 0.5 <NEW_LINE> y = np.sum(probA * (1 - probA)) - 0.25 <NEW_LINE> if x == 0: <NEW_LINE> <INDENT> exit() <NEW_LINE> <DEDENT> ret...
Updates the value of script A using Newton's Method
625941edbd1bec0571d90b6b
def _scale_coordinates(shape, scale): <NEW_LINE> <INDENT> ndim = len(shape) <NEW_LINE> if ndim == 2: <NEW_LINE> <INDENT> nx, ny = shape <NEW_LINE> fx, fy = np.meshgrid(np.linspace(-nx/2, nx/2, nx), np.linspace(-ny/2, ny/2, ny), indexing='ij') <NEW_LINE> sx = nx / (2.0*math.pi) / 2**scale <NEW_LINE> sy = ny / (2.0*math....
Compute the scaled image coordinates on the box [-pi,pi]^d
625941ed379a373c97cfb083
def train(model, x_train, y_train, x_test, y_test): <NEW_LINE> <INDENT> model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.Adam(lr=LEARNING_RATE), metrics=[metrics.CategoricalAccuracy(), metrics.Precision(), metrics.Recall()]) <NEW_LINE> checkpoint = ModelCheckpoint(WEIGHTS_PATH, monitor='val_cat...
Train the target model and save the weight of the model :param model: the model that will be trained :param x_train: the image as numpy format :param y_train: the label for x_train :param weights_path: path to save the model file :return: None
625941eddd821e528d63b6e0
def __len__(self): <NEW_LINE> <INDENT> return self._len
Which returns always how amny no.of child nodes it contains.
625941ed3d592f4c4ed1d59b
def RoutedInterfaces(self, instance): <NEW_LINE> <INDENT> return self._interfaceParser.GetAllInterfaces(instance)
Returns the RouterInterface object list for the requested routing instance
625941ed097d151d1a223392
def Test(self, data): <NEW_LINE> <INDENT> hit = 0.0 <NEW_LINE> miss = 0.0 <NEW_LINE> for i in range(1, len(data) ): <NEW_LINE> <INDENT> predicted = self.CalculateOutput(data[i]) <NEW_LINE> if ( predicted == data[i][ len(data[0])-1] ): <NEW_LINE> <INDENT> hit += 1.0 <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> miss +=...
Takes Test data set to run against trained model
625941edbe8e80087fb21176
def read( self, n=1 ): <NEW_LINE> <INDENT> s = self._data[0:n] <NEW_LINE> self._data = self._data[n:] <NEW_LINE> return s
This method simulates reading a pretermined amount of characters from the Arduino. Parameters: n (int): number of characters to read. Returns: s (string): the characters read from the Arduino.
625941ed8da39b475bd654b7
def flatnotnan(a): <NEW_LINE> <INDENT> notnan = np.argwhere(~np.isnan(a)) <NEW_LINE> return notnan.flatten()
Returns indices that are non nan in a flattened version of a Parameters ---------- a: np.array Returns ------- res: np.array Output array containing indices of an array that are not nan
625941edbf627c535bc1370b
def collate_fn(data): <NEW_LINE> <INDENT> _, labels, lengths = zip(*data) <NEW_LINE> max_len = max(lengths) <NEW_LINE> n_ftrs = data[0][0].size(1) <NEW_LINE> features = torch.zeros((len(data), max_len, n_ftrs)) <NEW_LINE> labels = torch.tensor(labels) <NEW_LINE> lengths = torch.tensor(lengths) <NEW_LINE> for i in range...
data: is a list of tuples with (example, label, length) where 'example' is a tensor of arbitrary shape and label/length are scalars
625941ed0383005118ecfb1d
def _getRecoveryWarnings(self, mirrorBuilder): <NEW_LINE> <INDENT> res = [] <NEW_LINE> for toRecover in mirrorBuilder.getMirrorsToBuild(): <NEW_LINE> <INDENT> if toRecover.getFailoverSegment() is not None: <NEW_LINE> <INDENT> src = toRecover.getLiveSegment() <NEW_LINE> dest = toRecover.getFailoverSegment() <NEW_LINE> i...
return an array of string warnings regarding the recovery
625941ed1b99ca400220aff0
def transcribe(s): <NEW_LINE> <INDENT> RNA = s.replace('T','U') <NEW_LINE> print(RNA)
given a DNA string, replace each T with a U and write it back out as RNA (str) -> (str) >>>transcribe('ATGCCCGGGTTTAAA') AUGCCCGGGUUUAAA
625941ed32920d7e50b28711
def send_request(self, request): <NEW_LINE> <INDENT> if 'path' not in request: <NEW_LINE> <INDENT> raise RuntimeError('Cannot send request without a path') <NEW_LINE> <DEDENT> reply_received = defer.Deferred() <NEW_LINE> msg_id = uuid.uuid4().hex <NEW_LINE> self._requests[msg_id] = reply_received <NEW_LINE> got_remote_...
Send a request. This assumes the request has a path, and it uses the service registry to determine which socket can handle the request based on the service registry. Params ====== request : dictionary Standard request message that contains a path, command, and args entries. Returns ======= reply_received : de...
625941ed442bda511e8be94d
def _choose_signer(self, operation_name, signing_type, context): <NEW_LINE> <INDENT> signing_type_suffix_map = { 'presign-post': '-presign-post', 'presign-url': '-query' } <NEW_LINE> suffix = signing_type_suffix_map.get(signing_type, '') <NEW_LINE> signature_version = self._signature_version <NEW_LINE> if signature_ver...
Allow setting the signature version via the choose-signer event. A value of `ibm_botocore.UNSIGNED` means no signing will be performed. :param operation_name: The operation to sign. :param signing_type: The type of signing that the signer is to be used for. :return: The signature version to sign with.
625941ed8c0ade5d55d3eefc
def decode_trace(buf): <NEW_LINE> <INDENT> trc = [] <NEW_LINE> for chunk in iter(partial(buf.read, HALF_WORD), b''): <NEW_LINE> <INDENT> trc.append(unpack('H', chunk)[0]) <NEW_LINE> <DEDENT> return trc
Pixie-16 stores traces with two samples per word. This is about the only place we need to use a half word to decode the data structure. :param buf: The buffer containing the trace. :return:
625941edfb3f5b602dac3bd5
def test_error_propagation_race(self, vector, unique_database): <NEW_LINE> <INDENT> if vector.get_value('exec_option')['debug_action'] is not None: <NEW_LINE> <INDENT> pytest.skip(".test file needs to override debug action") <NEW_LINE> <DEDENT> new_vector = deepcopy(vector) <NEW_LINE> del new_vector.get_value('exec_opt...
IMPALA-7662: failed scan signals completion before error is propagated. To reproduce, we construct a table with two Parquet files, one valid and another invalid. The scanner thread for the invalid file must propagate the error before we mark the whole scan complete.
625941edab23a570cc2506c3
def bindNeckPitch(self, *args): <NEW_LINE> <INDENT> return _yarp.IGazeControl_bindNeckPitch(self, *args)
bindNeckPitch(IGazeControl self, double const min, double const max) -> bool
625941ed009cb60464c638e9
def test_cut_simple(self): <NEW_LINE> <INDENT> unaries, pairwise, edges, expected = self.binary_data() <NEW_LINE> result = cut_simple(unaries, pairwise) <NEW_LINE> self.assertTrue(np.array_equal(result, expected))
Test the cut_simple method.
625941ed283ffb24f3c55e38
def _req_pagseguro(params): <NEW_LINE> <INDENT> params_encode = urllib.urlencode(params) <NEW_LINE> res = urllib.urlopen('https://pagseguro.uol.com.br/Security/NPI/Default.aspx', params_encode) <NEW_LINE> retorno = res.read() <NEW_LINE> res.close() <NEW_LINE> return retorno
Faz requisição de validação ao PagSeguro
625941edd53ae8145f87a7a1