code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def zero(device_path, size=None, task=_NullTask()): <NEW_LINE> <INDENT> if size is None: <NEW_LINE> <INDENT> size = fsutils.size(device_path) <NEW_LINE> <DEDENT> elif size % sc.BLOCK_SIZE_4K: <NEW_LINE> <INDENT> raise se.InvalidParameterException("size", size) <NEW_LINE> <DEDENT> log.info("Zeroing device %s (size=%d)",...
Zero a block device. Arguments: device_path (str): Path to block device to wipe size (int): Number of bytes to write. If not specified, use the device size. Size must be aligned to `vdsm.storage.constants.BLOCK_SIZE_4K`. task (`storage.task.Task`): Task running this operation. If specified,...
625941e6090684286d50f128
def getPatchIndexPair(self, sequentialIndex): <NEW_LINE> <INDENT> nx, ny = self._numPatches <NEW_LINE> x = sequentialIndex % nx <NEW_LINE> y = sequentialIndex // nx <NEW_LINE> return Index2D(x=x, y=y)
Convert sequential index into patch index (x,y) pair. Parameters ---------- sequentialIndex : `int` Returns ------- x, y : `lsst.skymap.Index2D`
625941e6e64d504609d74c7d
def email_admins_no_payment_profile(self, recurring_payment): <NEW_LINE> <INDENT> self.email.recipient = self.admin_emails <NEW_LINE> if self.email.recipient: <NEW_LINE> <INDENT> template_name = "recurring_payments/email_admins_no_payment_profile.html" <NEW_LINE> try: <NEW_LINE> <INDENT> email_content = render_to_strin...
Notify admin that payment method hasn't been setup yet for this recurring payment entry.
625941e6b7558d58953c5348
def test_receipt_store_get_and_set(self): <NEW_LINE> <INDENT> receipt_store = TransactionReceiptStore(DictDatabase()) <NEW_LINE> receipts = [] <NEW_LINE> for i in range(10): <NEW_LINE> <INDENT> state_changes = [] <NEW_LINE> events = [] <NEW_LINE> data = [] <NEW_LINE> for j in range(10): <NEW_LINE> <INDENT> string = str...
Tests that we correctly get and set state changes to a ReceiptStore. This test sets a list of receipts and then gets them back, ensuring that the data is the same.
625941e6004d5f362079a76e
def get_params(self): <NEW_LINE> <INDENT> if self.peephole: <NEW_LINE> <INDENT> return [self.W, self.U, self.b, self.V] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [self.W, self.U, self.b]
This function overrides the parents' one. Returns interal layer parameters. Returns ------- list a list of shared variables used.
625941e6099cdd3c635f1096
def _add_gen_numbers(self): <NEW_LINE> <INDENT> gen_index_list = [] <NEW_LINE> for i, gen_size in enumerate(self.gen_size_list): <NEW_LINE> <INDENT> gen_index_list += gen_size*[i] <NEW_LINE> <DEDENT> self.all_points['generation'] = gen_index_list
add column for generation number in pandas database
625941e6a79ad161976cc582
def postCollectionsDestroy(self, id): <NEW_LINE> <INDENT> payloads = self.makePayloads(locals()) <NEW_LINE> session = self.oauth1AuthorizedSession() <NEW_LINE> url = self.urlJoin('destroy.json') <NEW_LINE> res = session.post(url, params = payloads) <NEW_LINE> return res.json()
コレクション削除
625941e626068e7796caf122
def disconnect(self, device): <NEW_LINE> <INDENT> self.device.ctrl.send(chr(4))
Disconnect using protocol specific method.
625941e6a219f33f34628da1
def saveHTML(page,nombreArch): <NEW_LINE> <INDENT> page_text = (page).encode('utf-8') <NEW_LINE> textFile = open(nombreArch, 'wb') <NEW_LINE> textFile.write(page_text) <NEW_LINE> textFile.close()
Metodo que salva en archivo el sitio cargado. params: string, nombrepatharchivo
625941e63539df3088e2e788
def discovery_swagger_apis_id_service_definition_get(self, id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.discovery_swagger_apis_id_service_definition_get_with_http_info(id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> ...
Retrieves the service definition of the API. # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.discovery_swagger_apis_id_service_definition_get(id, async_req=True) >>> result = thread.get() :param as...
625941e67b180e01f3dc4c32
def set_password(self, original): <NEW_LINE> <INDENT> self.password = bcrypt.generate_password_hash(original).decode('utf-8')
Hashes password and stores it.
625941e6a17c0f6771cbe48d
def compute_grid(psf_map, input_image): <NEW_LINE> <INDENT> grid_z1 = [] <NEW_LINE> grid_x, grid_y = np.mgrid[0:input_image.shape[0], 0:input_image.shape[1]] <NEW_LINE> xmax = np.linspace(0, input_image.shape[0], psf_map.shape[0]) <NEW_LINE> ymax = np.linspace(0, input_image.shape[1], psf_map.shape[1]) <NEW_LINE> for i...
Computes interpolation grid coefficients
625941e610dbd63aa1bd2fdf
def resnet101(pretrained=False, **kwargs): <NEW_LINE> <INDENT> model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) <NEW_LINE> if pretrained: <NEW_LINE> <INDENT> model.load_state_dict(op.join(model_dir, model_paths['resnet101'])) <NEW_LINE> <DEDENT> return model
Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
625941e6293b9510aa2c36cf
def moveZeroes(self, nums): <NEW_LINE> <INDENT> if nums == None: <NEW_LINE> <INDENT> return nums <NEW_LINE> <DEDENT> count = nums.count(0) <NEW_LINE> for i in range(0,count): <NEW_LINE> <INDENT> nums.remove(0) <NEW_LINE> nums.append(0)
:type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
625941e66fece00bbac2db81
def stop(self, doNotifyInStart = False): <NEW_LINE> <INDENT> LOG_DEBUG('GameSessionController::stop') <NEW_LINE> self.__sessionStartedAt = -1 <NEW_LINE> self.__stats = None <NEW_LINE> self.__doNotifyInStart = doNotifyInStart <NEW_LINE> self.__clearBanCallback() <NEW_LINE> self.__clearNotifyCallback() <NEW_LINE> return
Stopping current game session
625941e699fddb7c1c9de7cc
def get_data(db_file): <NEW_LINE> <INDENT> with closing(sqlite3.connect(db_file).cursor()) as cur: <NEW_LINE> <INDENT> cur.execute( "SELECT ra, dec, glong, glat, plx, e_plx, " "mux, muy, vlsr, e_mux, e_muy, e_vlsr FROM Parallax" ) <NEW_LINE> data = pd.DataFrame(cur.fetchall(), columns=[desc[0] for desc in cur.descripti...
Retrieves all relevant data in Parallax table from database connection specified by db_file Returns DataFrame with: ra (deg), dec (deg), glong (deg), glat (deg), plx (mas), e_plx (mas), mux (mas/yr), muy (mas/yr), vlsr (km/s) + all proper motion/vlsr uncertainties
625941e6f9cc0f698b140a35
def last_talked_about(self, user_da, system_da): <NEW_LINE> <INDENT> old_user_da = deepcopy(user_da) <NEW_LINE> new_user_da = DialogueActConfusionNetwork() <NEW_LINE> for prob, user_dai in user_da: <NEW_LINE> <INDENT> new_user_dais = [] <NEW_LINE> lta_tsvs = self.ontology.last_talked_about(user_dai.dat, user_dai.name, ...
This adds dialogue act items to support inference of the last slots the user talked about.
625941e650485f2cf553d1d9
def test_roundtrip_split(self): <NEW_LINE> <INDENT> s = writes(nb0, split_lines=True) <NEW_LINE> self.assertEqual(nbjson.reads(s),nb0)
Ensure that splitting multiline blocks is safe
625941e6d7e4931a7ee9e35c
def update_from_unit(self, unit, pos, created): <NEW_LINE> <INDENT> location = unit.get_locations() <NEW_LINE> flags = unit.get_flags() <NEW_LINE> target = unit.get_target() <NEW_LINE> source = unit.get_source() <NEW_LINE> comment = unit.get_comments() <NEW_LINE> fuzzy = unit.is_fuzzy() <NEW_LINE> translated = unit.is_...
Updates Unit from ttkit unit.
625941e62eb69b55b151ccf3
def test_get_file_makedirs(self): <NEW_LINE> <INDENT> tgt = os.path.join(paths.TMP, 'make', 'dirs', 'scene33') <NEW_LINE> self.run_function( 'cp.get_file', [ 'salt://grail/scene33', tgt, ], makedirs=True ) <NEW_LINE> self.addCleanup(shutil.rmtree, os.path.join(paths.TMP, 'make'), ignore_errors=True) <NEW_LINE> with sal...
cp.get_file
625941e67c178a314d6ef8a4
def previous(self) -> "PyObject *": <NEW_LINE> <INDENT> return _PolyVoxCore.SwigPyIterator_previous(self)
previous(SwigPyIterator self) -> PyObject *
625941e6c432627299f05087
def duplicate_template(reach, template_id=None, external_id=None): <NEW_LINE> <INDENT> if not (template_id or external_id) or (template_id and external_id): <NEW_LINE> <INDENT> raise ValueError( 'Please specify only one of template_id or external_id.' ) <NEW_LINE> <DEDENT> response = reach.request( method='POST', body=...
Duplicate a template. Arguments: reach (reach.core.Reach): A UA Reach object. template_id (str or int): The ID of the template you wish to delete. external_id (str or int): The external ID of the template you wish to delete. Returns: A dictionary containing the id of the newly created template...
625941e697e22403b379d3d9
def init_generation(sim_params): <NEW_LINE> <INDENT> generation = [] <NEW_LINE> if sim_params.complex: <NEW_LINE> <INDENT> size = 19683 <NEW_LINE> chars = range(11) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> size = 243 <NEW_LINE> chars = range(7) <NEW_LINE> <DEDENT> for i in range(0, sim_params.population_size): <NE...
Creates randomly generated generation
625941e692d797404e3045ca
def GetFlatFileNameAndTime(flat_or_hierarchical_path): <NEW_LINE> <INDENT> _, local_filename = os.path.split(flat_or_hierarchical_path) <NEW_LINE> if re.match(r'\d\d\d\d_.*', local_filename): <NEW_LINE> <INDENT> flat_filename = local_filename <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> flat_filename = '_'.join(flat_o...
Returns (flat local filename, timestamp from original path or filename).
625941e69f2886367277acc7
def valid_supercoo(self, xy): <NEW_LINE> <INDENT> x, y = xy <NEW_LINE> return (0 <= x < self.grid_Lx) and (0 <= y < self.grid_Ly)
Whether ``xy`` is inside the supergrid boundary
625941e632920d7e50b28611
def __setitem__(self, key, value): <NEW_LINE> <INDENT> if not self.dict_has_key(key): <NEW_LINE> <INDENT> if not self.parent is None: <NEW_LINE> <INDENT> return self.send(key, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dict.__setitem__(self, key, nargs.Arg(key)) <NEW_LINE> <DEDENT> <DEDENT> dict.__getitem__(s...
Checks for the key locally, and if not found consults the parent. Sets the value of the Arg.
625941e6442bda511e8be850
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <...
Returns the model properties as a dict
625941e63c8af77a43ae3be3
def tokenizer(documents): <NEW_LINE> <INDENT> text = [[token.lemma_.lower() for token in nlp(sentence) if token.pos_ is not 'PUNCT' and token.pos_ in {'NOUN','VERB','PROPN', 'ADJ','ADV'} and not token.is_stop] for sentence in documents] <NEW_LINE> text = [token for token in text if token!=[]] <NEW_LINE> return(text)
Tokenize the documents Put the text into lower case and retreive only the lemmas form of the tokens Removing punctuation Retrieve only the content words (Noun,Verb,Propn,Adj,Adv) of the textbook Remove stopwords Remove empty tokens
625941e6d7e4931a7ee9e35d
def LTE_level_pop(self,Z,T): <NEW_LINE> <INDENT> return self.g*np.exp(-self.E/(constants.k*T))/Z
LTE level population for partition function Z and temperature T
625941e60a366e3fb873ec5c
def rank_hits(ranks, k, pos=True): <NEW_LINE> <INDENT> axis = 1 <NEW_LINE> def sort_f(x): <NEW_LINE> <INDENT> if pos: <NEW_LINE> <INDENT> return [ ranks.columns[i] for i in np.argsort(x)[-k:] ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [ ranks.columns[i] for i in np.argsort(x)[:k] ] <NEW_LINE> <DEDENT> <DEDE...
Creates an edge list based on rank matrix. Parameters ---------- ranks : pd.DataFrame Matrix of ranks (aka conditional probabilities) k : int Number of nearest neighbors pos : bool Specifies either most associated or least associated. This is a proxy to positively correlated or negatively correlated. Return...
625941e6d4950a0f3b08c787
def make_fully_connected_tests(zip_path): <NEW_LINE> <INDENT> test_parameters = [{ "shape1": [[3, 3]], "shape2": [[3, 3]], "transpose_a": [True, False], "transpose_b": [True, False], "constant_filter": [True, False], }, { "shape1": [[4, 4], [1, 4], [4]], "shape2": [[4, 4], [4, 1], [4]], "transpose_a": [False], "transpo...
Make a set of tests to do fully_connected.
625941e6b57a9660fec33cc8
def test_make_machine_node_address(self): <NEW_LINE> <INDENT> m2 = Machine('bar') <NEW_LINE> m3 = Machine('baz') <NEW_LINE> n2 = Node('FooNode') <NEW_LINE> n3 = Node('GabeNode') <NEW_LINE> a = Address()._make(machine=m2, node=n2) <NEW_LINE> self.assertEqual(str(a), 'node.bar.FooNode') <NEW_LINE> a = Address()._make(mac...
Node on machine specific message
625941e623e79379d52ee99c
def get_addrs(self): <NEW_LINE> <INDENT> with ServiceOperation(self): <NEW_LINE> <INDENT> svc = self._get_from_provider(use_proxy=False) <NEW_LINE> <DEDENT> ret = [] <NEW_LINE> ing_list = svc.status.load_balancer.ingress <NEW_LINE> if not ing_list: <NEW_LINE> <INDENT> return ret <NEW_LINE> <DEDENT> for ing in ing_list:...
Returns: list of hostnames associated with this load balancer
625941e6f8510a7c17cf9b3d
def parse(self, body, signature): <NEW_LINE> <INDENT> if not self.signature_validator.validate(body, signature): <NEW_LINE> <INDENT> raise InvalidSignatureError( 'Invalid signature. signature=' + signature) <NEW_LINE> <DEDENT> body_json = json.loads(body) <NEW_LINE> events = [] <NEW_LINE> for event in body_json['events...
Parse webhook request body as text. :param str body: Webhook request body (as text) :param str signature: X-Line-Signature value (as text) :rtype: list[T <= :py:class:`linebot.models.events.Event`] :return:
625941e6187af65679ca555e
def deserialize0(self, data): <NEW_LINE> <INDENT> def create_node(i): <NEW_LINE> <INDENT> if i >= len(data) or data[i] == 'null' or data[i] == '': <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> node = TreeNode(data[i] if data[i] != '' else '') <NEW_LINE> node.left = create_node(2 * i + 1) <NEW_LINE> node.right = c...
Decodes your encoded data to tree. :type data: str :rtype: TreeNode
625941e68da39b475bd653b7
def toCubePVR(srcDir, srcExt, dstFilename, format) : <NEW_LINE> <INDENT> if format not in PVRFormats : <NEW_LINE> <INDENT> error('invalid PVR texture format {}!'.format(format)) <NEW_LINE> <DEDENT> ensureDstDirectory() <NEW_LINE> pvrTool = getToolsBinPath() + 'PVRTexToolCLI' <NEW_LINE> srcFiles = ['posx', 'negx', 'posy...
Generate a cube map and convert to PVR
625941e6851cf427c661a949
def test_transform_type(self): <NEW_LINE> <INDENT> self.assertEqual(self.tr.getTransformType(), OCIO.TRANSFORM_TYPE_CDL)
Test the getTransformType() method.
625941e696565a6dacc8fb08
def kmeans(points, k, threshold=1e-5, init="forgy", verbose=False): <NEW_LINE> <INDENT> bigdiff = True <NEW_LINE> means, nearests, totaldist = initk(points, k, init) <NEW_LINE> if verbose: <NEW_LINE> <INDENT> print(means) <NEW_LINE> <DEDENT> while bigdiff: <NEW_LINE> <INDENT> means2 = [] <NEW_LINE> for j in range(k): <...
Input points: list of Point objects k: integer, the number of means threshould: minimal improvement between iterations init: initialization method ('forgy' or 'random') verbose: if True, print intermediate result Output totaldist: average distances between each point to its nearest m...
625941e68a43f66fc4b5449f
def remove_value(self, value_id): <NEW_LINE> <INDENT> return self._network.manager.removeSceneValue(self.scene_id, value_id)
Remove a value from the scene. :param value_id: The id of the value to change :type value_id: int :returns: True if the scene is removed. False otherwise. :rtype: bool
625941e630c21e258bdfa8df
def downloadAllAlbums(albumsUrl): <NEW_LINE> <INDENT> allAlbums = get(albumsUrl) <NEW_LINE> soup = bs(allAlbums.text, "html.parser") <NEW_LINE> people = soup.find('div', class_='info').h1.string <NEW_LINE> nextpage = soup.find('span', class_='next') <NEW_LINE> albums = soup.find_all('a', class_='album_photo') <NEW_LINE...
Download all albums of a person, the albumsUrl is the url of a person's albumlist. downloadAllAlbums('https://www.douban.com/people/abcde/photos')
625941e6656771135c3ebcb2
def timing_function(some_function): <NEW_LINE> <INDENT> def wrapper(): <NEW_LINE> <INDENT> t1 = time.time() <NEW_LINE> some_function() <NEW_LINE> t2 = time.time() <NEW_LINE> return "Time it took to run the function: {}\n".format(str((t2 - t1))) <NEW_LINE> <DEDENT> return wrapper
Outputs the time a function takes to execute.
625941e6d486a94d0b98e585
def get_queryset(self): <NEW_LINE> <INDENT> category_pk = self.kwargs['pk'] <NEW_LINE> queryset = Tutorial.objects.order_by('-created_at').filter(category__pk=category_pk) <NEW_LINE> return queryset
カテゴリ絞り込み category = get_object_or_404(Category, pk=self.kwargs['pk']) queryset = Tutorial.objects.order_by('-created_at').filter(category=category)
625941e6d8ef3951e324397c
def save_figure(self, evt=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> parent = self.canvas.HACK_parent <NEW_LINE> fig = self.canvas.HACK_fig <NEW_LINE> Page = self.canvas.HACK_Page <NEW_LINE> add = self.canvas.HACK_append <NEW_LINE> dirname = parent.dirname <NEW_LINE> filename = self.canvas.get_window_title().r...
A substitude function for save in: matplotlib.backends.backend_wx.NavigationToolbar2Wx We want to be able to give parameters such as dirname and filename.
625941e66fece00bbac2db82
def test_association_requested(self): <NEW_LINE> <INDENT> ae = AE() <NEW_LINE> ae.on_association_requested(None)
Test default callback raises exception
625941e61b99ca400220aef2
def test_isbc(self): <NEW_LINE> <INDENT> with self.admin_access.cnx() as cnx: <NEW_LINE> <INDENT> agent_authority = cnx.create_entity("AgentAuthority") <NEW_LINE> cnx.commit() <NEW_LINE> record = AgentRecord( { "eid": str(agent_authority.eid), "date naissance": "-0400-01-01T00:00:00Z", "precision date naissance": "9", ...
Test updating database. Trying: date is Before Christ Expecting: timestamp is formatted date and it is flagged as Before Christ
625941e6046cf37aa974d181
def subdomainVisits(self, cpdomains): <NEW_LINE> <INDENT> answer = dict() <NEW_LINE> for domain in cpdomains: <NEW_LINE> <INDENT> count, domain = domain.split() <NEW_LINE> count = int(count) <NEW_LINE> frags = domain.split('.') <NEW_LINE> for index in range(len(frags)): <NEW_LINE> <INDENT> virgin_count = 0 <NEW_LINE> k...
:type cpdomains: List[str] :rtype: List[str]
625941e660cbc95b062c6982
def showWelcomeAnimation(): <NEW_LINE> <INDENT> playerIndex = 0 <NEW_LINE> playerIndexGen = cycle([0, 1, 2, 1]) <NEW_LINE> loopIter = 0 <NEW_LINE> playerx = int(SCREENWIDTH * 0.2) <NEW_LINE> playery = int((SCREENHEIGHT - IMAGES['player'][0].get_height()) / 2) <NEW_LINE> messagex = int((SCREENWIDTH - IMAGES['message'].g...
Shows welcome screen animation of flappy bird
625941e61f5feb6acb0c4f87
def product_layer(layer): <NEW_LINE> <INDENT> return [ layer[j] * layer[k] for (j, k) in zip(range(0, len(layer), 2), range(1, len(layer), 2)) ]
INPUT: - ``layer`` -- a list of even length OUTPUT: A list of half the length whose terms are the products of the consecutive terms of the input EXAMPLES:: sage: layer = list(range(1,15)) sage: product_layer(layer) [2, 12, 30, 56, 90, 132, 182]
625941e656b00c62f0f14a9a
def process_df(df, mappings={}, na_dict={}, y_name=None, fill_na=True): <NEW_LINE> <INDENT> df_res = df.copy() <NEW_LINE> strings_to_cats(df_res) <NEW_LINE> if y_name is None: <NEW_LINE> <INDENT> df_res = new_to_other(df_res, mappings) <NEW_LINE> <DEDENT> df_res, mappings = cats_to_codes_plus1(df_res, mappings) <NEW_LI...
df: Pandas dataframe mappings: Dictionary, {'categorical_col': {'col1': <num1>, 'col2':<num2>...}...} na_dict: Dictionary, {'column_name': <value to fill NAs>} (usually median) y_name: String, name of response variable fill_na: bool, if True function will replace missing values in dataframe Function performs basic pre...
625941e621bff66bcd684d8c
@keras_export('keras.backend.resize_images') <NEW_LINE> @dispatch.add_dispatch_support <NEW_LINE> @doc_controls.do_not_generate_docs <NEW_LINE> def resize_images(x, height_factor, width_factor, data_format, interpolation='nearest'): <NEW_LINE> <INDENT> if data_format == 'channels_first': <NEW_LINE> <INDENT> rows, cols ...
Resizes the images contained in a 4D tensor. Args: x: Tensor or variable to resize. height_factor: Positive integer. width_factor: Positive integer. data_format: One of `"channels_first"`, `"channels_last"`. interpolation: A string, one of `nearest` or `bilinear`. Returns: A tensor. Raises: ...
625941e6ac7a0e7691ed4502
def __del__(self): <NEW_LINE> <INDENT> if not self.closed: <NEW_LINE> <INDENT> self.close()
Closes the ClientSession instance cleanly when the instance is deleted. Useful for things like when the interpreter closes. This would be perfect if discord.py had this as well. :thinking:
625941e63cc13d1c6d3c77b6
def addUserOutput(self, *kw): <NEW_LINE> <INDENT> output = [attr for attr in kw if type(attr) == str] <NEW_LINE> self.HAS_USER_OUTPUT = True <NEW_LINE> ModeList = list(self.__AnalysisModes__) <NEW_LINE> MaxMode = 0 <NEW_LINE> for attr in output: <NEW_LINE> <INDENT> if attr[:2] == 'ec' and self._MODE_ != 'null': <NEW_LI...
Add output parameters to the scanner as a collection of one or more string arguments ('O1','O2','O3', 'On'). These are evaluated at each iteration of the scanner and stored in the self.UserOutputResults array. The list of output is stored in self.UserOutputList.
625941e607f4c71912b118c3
def data_collection(path): <NEW_LINE> <INDENT> store = pd.HDFStore(path + 'index_option_series.h5', 'a') <NEW_LINE> today = dt.datetime.today() <NEW_LINE> start = today - dt.timedelta(31) <NEW_LINE> day = start.day <NEW_LINE> month = start.month <NEW_LINE> year = start.year <NEW_LINE> for i in range(4): <NEW_LINE> <IND...
Main function which saves data into the HDF5 file 'index_option_series.h5' for later use. Parameters ========== path: string path to store the data
625941e699cbb53fe6793023
def set_polygon(self, polygon): <NEW_LINE> <INDENT> self.py = polygon <NEW_LINE> self.basename = ''
Define the polygon to be triangulated by Triangle. Polygon is a polygon geometry as represented by the Shapely library.
625941e65f7d997b87174eda
def compress(self, z=None): <NEW_LINE> <INDENT> if z is not None and z != self._z: <NEW_LINE> <INDENT> self._z = z <NEW_LINE> self._resClear('cmp') <NEW_LINE> self._initCompression() <NEW_LINE> <DEDENT> if self._nonCompressible: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._state = 'cmp'
Set this sieve to its compressed state.
625941e6099cdd3c635f1097
def gaussian_shaping_filter(self, model): <NEW_LINE> <INDENT> bt = model.vars.shaping_filter_param.value <NEW_LINE> std = 1.05 / bt <NEW_LINE> w = self.gaussian(17, std) <NEW_LINE> w = tinynumpy.divide(w, w.sum()) <NEW_LINE> f_hack = tinynumpy.convolve(w, tinynumpy.ones((1, 8)).flatten()) <NEW_LINE> c_hack = tinynumpy....
Args: model (ModelRoot) : Data model to read and write variables from
625941e6be383301e01b58bc
def conf_set(self, option, val): <NEW_LINE> <INDENT> self.require_state("configuring", "connected") <NEW_LINE> if not isinstance(option, str): <NEW_LINE> <INDENT> raise TypeError('option must be a string') <NEW_LINE> <DEDENT> if not isinstance(val, str): <NEW_LINE> <INDENT> raise TypeError('val must be a string') <NEW_...
Set the value of a configuration option :param option: which option to set :type option: str :param option: value of the option :type option: str :raises: :class:`TypeError`, :class:`ObjectNotFound`
625941e66aa9bd52df0371e5
def __init__(self): <NEW_LINE> <INDENT> super(MacAppFirewallParser, self).__init__() <NEW_LINE> self._last_month = 0 <NEW_LINE> self._previous_structure = None <NEW_LINE> self._year_use = 0
Initializes a parser.
625941e6be7bc26dc91cda36
def plot_landmark_matchings(input_landmarks, target_landmarks, registered_landmarks, title='', landmark_size=50): <NEW_LINE> <INDENT> assert input_landmarks.ndim == 2 <NEW_LINE> assert input_landmarks.shape == target_landmarks.shape == registered_landmarks.shape <NEW_LINE> fig = plt.figure() <NEW_LINE> axis = fig.add_s...
Plot the results of the matching of landmarks. Parameters ---------- input_landmarks Positions of the input landmarks. target_landmarks Positions of the target landmarks. registered_landmarks Positions of the registered landmarks. title Title of the plot. landmark_size Size of the landmarks. Retur...
625941e68e7ae83300e4b40c
def format_refs_in_mirror(self): <NEW_LINE> <INDENT> refs = '' <NEW_LINE> if not self.repodir.exists(): <NEW_LINE> <INDENT> return refs <NEW_LINE> <DEDENT> env = os.environ.copy() <NEW_LINE> env['GIT_DIR'] = str(self.repodir) <NEW_LINE> refs += subprocess.run([ 'git', 'for-each-ref', "--format=%(objectname) %(refname)"...
Format a report on refs in the mirror like LIST wants it If the mirror is empty, the report will be empty.
625941e6187af65679ca555f
def remove(self, request): <NEW_LINE> <INDENT> access_token = request.META.get("HTTP_TOKEN") <NEW_LINE> if not token_verify(access_token): <NEW_LINE> <INDENT> return token_invalid() <NEW_LINE> <DEDENT> delete_data = request.data <NEW_LINE> subjects = delete_data.get('subjects') <NEW_LINE> if subjects is None: <NEW_LINE...
删除符合参数条件的已有课程信息 :param request: the request from browser. 用来获取access_token和删除条件 :return: JSON response. 包括code, message 1、如果token无效,即token不存在于数据库中,返回token_invalid的JSON response 2、如果request中的subjects参数为空,即Body-raw-json中没有内容,返回parameter_missed的JSON response 3、如果符合条件,尝试删除 删除失败,返回dele...
625941e667a9b606de4a82f5
def __init__( self, *, content: Optional[str] = None, children: Optional[list] = None, position: Tuple[int, int] = None ): <NEW_LINE> <INDENT> if content is not None: <NEW_LINE> <INDENT> self.content = content <NEW_LINE> <DEDENT> if children is not None: <NEW_LINE> <INDENT> self.children = children
Initialise basic span token. :param content: raw string content of the token :param children: list of child tokens :param position: span position within the source text
625941e615fb5d323cde0f54
def meld(self, *args): <NEW_LINE> <INDENT> return _MEDCoupling.MEDCouplingConstOnTimeInterval_meld(self, *args)
meld(self, MEDCouplingTimeDiscretization other) -> MEDCouplingTimeDiscretization 1
625941e685dfad0860c3b29a
def findLength(self, nums1: List[int], nums2: List[int]) -> int: <NEW_LINE> <INDENT> def condition(length): <NEW_LINE> <INDENT> comb = set() <NEW_LINE> i, j = 0, length <NEW_LINE> while j <= len(nums1): <NEW_LINE> <INDENT> comb.add(tuple(nums1[i:j])) <NEW_LINE> i, j = i+1, j+1 <NEW_LINE> <DEDENT> i, j = 0, length <NEW_...
找最小長度的 combination 然後查看 num2的各種 長度是否有在 combination 內 => binary search
625941e6cdde0d52a9e53475
def test_formatted_arrivals_returned(self): <NEW_LINE> <INDENT> block_id = self.active_scheduled_arrival.block_id <NEW_LINE> second_arrival = ScheduledArrival(stop_schedule_class=self.active_stop_schedule_class, block_id=block_id - 1, time=random.randint(1000, 1000000)) <NEW_LINE> second_arrival.save() <NEW_...
Test that the scheduled arrivals are returned in the expected format.
625941e644b2445a339324d1
def test_create_job(self): <NEW_LINE> <INDENT> job = self.iraw1.create_job(self.worker1) <NEW_LINE> self.assertEqual(job.worker, self.worker1) <NEW_LINE> self.assertEqual(self.iraw1.job, job)
Test create IGitRaw job
625941e6cc0a2c11143dd2d0
def add_ago_to_since(since: str) -> str: <NEW_LINE> <INDENT> since_words = since.split(" ") <NEW_LINE> grains = ["days", "years", "hours", "day", "year", "weeks"] <NEW_LINE> if len(since_words) == 2 and since_words[1] in grains: <NEW_LINE> <INDENT> since += " ago" <NEW_LINE> <DEDENT> return since
Backwards compatibility hack. Without this slices with since: 7 days will be treated as 7 days in the future. :param str since: :returns: Since with ago added if necessary :rtype: str
625941e621a7993f00bc8136
def _start_bind(self): <NEW_LINE> <INDENT> addr_str = "{}:{}".format(BIND_BIND_ADDRESS[0], BIND_BIND_ADDRESS[1]) <NEW_LINE> self.process = subprocess.Popen( [ "docker", "run", "--rm", "-p", "{}:53/udp".format(addr_str), "-p", "{}:53/tcp".format(addr_str), "-v", "{}/conf:/etc/bind".format(self.bind_root), "-v", "{}/zone...
Launch the BIND9 server as a Docker container
625941e6bf627c535bc1360e
def verify_login_failed(self): <NEW_LINE> <INDENT> result = self.is_element_present( "//div[contains(text(),'Invalid email or password')]", locator_type="xpath") <NEW_LINE> return result
Verify error message displayed for failed login
625941e63cc13d1c6d3c77b7
def _SetInstanceMetadata(self, instance, new_metadata): <NEW_LINE> <INDENT> compute = self.compute <NEW_LINE> errors = [] <NEW_LINE> zone = instance.zone.split('/')[-1] <NEW_LINE> list(request_helper.MakeRequests( requests=[ (compute.instances, 'SetMetadata', self.messages.ComputeInstancesSetMetadataRequest( instance=i...
Sets the project metadata to the new metadata.
625941e6596a897236089efa
def get_tag(self, tag): <NEW_LINE> <INDENT> values = self.tags.get(tag) <NEW_LINE> if values: <NEW_LINE> <INDENT> values = (to_unicode(x, self.encoding) for x in values if x not in (None, '')) <NEW_LINE> return u" / ".join(values) <NEW_LINE> <DEDENT> return u""
Common function for getting a tag. Simplifies a list into a single string separated by " / ".
625941e6ff9c53063f47c630
@commandWrap <NEW_LINE> def DisplayWireframe(*args, **kwargs): <NEW_LINE> <INDENT> return cmds.DisplayWireframe(*args, **kwargs)
:rtype: list|str|DagNode|AttrObject|ArrayAttrObject|Components1Base
625941e64f6381625f114e7a
@app.middleware("response") <NEW_LINE> def add_allow_origin(request, response): <NEW_LINE> <INDENT> if "Origin" in request.headers: <NEW_LINE> <INDENT> origin = request.headers["Origin"] <NEW_LINE> response.headers.update({"Access-Control-Allow-Origin": origin})
Adds client origin to response allowed origin header.
625941e6aad79263cf390e86
@jit(nopython=True) <NEW_LINE> def ozone_transmittance(oz, geo_air_mass): <NEW_LINE> <INDENT> ozm = oz * geo_air_mass / 10 <NEW_LINE> return 1-0.1611 * ozm * (1 + 139.48*ozm)**(-0.3035) - (0.002715*ozm)/(1 + 0.044*ozm + 0.0003*ozm**2)
TBA. Parameters ---------- oz : float Total column ozone amount in kg m**-2. geo_air_mass : float The geometric air mass. Returns ------- To : float Ozone transmittance (eq. 3.8 and 3.9).
625941e650485f2cf553d1da
def get_description(path): <NEW_LINE> <INDENT> mf = open(path, 'rb') <NEW_LINE> for i, line in enumerate(mf): <NEW_LINE> <INDENT> if i > 10: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> line = line.decode('utf-8').strip() <NEW_LINE> if '' in line or "'''" in line: <NEW_LINE> <INDENT> while line.strip('\n\t\r \'\"') ==...
Return first non-empty line from module docstring
625941e656b00c62f0f14a9b
def delete_comment_by_comment_id(comment_id, user_id): <NEW_LINE> <INDENT> comment = db_session.query(Comment).filter_by( comment_id=comment_id).first() <NEW_LINE> if (comment.user_id != user_id and not root_authorized()) or comment is None: <NEW_LINE> <INDENT> return 'fail' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT...
Delete the comment Args: comment_id: the id of the comment user_id: the id of the user Returns: If user is not the author and he's not authorized or the comment doesn't exist, it returns 'fail' Otherwise it returns 'success'
625941e6090684286d50f12a
def arguments_not_none(func): <NEW_LINE> <INDENT> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> for arg in args: <NEW_LINE> <INDENT> if arg is None: <NEW_LINE> <INDENT> raise NullArgument() <NEW_LINE> <DEDENT> <DEDENT> for arg, val in kwargs.iteritems(): <NEW_LINE> <INDENT> if val is None: <NEW_LINE> <INDENT> raise...
decorator, to check if any arguments are None; raise exception if so
625941e63d592f4c4ed1d4a1
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(PlannerResponse, self).__init__(*args, **kwds) <NEW_LINE> if self.agents_paths is None: <NEW_LINE> <INDENT> self.agents_paths = [] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.agents_paths = []
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: agents_paths :param args: complet...
625941e6b7558d58953c534a
def github_repo_to_api(url: str) -> str: <NEW_LINE> <INDENT> url = normalize_url(url) <NEW_LINE> url = url.with_host("api.github.com").with_path("/repos" + url.path) <NEW_LINE> return str(url)
Converts a github repository url to the api entry with the general information
625941e69c8ee82313fbbbb5
def get_members(self): <NEW_LINE> <INDENT> members = self.get_members_json(self.base_uri) <NEW_LINE> members_list = [] <NEW_LINE> for member_json in members: <NEW_LINE> <INDENT> members_list.append(self.create_member(member_json)) <NEW_LINE> <DEDENT> return members_list
Get Members attached to this board. Returns a list of Member objects.
625941e6507cdc57c6307124
def login(self, user=None, password=None): <NEW_LINE> <INDENT> if user: <NEW_LINE> <INDENT> self._user = user <NEW_LINE> <DEDENT> if password: <NEW_LINE> <INDENT> self._password = password <NEW_LINE> <DEDENT> return client_eventlet.NvpApiClientEventlet._login(self)
Login to NVP controller. Assumes same password is used for all controllers. :param user: NVP controller user (usually admin). Provided for backwards compatibility. In the normal mode of operation this should be None. :param password: NVP controller password. Provided for backwards compatibili...
625941e65fc7496912cc3dbd
def test_read_set(self): <NEW_LINE> <INDENT> self.assertRaises(AttributeError, setattr, self.rw, 'read', 42)
read is readonly
625941e65166f23b2e1a5598
def check_config(dbdriver, dbtype, dbhost, dbuser, dbpasswd, testdb): <NEW_LINE> <INDENT> global DBDRIVER, DBTYPE, DBHOST, DBUSER, DBPASSWD, TESTDB, DBSCHEMA <NEW_LINE> global SYSTEM, SQL_FILE <NEW_LINE> DBDRIVER = dbdriver <NEW_LINE> DBTYPE = dbtype <NEW_LINE> DBHOST = dbhost <NEW_LINE> DBUSER = dbuser <NEW_LINE> DBPA...
Verify the database settings work for connecting.
625941e6498bea3a759b9eed
def batch_flatten(t): <NEW_LINE> <INDENT> return tf.reshape(t, [tf.shape(t)[0], -1])
Reshape tensor so that it is flat vector (except for batch dimension)
625941e6a4f1c619b28b046e
def create_clause_table(avg_clause_list, names, num_files): <NEW_LINE> <INDENT> all_items = [] <NEW_LINE> key_list = get_key_list(avg_clause_list) <NEW_LINE> all_items = [] <NEW_LINE> for key in key_list: <NEW_LINE> <INDENT> add_item = [key] <NEW_LINE> added_gold = False <NEW_LINE> for avg_clause in avg_clause_list: <N...
Create a table with F-scores per clause, order by gold instances and print per clause type
625941e615baa723493c43b8
def __init__(self, filename, clusterFinal, samples): <NEW_LINE> <INDENT> self._clusters = clusterFinal <NEW_LINE> self._filename = filename <NEW_LINE> self._samples = samples <NEW_LINE> self._closestExemplar = []
Writes the file with the closest Sample to the centroid of the cluster
625941e68da39b475bd653b8
def gen_captcha(text, fnt, fnt_sz, f, fmt='JPEG'): <NEW_LINE> <INDENT> fgcolor = random.randint(0,0xffff00) <NEW_LINE> bgcolor = fgcolor ^ 0xffffff <NEW_LINE> font = ImageFont.truetype(fnt,fnt_sz) <NEW_LINE> dim = font.getsize(text) <NEW_LINE> im = Image.new('RGB', (dim[0]+5,dim[1]+5), bgcolor) <NEW_LINE> d = ImageDraw...
Generate a captcha image
625941e6462c4b4f79d1db0f
def get_packed_plastic_region(self, synapse_row, weight_scale, n_synapse_type_bits): <NEW_LINE> <INDENT> abs_scaled_weights = numpy.asarray( numpy.abs(synapse_row.weights) * weight_scale, dtype='uint16') <NEW_LINE> if (len(abs_scaled_weights) % 2) != 0: <NEW_LINE> <INDENT> abs_scaled_weights = numpy.asarray(numpy.appen...
Gets the plastic region of the row as an array of 32-bit words
625941e6f548e778e58cd9bf
def datetimereader(datetimeattribute, parsingfunction=ymdhmsparser): <NEW_LINE> <INDENT> def readerfunction(targetconnection, row, namemapping = {}): <NEW_LINE> <INDENT> atttouse = (namemapping.get(datetimeattribute) or datetimeattribute) <NEW_LINE> return parsingfunction(row[atttouse]) <NEW_LINE> <DEDENT> return reade...
Return a function that converts a certain dict member to a datetime When setting, fromfinder for a tables.SlowlyChangingDimension, this method can be used for generating a function that picks the relevant dictionary member from each row and converts it. Arguments: - datetimeattribute: the attribute the generated func...
625941e650485f2cf553d1db
def kill_leader(*args, **kwargs): <NEW_LINE> <INDENT> node = kwargs['target'] <NEW_LINE> signal = (kwargs['udf1'] if kwargs['udf1'] and kwargs['udf1'] > 0 else "") <NEW_LINE> subprocess.call(["pkill", signal, "-f", "-u", "root", node]) <NEW_LINE> logging.info("Process killed: %s" % node)
kwargs['target']: Linux process to kill kwargs['udf1']: Signal to send to pkill
625941e666673b3332b924d0
def robust_optimize(self, robustness_functions, scenarios, algorithm=EpsNSGAII, nfe=10000, convergence_freq=1000, logging_freq=5, **kwargs): <NEW_LINE> <INDENT> return robust_optimize(self._msis, robustness_functions, scenarios, self, algorithm=algorithm, nfe=nfe, convergence_freq=convergence_freq, logging_freq=logging...
convenience method for robust optimization. is forwarded to :func:robust_optimize, with evaluator and models arguments added in.
625941e6ec188e330fd5abd6
def allocate_fixed_ip(self, context, instance_id, network, **kwargs): <NEW_LINE> <INDENT> LOG.debug('Allocate fixed IP on network %s', network['uuid'], instance_uuid=instance_id) <NEW_LINE> vif = objects.VirtualInterface.get_by_instance_and_network( context, instance_id, network['id']) <NEW_LINE> if vif is None: <NEW_L...
Gets a fixed IP from the pool.
625941e6796e427e537b0a09
def test_validate_on_invalid_mask(self): <NEW_LINE> <INDENT> args = (enums.CryptographicAlgorithm.AES, 128, self.bytes_128a) <NEW_LINE> kwargs = {'masks': ['invalid']} <NEW_LINE> self.assertRaises(TypeError, objects.SymmetricKey, *args, **kwargs)
Test that a TypeError is raised when an invalid mask value is used to construct a SymmetricKey.
625941e691f36d47f21ac936
def __init__(self, recipients=None, template=None, template_vars=None): <NEW_LINE> <INDENT> self._recipients = None <NEW_LINE> self._template = None <NEW_LINE> self._template_vars = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.recipients = recipients <NEW_LINE> self.template = template <NEW_LINE> if templa...
TemplatePushResource - a model defined in Swagger
625941e6442bda511e8be851
def bootstrap_repo(self, directory): <NEW_LINE> <INDENT> python_fallback = False <NEW_LINE> if sys.platform.startswith('win') and not self.FindExecutable('7z'): <NEW_LINE> <INDENT> python_fallback = True <NEW_LINE> <DEDENT> elif sys.platform.startswith('darwin'): <NEW_LINE> <INDENT> python_fallback = True <NEW_LINE> <D...
Bootstrap the repo from Google Stroage if possible. More apt-ly named bootstrap_repo_from_cloud_if_possible_else_do_nothing().
625941e6e8904600ed9f2373
def test_promoter_repression(self): <NEW_LINE> <INDENT> tests = [(';N10[]3F-5.0[]!AAA3SP5AAAN3[]7SR15[]GATTA!CA5GGTAC;', 2), (';N10[]3F-10.3[]CCT!T3SP10CCTTN3[]7R15[]GATTA!CA5GGTAC;', 2)] <NEW_LINE> for seq, len_units in tests: <NEW_LINE> <INDENT> c = cell.Cell(seq) <NEW_LINE> c.read_seq() <NEW_LINE> c.run_all() <NEW_L...
Repress promoter with transcription factors
625941e6de87d2750b8601d6
@cli.command() <NEW_LINE> @click.argument('word') <NEW_LINE> def define(word): <NEW_LINE> <INDENT> with spinner(): <NEW_LINE> <INDENT> words = lexicon.define( word, ) <NEW_LINE> <DEDENT> print_words(words)
Find the definition of the given word.
625941e6ff9c53063f47c631
@app.route('/employees') <NEW_LINE> def employee_list(): <NEW_LINE> <INDENT> employees = Employee.query.all() <NEW_LINE> return render_template('employees.html',employees=employees)
A list of all employees
625941e6e1aae11d1e74a0fb
def is_valid_range(self, num): <NEW_LINE> <INDENT> return _NumberCheck.in_range(num, self.low, self.high)
Tests whether the given number is valid for this entry widgets range Args: num: The number to range test Returns: Whether or not the number is in range
625941e607d97122c4178cd5
def subprocess_call(): <NEW_LINE> <INDENT> subprocess.call(["python","datas.py"])
阻塞,主程序必须等待命令执行完毕
625941e60c0af96317bb8627