code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def testUrlToTextRequest(self): <NEW_LINE> <INDENT> pass
Test UrlToTextRequest
625941e0b545ff76a89141a0
def get_initials(full_name): <NEW_LINE> <INDENT> initials = "".join(item[0].upper() for item in full_name.split()) <NEW_LINE> return initials
return initials of full name
625941e0aad79263cf390dd1
def create_media_stub(): <NEW_LINE> <INDENT> user = request.environ['repoze.who.identity']['user'] <NEW_LINE> timestamp = datetime.now().strftime('%b-%d-%Y') <NEW_LINE> m = Media() <NEW_LINE> m.slug = get_available_slug(Media, 'stub-%s' % timestamp) <NEW_LINE> m.title = '(Stub %s created by %s)' % (timestamp, user.disp...
Return a new :class:`Media` instance with helpful defaults. This is used any time we need a placeholder db record, such as when: * Some admin adds a file *before* saving their new media * Some admin uploads a thumbnail *before* saving their new media
625941e0cdde0d52a9e533c0
def test_memoized_b_bins(self): <NEW_LINE> <INDENT> dist = FreqDist(random_characters(1000)) <NEW_LINE> self.assertEqual(dist.B, 26) <NEW_LINE> for letter in random_characters(100, 'abcdef'): <NEW_LINE> <INDENT> dist[letter] += 1 <NEW_LINE> <DEDENT> self.assertEqual(dist.B, 26) <NEW_LINE> del dist.B <NEW_LINE> self.ass...
Test the memoization of B, the number of bins
625941e0d10714528d600071
@jit(nopython=True, fastmath=True, cache=True, parallel=False) <NEW_LINE> def np_clip(arr, a_min, a_max): <NEW_LINE> <INDENT> lower = np.where(arr < a_min, a_min, arr) <NEW_LINE> upper = np.where(lower > a_max, a_max, lower) <NEW_LINE> return upper
Simple numba compatible clipping of array. Both min and max are required
625941e0d18da76e23532864
def get_line_count(filename): <NEW_LINE> <INDENT> line_count = None <NEW_LINE> if os.path.exists(filename): <NEW_LINE> <INDENT> cmd = f"wc -l {filename}" <NEW_LINE> sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) <NEW_LINE> sp_outs = sp.communicate() <NEW_LINE> for info in sp_outs...
Find total number of lines in a file. Args: filename (str): file to count lines Returns: line_count (int): number of lines in the file Raises: Exception: on unknown error in line count subprocess FileNotFoundError: on missing input file
625941e091af0d3eaac9bda6
def modpath_from_file(filename, extrapath=None): <NEW_LINE> <INDENT> base = splitext(abspath(filename))[0] <NEW_LINE> if extrapath is not None: <NEW_LINE> <INDENT> for path_ in extrapath: <NEW_LINE> <INDENT> path = _abspath(path_) <NEW_LINE> if path and base[:len(path)] == path: <NEW_LINE> <INDENT> submodpath = [pkg fo...
given a file path return the corresponding splitted module's name (i.e name of a module or package splitted on '.') :type filename: str :param filename: file's path for which we want the module's name :type extrapath: dict :param extrapath: optional extra search path, with path as key and package name for the path ...
625941e076e4537e8c351a00
def setRel(self, relStr): <NEW_LINE> <INDENT> pass
setRel(string) -> void Sets the rel attribute value.
625941e0596a897236089e47
def test_search_menu(self): <NEW_LINE> <INDENT> addon.run(['plugin://plugin.video.vrt.nu/search', '0', '']) <NEW_LINE> self.assertEqual(plugin.url_for(addon.search), 'plugin://plugin.video.vrt.nu/search') <NEW_LINE> addon.run(['plugin://plugin.video.vrt.nu/search/query', '0', '']) <NEW_LINE> self.assertEqual(plugin.url...
Search VRT NU menu: /search/query/<keywords>/<page>
625941e0435de62698dfdfd8
def testFacilityProperty(self): <NEW_LINE> <INDENT> pass
Test FacilityProperty
625941e0fff4ab517eb2f7c8
def get_validation_generator(self): <NEW_LINE> <INDENT> return self.__class__( method=self.method, nb_frames=self.nbframe - 1, nb_channel=self.nb_channel, target_shape=self.target_shape, classes=self.classes, batch_size=self.batch_size, shuffle=self.shuffle, rescale=self.rescale, glob_pattern=self.glob_pattern, _valida...
Return the validation generator if you've provided split factor
625941e0091ae356686672e3
def __init__(self, channel, q, max_id, min_id, limit, events_filter=None, admins=None): <NEW_LINE> <INDENT> self.channel = channel <NEW_LINE> self.q = q <NEW_LINE> self.max_id = max_id <NEW_LINE> self.min_id = min_id <NEW_LINE> self.limit = limit <NEW_LINE> self.events_filter = events_filter <NEW_LINE> self.admins = ad...
:param TypeInputChannel channel: :param str q: :param int max_id: :param int min_id: :param int limit: :param Optional[TypeChannelAdminLogEventsFilter] events_filter: :param Optional[List[TypeInputUser]] admins: :returns channels.AdminLogResults: Instance of AdminLogResults.
625941e04428ac0f6e5bab7f
def run_tests(test_dir, data_yaml_path, repetitions=10, local_staging_dir=None): <NEW_LINE> <INDENT> all_running_times = {} <NEW_LINE> for candidate_test_yaml in pathlib.Path(test_dir).glob("**/test.yaml"): <NEW_LINE> <INDENT> candidate_test_path = candidate_test_yaml.parent <NEW_LINE> print(candidate_test_yaml, candid...
Discover tests by recursing through test_dir. Run each test repetitions times and report running times.
625941e0d268445f265b51f9
def _update_storage_table_header(request, content_type='application/atom+xml',use_json=True): <NEW_LINE> <INDENT> request = _update_storage_header(request) <NEW_LINE> if content_type: <NEW_LINE> <INDENT> for name, _ in request.headers: <NEW_LINE> <INDENT> if name.lower() == 'content-type': <NEW_LINE> <INDENT> break <NE...
add additional headers for storage table request.
625941e0d10714528d600072
def createToolButtons(self): <NEW_LINE> <INDENT> self.toggleAnimated_toolButton = QtWidgets.QToolButton(self) <NEW_LINE> self.toggleAnimated_toolButton.setText('ANM') <NEW_LINE> self.toggleAnimated_toolButton.setCheckable(True) <NEW_LINE> self.ui.toggleButtons_layout.addWidget(self.toggleAnimated_toolButton) <NEW_LINE>...
Create the 'toggle' buttons for the Attribute browser.
625941e00c0af96317bb8572
def _clean_config(self, config_dict): <NEW_LINE> <INDENT> result = dict() <NEW_LINE> for key, value in config_dict.iteritems(): <NEW_LINE> <INDENT> new_key = key <NEW_LINE> if new_key.startswith("--"): <NEW_LINE> <INDENT> new_key = new_key[2:] <NEW_LINE> <DEDENT> elif new_key.startswith("<") and new_key.endswith(">"): ...
Makes sure that the keys of config_dict are able to be used. For example the "--" prefix of a docopt dict isn't valid and won't populate correctly.
625941e010dbd63aa1bd2f2d
def mean(a, axis=None, dtype=None, out=None, keepdims=False): <NEW_LINE> <INDENT> if not (type(a) is mu.ndarray): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> mean = a.mean <NEW_LINE> return mean(axis=axis, dtype=dtype, out=out) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DE...
Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. `float64` intermediate and return values are used for integer inputs. Parameters ---------- a : array_like Array containing...
625941e04428ac0f6e5bab80
def connect(self, ip, port): <NEW_LINE> <INDENT> if ':' in ip: <NEW_LINE> <INDENT> mode, address = socket.AF_INET6, (ip, port, 0, 0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mode, address = socket.AF_INET, (ip, port) <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> while not self._socke...
Connects to the specified IP and port number. 'timeout' must be given in seconds
625941e001c39578d7e751c6
def _header_record(self, text_count, chapter_count, link_count, image_count): <NEW_LINE> <INDENT> compression = 10 <NEW_LINE> non_text_offset = text_count + 1 <NEW_LINE> chapter_offset = non_text_offset <NEW_LINE> link_offset = chapter_offset + chapter_count <NEW_LINE> if image_count > 0: <NEW_LINE> <INDENT> image_data...
text_count = the number of text pages image_count = the number of images
625941e03617ad0b5ed68281
def run_migrations_online(): <NEW_LINE> <INDENT> alembic_config = config.get_section(config.config_ini_section) <NEW_LINE> db_connection_string = settings["db_connection_string"] <NEW_LINE> alembic_config["sqlalchemy.url"] = db_connection_string <NEW_LINE> connectable = engine_from_config( alembic_config, prefix="sqlal...
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
625941e05e10d32532c5f2b0
def test_read_2(self): <NEW_LINE> <INDENT> string = "100 100\n" <NEW_LINE> input_i, input_j = collatz_read(string) <NEW_LINE> self.assertEqual(input_i, 100) <NEW_LINE> self.assertEqual(input_j, 100)
Test collatz_read for a range (i == j)
625941e05166f23b2e1a54e4
def _validate_trial_condition_exclusivity(self, tr_data: dict) -> None: <NEW_LINE> <INDENT> trial_conditions = {} <NEW_LINE> for key in ['hit', 'miss', 'false_alarm', 'correct_reject', 'auto_rewarded', 'aborted']: <NEW_LINE> <INDENT> trial_conditions[key] = tr_data[key] <NEW_LINE> <DEDENT> on = [] <NEW_LINE> for condit...
ensure that only one of N possible mutually exclusive trial conditions is True
625941e07d847024c06be64a
def _izip_fields(iterable): <NEW_LINE> <INDENT> for element in iterable: <NEW_LINE> <INDENT> if (hasattr(element, '__iter__') and not isinstance(element, str)): <NEW_LINE> <INDENT> for f in _izip_fields(element): <NEW_LINE> <INDENT> yield f <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(element, np.void) and len(tuple(el...
Returns an iterator of concatenated fields from a sequence of arrays.
625941e04e4d5625662d475e
def get_cosine_simialrity(v1, v2): <NEW_LINE> <INDENT> cos_sim = (dot_product(v1 , v2)) / (norm(v2)*norm(v1)) <NEW_LINE> return cos_sim
Calculate the cosine similarity = v1 * v2 / (|v1| * |v2|)
625941e0e64d504609d74bcb
def test_make( self, controller, verify_convent, add_flashmsg, redirect, move_to_box, matchdict ): <NEW_LINE> <INDENT> matchdict['room_id'] = '10' <NEW_LINE> verify_convent.return_value = True <NEW_LINE> controller.make() <NEW_LINE> verify_convent.assert_called_once_with() <NEW_LINE> move_to_box.assert_called_once_with...
GameCopyToBoxController should verify convent, move game copy to box and redirect to gamecopy:list
625941e0a8370b7717052c29
def parse_main_page(self, response): <NEW_LINE> <INDENT> sel = Selector(response) <NEW_LINE> main_data = sel.xpath('//a/@href').extract() <NEW_LINE> for link in main_data: <NEW_LINE> <INDENT> if 'stop-and-shop/weekly-ads-sales/' in link and 'promotionpagenumbers' in link: <NEW_LINE> <INDENT> link = self.star...
parse_main_page parse the page http://www.shoplocal.com/ and return all links that include: 1. stop-and-shop/weekly-ads-sales/ 2. promotionpagenumbers
625941e0a79ad161976cc4d0
def _assess_id(self, rpc): <NEW_LINE> <INDENT> if "id" in rpc["call"] and rpc["call"]["id"] != None: <NEW_LINE> <INDENT> rpc["rpc_id"] = rpc["call"]["id"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rpc["notification"] = True
Assess the id
625941e07b180e01f3dc4b82
def readFile(self, file_name, directory=None): <NEW_LINE> <INDENT> self.file_name = file_name <NEW_LINE> self.directory = file_name[:-5] <NEW_LINE> self._unzipFiles() <NEW_LINE> self.decodePlistFiles(self.directory) <NEW_LINE> print(file_name)
Unzips the file, parses it, turns information into a structure.
625941e057b8e32f52483829
def perform_calc(tokens): <NEW_LINE> <INDENT> operator = tokens[0] <NEW_LINE> first_arg = tokens[1] <NEW_LINE> second_arg = tokens[2] <NEW_LINE> if isinstance(first_arg, list): <NEW_LINE> <INDENT> first_arg = perform_calc(first_arg) <NEW_LINE> <DEDENT> if isinstance(second_arg, list): <NEW_LINE> <INDENT> second_arg = p...
tokens is of the form ['+', p, q]
625941e063f4b57ef000149a
def test_tables_exist(self): <NEW_LINE> <INDENT> self.assertTrue(DwellingType.objects.count() > 0) <NEW_LINE> self.assertTrue(LandUse.objects.count() > 0) <NEW_LINE> self.assertTrue(Location.objects.count() > 0) <NEW_LINE> self.assertTrue(Planner.objects.count() > 0) <NEW_LINE> self.assertTrue(ProjectFeature.objects.co...
Tables successfully created
625941e0e5267d203edce024
def transform(self): <NEW_LINE> <INDENT> self.validate_ports() <NEW_LINE> if self.input_a.variable.ndim >= 2: <NEW_LINE> <INDENT> xA = T.flatten(self.input_a.variable, outdim=2) <NEW_LINE> xB = T.flatten(self.input_b.variable, outdim=2) <NEW_LINE> axis = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> xA = self.input_a...
Transform inputs to outputs.
625941e0442bda511e8be79f
def get_last_time_diff(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> t = int(time.time()) <NEW_LINE> if self.last_time == -1: <NEW_LINE> <INDENT> f = open(self.time_file, 'r') <NEW_LINE> t_old = int(f.read()) <NEW_LINE> f.close() <NEW_LINE> self.last_time = t_old <NEW_LINE> <DEDENT> if self.last_time > t: return ...
returns time difference to last check in seconds >=0 or -1 on error
625941e0dc8b845886cb58c2
def current_desc_tol_idx(self): <NEW_LINE> <INDENT> self.start_idx = self.mapper.currentIndex() <NEW_LINE> self.start_desc = self.street_browser.ui.descriptionTextEdit.toPlainText() <NEW_LINE> self.start_tol = self.street_browser.ui.tolLineEdit.text()
Grab the current record index and desc
625941e0f548e778e58cd90b
def get_assets(dstore): <NEW_LINE> <INDENT> assetcol = dstore['assetcol'] <NEW_LINE> tagnames = sorted(assetcol.tagnames) <NEW_LINE> tag = {t: getattr(assetcol.tagcol, t) for t in tagnames} <NEW_LINE> dtlist = [] <NEW_LINE> for tagname in tagnames: <NEW_LINE> <INDENT> dtlist.append((tagname, (bytes, 100))) <NEW_LINE> <...
:param dstore: a datastore with keys 'assetcol' :returns: an array of records (asset_ref, tag1, ..., tagN, lon, lat)
625941e0b5575c28eb68e38f
def add_channel(self, channel, owner, package=None, version=None, filename=None): <NEW_LINE> <INDENT> url = '%s/channels/%s/%s' % (self.domain, owner, channel) <NEW_LINE> data, headers = jencode(package=package, version=version, basename=filename) <NEW_LINE> res = self.session.post(url, data=data, headers=headers) <NEW...
Add a channel to the specified files :param channel: channel to add :param owner: The user to add the channel to (all files of all packages for this user) :param package: The package to add the channel to (all files in this package) :param version: The version to add the channel to (all files in this version of the pa...
625941e03317a56b86939fdb
def open_po_fle(self, po_filename): <NEW_LINE> <INDENT> if isinstance(po_filename, io.TextIOWrapper): <NEW_LINE> <INDENT> po_filename = po_filename.name <NEW_LINE> <DEDENT> self.po = polib.pofile(po_filename)
Открыть po-файл :param po_filename: :return:
625941e04d74a7450ccd4550
def gamma_vF_Func(self, vx, vy, vz): <NEW_LINE> <INDENT> vF = sqrt(vx**2 + vy**2 + vz**2) / (hbar / meV) * 1e-12 <NEW_LINE> return vF / self.l_path
vx, vy, vz are in Angstrom.meV l_path is in Angstrom
625941e038b623060ff0b179
def browse(self): <NEW_LINE> <INDENT> import webbrowser <NEW_LINE> webbrowser.open(oeis_url)
Open the OEIS web page in a browser. EXAMPLES:: sage: oeis.browse() # optional -- webbrowser
625941e0dd821e528d63b532
def create_menu_action_unique(ia, parent_menu, menu_text, image=None, tooltip=None, shortcut=None, triggered=None, is_checked=None, shortcut_name=None, unique_name=None, favourites_menu_unique_name=None): <NEW_LINE> <INDENT> orig_shortcut = shortcut <NEW_LINE> kb = ia.gui.keyboard <NEW_LINE> if unique_name is None: <NE...
Create a menu action with the specified criteria and action, using the new InterfaceAction.create_menu_action() function which ensures that regardless of whether a shortcut is specified it will appear in Preferences->Keyboard
625941e0baa26c4b54cb14a8
def tear_down(self): <NEW_LINE> <INDENT> pass
Free any resources held by the camera.
625941e0b7558d58953c5299
def integrate_water_vapor(vmr, p, T=None, z=None, axis=0): <NEW_LINE> <INDENT> if T is None and z is None: <NEW_LINE> <INDENT> q = thermodynamics.vmr2specific_humidity(vmr) <NEW_LINE> g = constants.earth_standard_gravity <NEW_LINE> return -math.integrate_column(q, p, axis=axis) / g <NEW_LINE> <DEDENT> elif T is None or...
Calculate the integrated water vapor (IWV). The basic implementation of the function assumes the atmosphere to be in hydrostatic equilibrium. The IWV is calculated as follows: .. math:: \mathrm{IWV} = -\frac{1}{g} \int q(p)\,\mathrm{d}p For non-hydrostatic atmospheres, additional information on temperature and ...
625941e073bcbd0ca4b2c401
def current_single_word(cursor_offset: int, line: str) -> Optional[LinePart]: <NEW_LINE> <INDENT> for m in _current_single_word_re.finditer(line): <NEW_LINE> <INDENT> if m.start(1) <= cursor_offset <= m.end(1): <NEW_LINE> <INDENT> return LinePart(m.start(1), m.end(1), m.group(1)) <NEW_LINE> <DEDENT> <DEDENT> return Non...
the un-dotted word just before or under the cursor
625941e0379a373c97cfaed2
def _create_family_invlogit(self, name, value, g_mu=None, g_tau=15**-2, std_std=0.2, std_value=.1): <NEW_LINE> <INDENT> if g_mu is None: <NEW_LINE> <INDENT> g_mu = value <NEW_LINE> <DEDENT> value_trans = np.log(value) - np.log(1-value) <NEW_LINE> g_mu_trans = np.log(g_mu) - np.log(1-g_mu) <NEW_LINE> knodes = OrderedDic...
Similar to _create_family_normal_normal_hnormal() but adds a invlogit transform knode to the subject and group mean nodes. This is useful when the parameter space is restricted from [0, 1]. See _create_family_normal_normal_hnormal() help for more information.
625941e0566aa707497f48ef
def constrain(self, var, par, fcon=None): <NEW_LINE> <INDENT> var_ref = self.__getRef(var) <NEW_LINE> varnc = _convertCallable(var) <NEW_LINE> if fcon: <NEW_LINE> <INDENT> fc = self.FCON[fcon] <NEW_LINE> pdffit2.constrain_int(self._handle, var_ref, varnc, par, fc) <NEW_LINE> <DEDENT> elif isinstance(par, six.string_typ...
constrain(var, par[, fcon]) --> Constrain a variable to a parameter. A variable can be constrained to a number or equation string. var -- variable to constrain, such as x(1) par -- parameter which to constrain the variable. This can be an integer or an equation string containing a reference ...
625941e085dfad0860c3b1e8
def forwardable(cls): <NEW_LINE> <INDENT> if 'delegates' not in forwardable.__dict__: <NEW_LINE> <INDENT> return cls <NEW_LINE> <DEDENT> for attr in forwardable.__dict__['delegates']: <NEW_LINE> <INDENT> symbols = forwardable.__dict__['delegates'][attr] <NEW_LINE> for symb in symbols: <NEW_LINE> <INDENT> if hasattr(cls...
Class decorator that allows for the definition of delegators (in conjunction with `def_delegators`), just like the Forwardable module in Ruby. *Note that this pattern does not work for nested classes* :Examples: >>> class NameContainer(object): ... name = "" ... def __init__(self, name): ... self.nam...
625941e07047854f462a1791
def decode(rle: list) -> Iterable: <NEW_LINE> <INDENT> return chain.from_iterable(repeat(elm, cnt) for elm, cnt in rle)
Decodes RLE-encoded sequence, returns iterator
625941e0d4950a0f3b08c6d6
def getGuessedWord(secretWord, lettersGuessed): <NEW_LINE> <INDENT> guessed_string = "" <NEW_LINE> for letter in secretWord: <NEW_LINE> <INDENT> if letter in lettersGuessed: <NEW_LINE> <INDENT> guessed_string += letter <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> guessed_string += "_" <NEW_LINE> <DEDENT> <DEDENT> retu...
secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far.
625941e096565a6dacc8fa56
def to_serializable(o: Any) -> Any: <NEW_LINE> <INDENT> if isinstance(o, UUID): <NEW_LINE> <INDENT> return str(o) <NEW_LINE> <DEDENT> if ( isinstance(o, IPv4Address) or isinstance(o, IPv6Address) or isinstance(o, IPv4Network) or isinstance(o, IPv6Network) ): <NEW_LINE> <INDENT> return str(o) <NEW_LINE> <DEDENT> if isin...
Convert an object into an object that the JSON encode can serialize. Args: o: Object to convert. Returns: Serializable object. Raises: TypeError: in case no conversion was possible.
625941e0507cdc57c630706e
def set_model_attr(self, field, value, validator=None): <NEW_LINE> <INDENT> logging.debug('%s = %s' % (field, value)) <NEW_LINE> super().set_model_attr(field, value, validator) <NEW_LINE> self._dirty = True <NEW_LINE> self.refresh_sensitivity()
Set attributes on the model and update the GUI as expected.
625941e0be383301e01b580b
def get_layer(self, content: str, base_image_id: str) -> str: <NEW_LINE> <INDENT> return self.db.get_cached_layer(content, base_image_id)
provide a layer for given content and base_image_id; if there is such layer in cache store, return its layer_id :param content: :param base_image_id: :return:
625941e067a9b606de4a8243
def test(self, response): <NEW_LINE> <INDENT> from scrapy.shell import inspect_response <NEW_LINE> inspect_response(response, self)
测试方法,回调进入交互式测试
625941e04c3428357757c6b2
@wrap_name_default("seq_pooling") <NEW_LINE> @wrap_bias_attr_default(has_bias=False) <NEW_LINE> @wrap_param_default(['pooling_type'], default_factory=lambda _: MaxPooling()) <NEW_LINE> @layer_support() <NEW_LINE> def pooling_layer(input, pooling_type=None, name=None, bias_attr=None, agg_level=AggregateLevel.EACH_TIMEST...
Pooling layer for sequence inputs, not used for Image. The example usage is: .. code-block:: python seq_pool = pooling_layer(input=layer, pooling_type=AvgPooling(), agg_level=AggregateLevel.EACH_SEQUENCE) :param agg_level: AggregateLevel.EACH_TIMESTEP or ...
625941e063f4b57ef000149b
def test_showcase_admin_list_unauthorized_creds(self): <NEW_LINE> <INDENT> not_a_sysadmin = factories.User() <NEW_LINE> context = {'user': not_a_sysadmin['name'], 'model': None} <NEW_LINE> nosetools.assert_raises(toolkit.NotAuthorized, helpers.call_auth, 'ckanext_showcase_admin_list', context=context)
Calling showcase admin list with unauthorized user raises NotAuthorized.
625941e0293b9510aa2c361e
def _set_inter_level_propagation_policies(self, v, load=False): <NEW_LINE> <INDENT> if hasattr(v, "_utype"): <NEW_LINE> <INDENT> v = v._utype(v) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> t = YANGDynClass( v, base=inter_level_propagation_policies.inter_level_propagation_policies, is_container="container", yang_name="...
Setter method for inter_level_propagation_policies, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/global/inter_level_propagation_policies (container) If this variable is read-only (config: false) in the source YANG file, then _set_inter_level_propagation_policies is considered as...
625941e0d53ae8145f87a5f5
def addNodeBefore(self, new_value, before_node): <NEW_LINE> <INDENT> new_node = Node(new_value) <NEW_LINE> current = self.head <NEW_LINE> while str(current) != str(before_node): <NEW_LINE> <INDENT> current = current.next <NEW_LINE> <DEDENT> if str(current) == str(before_node): <NEW_LINE> <INDENT> self.length +=1 <NEW_L...
takes a value and adds before the before_node
625941e04f88993c3716c3f0
def __init__(self, fname): <NEW_LINE> <INDENT> file_object = open(fname,'r') <NEW_LINE> self.name = file_object.readline() <NEW_LINE> self.flags = file_object.readline().split() <NEW_LINE> self.nlayers = file_object.readline().split() <NEW_LINE> DataLayout = np.dtype([('rad',np.float32,1), ('rho',np.float32,1), ('...
initializes the class from a 1d model file :param fname: file name of the model file
625941e050485f2cf553d127
def moveDamagedShips(self): <NEW_LINE> <INDENT> for shipID in self.shipsFrom: <NEW_LINE> <INDENT> myShip = self.game.myShips[shipID] <NEW_LINE> if myShip['strength'] < 100.0: <NEW_LINE> <INDENT> self.shipsFrom.remove(shipID) <NEW_LINE> self.shipsTo.append(shipID)
Move only Damaged Ships
625941e076d4e153a657eebe
def quantize(model, per_channel=True, nbits=8, quantization_mode=QuantizationMode.IntegerOps, static=False, asymmetric_input_types=False, input_quantization_params=None, output_quantization_params=None): <NEW_LINE> <INDENT> if nbits == 8: <NEW_LINE> <INDENT> input_qType = onnx_proto.TensorProto.UINT8 <NEW_LINE> weight_...
Given an onnx model, create a quantized onnx model and save it into a file :param model: ModelProto to quantize :param per_channel: quantize weights per channel :param nbits: number of bits to represent quantized data. Currently only supporting 8-bit types :param quantization_mode: Can be one of the QuantizationMod...
625941e02ae34c7f2600d4bd
@pytest.fixture <NEW_LINE> def client_mock(mock_fetch_json): <NEW_LINE> <INDENT> return mock_fetch_json, TextUnitedClient(company_id=123, api_key='abc')
Return a TextUnitedClient instance with the fetch_json mocked.
625941e05166f23b2e1a54e5
def get_parliament_members_urls(self) -> list: <NEW_LINE> <INDENT> directory = self.read_html(self.url) <NEW_LINE> return [ a.attrs["href"] for a in directory.select(".single-mp a") if a.attrs["href"].startswith("https") ]
Retrieve a list of members direct URL which link to their Parliament's profile.
625941e07d43ff24873a302f
def _load_compatibility(self): <NEW_LINE> <INDENT> metrics_uuid = self._state.get_complex_dict('metrics_uuid', {}) <NEW_LINE> thresholds = self._state.get_complex_dict('thresholds', {}) <NEW_LINE> services_uuid = self._state.get_complex_dict('services_uuid', {}) <NEW_LINE> for (key, metric_uuid) in metrics_uuid.items()...
Load cache information from old keys and remove thems
625941e0de87d2750b860122
def __parse_arguments(self): <NEW_LINE> <INDENT> args = self.parser.parse_args() <NEW_LINE> self.number_of_inputs = len(args.snapshots) <NEW_LINE> self.snapshot_list = args.snapshots <NEW_LINE> self.catalogue_list = args.catalogues <NEW_LINE> self.directory_list = args.input_directories <NEW_LINE> self.name_list = ( ar...
Parses the arguments from the ``parser``.
625941e026068e7796caf070
def rule7(self, formula): <NEW_LINE> <INDENT> return True
not implemented, due to limited usefulness :return:
625941e0d7e4931a7ee9e2ab
def strip_textpad(text): <NEW_LINE> <INDENT> if text is None: <NEW_LINE> <INDENT> return text <NEW_LINE> <DEDENT> if '\n' not in text: <NEW_LINE> <INDENT> return text.rstrip() <NEW_LINE> <DEDENT> stack, current_line = [], '' <NEW_LINE> for line in text.split('\n'): <NEW_LINE> <INDENT> if line.endswith(' '): <NEW_LINE>...
Attempt to intelligently strip excess whitespace from the output of a curses textpad.
625941e029b78933be1e5a34
def __init__(self, temboo_session): <NEW_LINE> <INDENT> Choreography.__init__(self, temboo_session, '/Library/LastFm/User/GetArtistTracks')
Create a new instance of the GetArtistTracks Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied.
625941e08c3a87329515874b
def get_num_owners(self) -> int: <NEW_LINE> <INDENT> return Participant.query.join(QueueRole).filter( QueueRole.name == 'Owner', Participant.queue_id == g.queue.id).count()
Get number of owners for the global, current queue.
625941e0aad79263cf390dd3
def get_index_in_crossing_array(self): <NEW_LINE> <INDENT> crossing_index_in_crossing_array = {} <NEW_LINE> for i in range(len(self.crossing_array)): <NEW_LINE> <INDENT> for j in range(len(self.crossing_array[0])): <NEW_LINE> <INDENT> crossing_index_in_crossing_array[self.crossing_array[i][j].crossing_id] = (i, j) <NEW...
得到每个路口在路口的矩阵中的索引的map :return: crossing_index_in_crossing_array
625941e015fb5d323cde0ea1
def update_cluster_node(self, cluster_id, node_id, **kwargs): <NEW_LINE> <INDENT> return self.http.patch(url_maker("/clusters", cluster_id, "nodes", node_id), **kwargs)
Updated node information
625941e0bde94217f368317a
def start(self, extra_args=None, stderr=None, *args, **kwargs): <NEW_LINE> <INDENT> if extra_args is None: <NEW_LINE> <INDENT> extra_args = self.extra_args <NEW_LINE> <DEDENT> if stderr is None: <NEW_LINE> <INDENT> stderr = self.stderr <NEW_LINE> <DEDENT> delete_cookie_file(self.datadir) <NEW_LINE> self.process = subpr...
Start the node.
625941e0f8510a7c17cf9a8b
def fdiff(self, argindex=1): <NEW_LINE> <INDENT> if not (1 <= argindex <= len(self.args)): <NEW_LINE> <INDENT> raise ArgumentIndexError(self, argindex) <NEW_LINE> <DEDENT> if not self.args[argindex - 1].is_Symbol: <NEW_LINE> <INDENT> arg_dummy = C.Dummy('xi_%i' % argindex) <NEW_LINE> arg_dummy.dummy_index = hash(self.a...
Returns the first derivative of the function.
625941e045492302aab5e654
def derror(target, y): <NEW_LINE> <INDENT> return target-y
Derivative of the error function.
625941e0d18da76e23532867
@registry.register_hparams <NEW_LINE> def rl_modelrl_tiny(): <NEW_LINE> <INDENT> return rl_modelrl_base().override_from_dict( tf.contrib.training.HParams( epochs=2, true_env_generator_num_steps=64, simulated_env_generator_num_steps=64, model_train_steps=2, ppo_epochs_num=2, ppo_time_limit=5, ppo_epoch_length=5, ppo_num...
Tiny set for testing.
625941e044b2445a33932420
@register.filter <NEW_LINE> def subtract_one(length): <NEW_LINE> <INDENT> return length - 1
Subtract one from int:length and return the difference.
625941e073bcbd0ca4b2c402
def search(self, text): <NEW_LINE> <INDENT> url = '%s/search' % self._site <NEW_LINE> headers = std_headers() <NEW_LINE> if self.hasAccess(): <NEW_LINE> <INDENT> headers.update(self._credential.getAuthorization('POST', url)) <NEW_LINE> <DEDENT> data = {'SearchableText': text, 'portal_type': 'Workspace'} <NEW_LINE> resp...
This is a Plone style search so wildcards are necessary.
625941e007d97122c4178c20
def mergeSort(self, head): <NEW_LINE> <INDENT> if head is None or head.next is None: <NEW_LINE> <INDENT> return head <NEW_LINE> <DEDENT> mid = self.findMid(head) <NEW_LINE> newhead = mid.next <NEW_LINE> mid.next = None <NEW_LINE> left = self.mergeSort(head) <NEW_LINE> right = self.mergeSort(newhead) <NEW_LINE> return s...
input: ListNode head return: ListNode
625941e056b00c62f0f149e8
def is_charm_interface(asset_path): <NEW_LINE> <INDENT> return ( f_exists(asset_path, 'interface.yaml') and not f_exists(asset_path, '.build.manifest') and not f_exists(asset_path, 'layer.yaml') )
Return True if the contents of asset_path appear to be a Juju charm interface.
625941e00383005118ecf96e
def dateCreated(self, request, tag): <NEW_LINE> <INDENT> return self.original.dateCreated.asHumanly()
@return: creation date of our blurb
625941e099fddb7c1c9de71c
def load_line_geo_txt(file, sep=',', header=0, fooder=0, encoding='utf-8', ptype='LONG_LAT'): <NEW_LINE> <INDENT> if ptype == 'LONG_LAT': <NEW_LINE> <INDENT> names = ['ID', 'X', 'y', 'LONG', 'LAT'] <NEW_LINE> formats = ['i2', 'f8', 'f8', 'f8', 'f8'] <NEW_LINE> x_pos = 'LONG' <NEW_LINE> y_pos = 'LAT' <NEW_LINE> <DEDENT>...
Read line geographic data from txt/csv file Parameters ---------- file : str 要读取的文件路径. sep : string 分隔符. header : integer 开头几行不要. fooder : integer 结尾几行不要. encoding : 编码方式 默认为utf-8, 中文系统常用到gbk. ptype : {'LONG_LAT', 'XY'}, optional 指明地理文件中的是经纬度还是坐标, 是'LONG_LAT'则返回字典值中结构数组的field为X', 'y', 'LONG...
625941e0283ffb24f3c55c8a
def __init__(self, *_, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not self.create_statement or not isinstance(self.create_statement, str): <NEW_LINE> <INDENT> raise AttributeError('Invalid CREATE statement defined') <NEW_LINE> <DEDENT> if not self.drop_statement or not isinstance(self.drop_statement, st...
Initialize Datamodel
625941e0091ae356686672e5
def popular_trip(df): <NEW_LINE> <INDENT> print('-'*80) <NEW_LINE> print('Calculating Trip Duration...') <NEW_LINE> start_time = time.time() <NEW_LINE> print("This took %s seconds.\n" % (time.time() - start_time)) <NEW_LINE> popular_trip = df[['Start Station', 'End Station']].groupby(['Start Station', 'End Station']).s...
Displays statistics on the total and average trip duration.
625941e0287bf620b61d3dee
def get_constant_dy(self): <NEW_LINE> <INDENT> return self.__constant_dy
This function will return a variable. (a velocity) :return: self.__constant_dy
625941e0a8ecb033257d3458
def process_signals(self, signals): <NEW_LINE> <INDENT> if self._stopping: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not self._client or not self._client_ready: <NEW_LINE> <INDENT> self.logger.warning( "Tried to send to a non-existent or " "terminated web socket, dropping signals") <NEW_LINE> return <NEW_LINE> ...
Send content to the socket.io room.
625941e0f7d966606f6aa395
def writeCommand(self, command): <NEW_LINE> <INDENT> self.verifyCommand(command) <NEW_LINE> hex_command = self.asciiCommandToHex(command) <NEW_LINE> try: <NEW_LINE> <INDENT> self.connectSerial() <NEW_LINE> self.serial_connection.write(hex_command) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.disconnectSerial()
Write a command as an ascii string, will be converted to hex. Args: command: (string) ascii characters to be hexified for writing to serial
625941e04428ac0f6e5bab81
def test_async_produce_context(self): <NEW_LINE> <INDENT> payload = uuid4().bytes <NEW_LINE> with self._get_producer(min_queued_messages=1) as producer: <NEW_LINE> <INDENT> producer.produce(payload) <NEW_LINE> <DEDENT> message = self.consumer.consume() <NEW_LINE> assert message.value == payload
Ensure that the producer works as a context manager
625941e0462c4b4f79d1da5c
def angle(a, b, c=None): <NEW_LINE> <INDENT> pass
angle(u, v) --> float Returns the angle of rotation between u and v. u and v should be 3 dimensional Vectors representing 3D vectors. Note: this angle is not signed, use axis to know the direction of the rotation. >>> u = VectorN(1.0, 0.0, 0.0) >>> v = VectorN(0.707, 0.0, -0.707) >>> round(angle(u, v), 7) 0.7853982 ...
625941e067a9b606de4a8244
def _fits(self,value,cap=None): <NEW_LINE> <INDENT> if cap is None : cap=self._capacity <NEW_LINE> if isinstance(value,(int,float)): <NEW_LINE> <INDENT> return value<=cap <NEW_LINE> <DEDENT> if isinstance(value,set): <NEW_LINE> <INDENT> return len(value)<=cap <NEW_LINE> <DEDENT> return all(itertools.imap(self._fits,zip...
compare value to capacity
625941e00c0af96317bb8574
def _tile_image(self, data): <NEW_LINE> <INDENT> image = Image.open(BytesIO(data)) <NEW_LINE> return image.convert('RGBA')
Tile binary content as PIL Image.
625941e00c0af96317bb8575
def std_to_prob(std): <NEW_LINE> <INDENT> return (1-(stats.norm.cdf(abs(std))-stats.norm.cdf(-abs(std))))
Compute probability of having distance>std from the mean=0.
625941e0d8ef3951e32438cb
def to3llh(self): <NEW_LINE> <INDENT> return self.lat, self.lon, self.height
Return this point's lat-, longitude and height. @return: 3-Tuple (lat, lon, h) in (degrees, degrees, meter).
625941e032920d7e50b28560
def deserialize(self, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.pose is None: <NEW_LINE> <INDENT> self.pose = geometry_msgs.msg.PoseStamped() <NEW_LINE> <DEDENT> end = 0 <NEW_LINE> start = end <NEW_LINE> end += 4 <NEW_LINE> (length,) = _struct_I.unpack(str[start:end]) <NEW_LINE> start = end <NEW_LINE> ...
unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str``
625941e071ff763f4b549a1f
def score( self, X, W, labels=None, delta=0.5, attribute_score=skm.calinski_harabasz_score, spatial_score=boundary_fraction, attribute_kw=dict(), spatial_kw=dict(), ): <NEW_LINE> <INDENT> if labels is None: <NEW_LINE> <INDENT> if not hasattr(self, "labels_"): <NEW_LINE> <INDENT> raise Exception("Object must be fit in o...
Computes the score of the given label vector on data in X using convex combination weight in delta. Arguments --------- X : numpy array (N,P) array of data classified into `labels` to score. W : sparse array or numpy array (N,N) array representation of sp...
625941e0fff4ab517eb2f7cb
def size(self): <NEW_LINE> <INDENT> total = 0 <NEW_LINE> for i, p in enumerate(self.data): <NEW_LINE> <INDENT> if i % 2: <NEW_LINE> <INDENT> total += p <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> total -= p <NEW_LINE> <DEDENT> <DEDENT> return total
Returns the total size of the RangeSet (ie, how many integers are in the set).
625941e04428ac0f6e5bab82
def __deinstallPlugin(self): <NEW_LINE> <INDENT> from PluginManager.PluginUninstallDialog import PluginUninstallDialog <NEW_LINE> dlg = PluginUninstallDialog(self.pluginManager, self) <NEW_LINE> dlg.exec_()
Private slot to show a dialog to uninstall a plugin.
625941e0f8510a7c17cf9a8c
def _evaluate_for_train_valid(self): <NEW_LINE> <INDENT> train_predictions, train_length = evaluate( model=self.model, data_loader=self.data_loader['valid_train'], device=self.device) <NEW_LINE> valid_predictions, valid_length = evaluate( model=self.model, data_loader=self.data_loader['valid_valid'], device=self.device...
Evaluate model on train and valid set and get acc and f1 score. Returns: train_acc, train_f1, valid_acc, valid_f1
625941e038b623060ff0b17a
def __init__(self, black, white): <NEW_LINE> <INDENT> self._black = set(black) <NEW_LINE> self._white = set(white) <NEW_LINE> self.reshuffle()
Initializes a new game deck. Args: black: An iterable of black cards -- open-ended questions or fill-in-the-blank cards. white: An iterable of white cards -- answers or values for black cards.
625941e026068e7796caf071
def _mergeAlts(self,rows): <NEW_LINE> <INDENT> r = sorted(rows.ref.values,key=len)[-1] <NEW_LINE> a = rows[rows.ref!=r].alt.iloc[0] <NEW_LINE> if len(a) == 1: <NEW_LINE> <INDENT> alt = a + r[1:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> alt = a <NEW_LINE> <DEDENT> return pd.Series({'ref':r,'alt':alt})
merges alt calls for multiple calls at same pos for one sample
625941e0be8e80087fb20fcb
def test_strip_calls_multiple(self): <NEW_LINE> <INDENT> @strip_calls('a') <NEW_LINE> @strip_calls('b') <NEW_LINE> def foo(): <NEW_LINE> <INDENT> a() <NEW_LINE> b() <NEW_LINE> <DEDENT> def bar(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.assertEqual(foo.func_code.co_code, bar.func_code.co_code)
Testing @strip_calls stripping multiple functions
625941e092d797404e304518
def test_invalid_login(self): <NEW_LINE> <INDENT> def postgresql_login(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> psycopg2.connect("postgres://scott:tiger@0.0.0.0:2504/") <NEW_LINE> <DEDENT> except psycopg2.OperationalError as e: <NEW_LINE> <INDENT> return e <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> opti...
Tests if postgres server responds correctly to a invalid login attempt.
625941e0851cf427c661a899
def on_sanji_message(self, client, userdata, msg): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> message = Message(msg.payload) <NEW_LINE> <DEDENT> except (TypeError, ValueError) as e: <NEW_LINE> <INDENT> _logger.error(e, exc_info=True) <NEW_LINE> return <NEW_LINE> <DEDENT> if message.type() == MessageType.UNKNOWN: <NEW...
This function will recevie all message from mqtt client the client instance for this callback userdata the private user data as set in Client() or userdata_set() message an instance of MQTTMessage. This is a class with members topic, payload, qos, retain.
625941e0c4546d3d9de72dc4
def timing( self, stat: str, delta: Union[int, timedelta], rate: Union[int, float] = None, tags: TagsType = None, ) -> None: <NEW_LINE> <INDENT> stat = self._metric_name(stat, tags) <NEW_LINE> current_app.extensions['statsd_core'].timing( stat, delta, rate=rate if rate is not None else current_app.config['STATSD_RATE']...
Send new timing information. :param delta: Either a number of milliseconds, or a timedelta
625941e05e10d32532c5f2b2