code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def get_flush_data(code): <NEW_LINE> <INDENT> page = '' <NEW_LINE> while page == '': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> url = 'https://basic.10jqka.com.cn/api/stockph/research/' + code + '/stock/' <NEW_LINE> headers = { 'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*... | 获取同花顺数据 | 625941c4b545ff76a8913e00 |
def test_was_published_recently_with_old_question(self): <NEW_LINE> <INDENT> time = timezone.now() - datetime.timedelta(days=1, seconds=1) <NEW_LINE> old_question = Question(pub_date=time) <NEW_LINE> self.assertIs(old_question.was_published_recently(), False) | 以前时间 | 625941c4dd821e528d63b194 |
def __call__(self, mode='array', normalized=True): <NEW_LINE> <INDENT> if normalized: <NEW_LINE> <INDENT> cont = self.norm_container <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cont = self.container <NEW_LINE> <DEDENT> if self.keys is not None: <NEW_LINE> <INDENT> keys = self.keys <NEW_LINE> <DEDENT> else: <NEW_LINE>... | Return either a dictionary or numpy array representation
of the class for use in functions.
Parameter 'mode' must be either 'dict' or 'array' | 625941c4a05bb46b383ec80d |
def test_item_to_be_returned_on_get_request_does_not_exist(self): <NEW_LINE> <INDENT> with self.client: <NEW_LINE> <INDENT> token = self.get_user_token() <NEW_LINE> self.create_bucket(token) <NEW_LINE> response = self.client.get( '/bucketlists/1/items/1', headers=dict(Authorization='Bearer ' + token) ) <NEW_LINE> data ... | Test that the item to be returned on a get request does not exist.
:return: | 625941c43617ad0b5ed67ee2 |
def _get_item(self, item_field, index, auto_index=False): <NEW_LINE> <INDENT> if not item_field: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if index is None: <NEW_LINE> <INDENT> index = 0 <NEW_LINE> <DEDENT> if isinstance(item_field, tuple): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return item_field[index]... | Retrieve an item from a list or a single value.
item_field: can be None, a tuple of a single value
index: if None is same as 0, else is the index for a chain
auto_index: if true will automatically get the final value by adding the
index to the base value (if full list not provided)
If the item_field is no... | 625941c4283ffb24f3c558ec |
def _structured(klearner): <NEW_LINE> <INDENT> return lambda d: LearnerConfig(attach=tc_learner(klearner(d)), label=label_learner_maxent()) | learner configuration pair for a structured learner
(parameterised on a decoder) | 625941c4a8ecb033257d30b7 |
def admin_command(sudo, command): <NEW_LINE> <INDENT> if sudo: <NEW_LINE> <INDENT> if not isinstance(command, list): <NEW_LINE> <INDENT> command = [command] <NEW_LINE> <DEDENT> return ['sudo'] + [cmd for cmd in command] <NEW_LINE> <DEDENT> return command | If sudo is needed, make sure the command is prepended
correctly, otherwise return the command as it came.
:param sudo: A boolean representing the intention of having a sudo command
(or not)
:param command: A list of the actual command to execute with Popen. | 625941c4167d2b6e31218b80 |
def get_caption(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> c = self.findall(".//CAPTION") <NEW_LINE> return c[0].text <NEW_LINE> <DEDENT> except (KeyError, IndexError) as e: <NEW_LINE> <INDENT> return None | Return the <caption> tag text | 625941c47cff6e4e8111796f |
def hashf(self,L): <NEW_LINE> <INDENT> q = self.PPATCpp.order <NEW_LINE> f = fingexp.fingerprint(L) <NEW_LINE> r = utils.b64tompz(f)%q <NEW_LINE> return r | Return a number in Zq computed from a list L of elements
Assuming that all elements of the list has a fingerprint | 625941c45166f23b2e1a5143 |
def system_loader(): <NEW_LINE> <INDENT> system = namedtuple("System", ["clock", "elements", "modules", "dependancies", "regulations"]) <NEW_LINE> system.elements = namedtuple("elements", ['all', 'input', 'output']) <NEW_LINE> system.modules = namedtuple("modules", ['all', 'input', 'output']) <NEW_LINE> system.modules.... | Loads all necessary objects for system operation from database
Configures system and returns system named tuple | 625941c4cdde0d52a9e5301b |
def get(self): <NEW_LINE> <INDENT> args = request.args.to_dict() <NEW_LINE> residues = args.get("res") <NEW_LINE> manure = args.get("f") <NEW_LINE> nitro = args.get("n") <NEW_LINE> phos = args.get("p") <NEW_LINE> rotation = args.get("rot") <NEW_LINE> rep = args.get("rep") <NEW_LINE> combination_results = [] <NEW_LINE> ... | End point for returning all results for a particular year
---
parameters:
- in: header
name: token
type: string
description: Access token
required: true
responses:
200:
description: Returns all results.
| 625941c45f7d997b87174a80 |
def test_delete_json(self, req, dbsession, factories): <NEW_LINE> <INDENT> from webob.multidict import MultiDict <NEW_LINE> from occams import models <NEW_LINE> study = factories.StudyFactory.create() <NEW_LINE> external_service = factories.ExternalServiceFactory.create( study=study, title=u'test-service' ) <NEW_LINE> ... | It should return a single JSON record for the study's external service | 625941c4bd1bec0571d90619 |
def flipEquiv(self, root1, root2): <NEW_LINE> <INDENT> if not root1 or not root2: <NEW_LINE> <INDENT> return root1 == root2 <NEW_LINE> <DEDENT> return root1.val == root2.val and ((self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root2.right)) or ((self.flipEquiv(root1.left, root2.right) and self.f... | :type root1: TreeNode
:type root2: TreeNode
:rtype: bool | 625941c4187af65679ca5108 |
def extract_path(self, PARENT): <NEW_LINE> <INDENT> path = [self.s_goal] <NEW_LINE> s = self.s_goal <NEW_LINE> while True: <NEW_LINE> <INDENT> s = PARENT[s] <NEW_LINE> path.append(s) <NEW_LINE> if s == self.s_start: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return list(path) | Extract the path based on the PARENT set.
:return: The planning path | 625941c40c0af96317bb81d2 |
def camera_alpha_to_theta(self, alpha): <NEW_LINE> <INDENT> theta = alpha - self.markerFromNormal <NEW_LINE> return u.within_pi(theta) | Takes in an alpha and outputs theta from the camera +-180 | 625941c4d164cc6175782d37 |
def __getitem__(self, index): <NEW_LINE> <INDENT> img = Image.open(self.images[index]) <NEW_LINE> anns = self.parse_voc_xml(self.annotations[index])['annotations'] <NEW_LINE> for ann in anns: <NEW_LINE> <INDENT> ann['image_id'] = index <NEW_LINE> <DEDENT> if self.transform is not None: <NEW_LINE> <INDENT> img, anns = s... | Args:
index (int): Index
Returns:
tuple: (image, target) where target is a dictionary of the XML tree. | 625941c43617ad0b5ed67ee3 |
def get_config_form(self, step=None): <NEW_LINE> <INDENT> return {"title": self.name, "inputs": [param.to_dict(self.trans) for param in self.get_inputs().values()]} | Serializes input parameters of a module into input dictionaries. | 625941c492d797404e304173 |
def _generate_decay_model( *, nr_compartments: int, irf: bool, spectral: bool, decay_type: str ) -> dict[str, Any]: <NEW_LINE> <INDENT> compartments = [f"species_{i+1}" for i in range(nr_compartments)] <NEW_LINE> rates = [f"rates.species_{i+1}" for i in range(nr_compartments)] <NEW_LINE> model = { "megacomplex": { f"me... | Generate a decay model dictionary.
Parameters
----------
nr_compartments : int
The number of compartments.
irf : bool
Whether to add a gaussian irf.
spectral : bool
Whether to add a spectral model.
decay_type : str
The dype of the decay
Returns
-------
dict[str, Any] :
The generated model dictiona... | 625941c4442bda511e8be404 |
def priceForBuyBTC(btc_expected,X): <NEW_LINE> <INDENT> p_r = X / (btc_expected * (1 + taker / 100)) <NEW_LINE> p_l = (X - 0.0201) / (btc_expected * (1 + taker / 100)) <NEW_LINE> while (p_r-p_l>0.01): <NEW_LINE> <INDENT> p_n = (p_r + p_l) / 2 <NEW_LINE> X_n = X_for_buyBTC(btc_expected, p_n, taker) <NEW_LINE> if (X_n > ... | X вычисляется по формуле:
fO(x) = округление_в_большую_сторону_до_2_знаков(x)
k-комиссия при транзакции (taker)
X = fO(p*b) + fO(fO(p*b)*k)
Округление можно заменит на добавление необходимой величины:
X = p*b+e + (p*b+e)*k+w = (1+k)p*b+e+w+k*e
где e - необходимая величина, чтобы произведение p*b округлить до двух знако... | 625941c430c21e258bdfa486 |
def return_str(returned_from_drmaa2_call): <NEW_LINE> <INDENT> LOGGER.debug("enter return_str") <NEW_LINE> result = returned_from_drmaa2_call.value <NEW_LINE> DRMAA_LIB.drmaa2_string_free(pointer(returned_from_drmaa2_call)) <NEW_LINE> LOGGER.debug("leave return_str {}".format(result)) <NEW_LINE> if result: <NEW_LINE> <... | Retrieves a string and frees memory associated with the pointer.
Why is the ctypes usual method not good enough? It doesn't free
memory automatically, so wrapping a function like char* get_name()
will lose the char*. | 625941c4be383301e01b5473 |
def depolarize(self, amount): <NEW_LINE> <INDENT> for gate in self.param_gates: <NEW_LINE> <INDENT> gate.depolarize(amount) <NEW_LINE> <DEDENT> for element in self.values(): <NEW_LINE> <INDENT> element._construct_matrix() <NEW_LINE> <DEDENT> self.dirty = True | Depolarize this Instrument by the given `amount`.
Parameters
----------
amount : float or tuple
The amount to depolarize by. If a tuple, it must have length
equal to one less than the dimension of the gate. All but the
first element of each spam vector (often corresponding to the
identity element) ar... | 625941c44e4d5625662d43c4 |
def perform_injection_updates(self): <NEW_LINE> <INDENT> injector_files = self.install_config.injector_files <NEW_LINE> for injector in injector_files: <NEW_LINE> <INDENT> self.config_injector.inject_to_file(injector) | Function that calls the ConfigInjector functions for appending config files.
| 625941c4be7bc26dc91cd5ec |
def get_repository_query(self): <NEW_LINE> <INDENT> raise errors.Unimplemented() | Gets the query for a repository.
Multiple queries can be retrieved for a nested ``OR`` term.
return: (osid.repository.RepositoryQuery) - the repository query
raise: Unimplemented - ``supports_repository_query()`` is
``false``
*compliance: optional -- This method must be implemented if
``supports_repository_q... | 625941c407d97122c4178872 |
def affiche(lst_points, cc): <NEW_LINE> <INDENT> points_proj = [] <NEW_LINE> for p in lst_points: <NEW_LINE> <INDENT> points_proj.append(cc.proj_to_CC(p.lon, p.lat)) <NEW_LINE> <DEDENT> x_cc = [] <NEW_LINE> y_cc = [] <NEW_LINE> for p in points_proj: <NEW_LINE> <INDENT> x_cc.append(p[0]) <NEW_LINE> y_cc.append(p[1]) <NE... | affiche la carte
:param lst_points: liste d'objets Point
:param cc: projection conique conforme
:return: | 625941c4b830903b967e98f7 |
def can_runas(): <NEW_LINE> <INDENT> if salt.utils.platform.is_windows(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> salt.utils.win_runas.runas( 'cmd.exe /c echo 1', 'noexistuser', 'n0existp4ss', ) <NEW_LINE> <DEDENT> except WindowsError as exc: <NEW_LINE> <INDENT> if exc.winerror == 5: <NEW_LINE> <INDENT> return Fal... | Detect if we are running in a limited shell (winrm) and are un-able to use
the runas utility method. | 625941c491f36d47f21ac4db |
def test_module_imports(self): <NEW_LINE> <INDENT> apps = [ 'rms_attachments', 'rms_attachments.migrations', 'rms_attachments.views', ] <NEW_LINE> for a in apps: <NEW_LINE> <INDENT> self.assertTrue(module_exists(a)) | Ensure modules are importable. | 625941c45fcc89381b1e16a8 |
def _generate_samples(): <NEW_LINE> <INDENT> for example in examples: <NEW_LINE> <INDENT> context = ' '.join(example[FeatureNames.STORY]) <NEW_LINE> yield { 'context': ' '.join(context.split()), 'inputs': ' '.join(example[FeatureNames.QUESTION].split()), 'targets': example[FeatureNames.ANSWER] } | sample generator.
Yields:
A dict. | 625941c4eab8aa0e5d26db42 |
def __https_pool(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pool = HTTPSConnectionPool( host=self.__cfg.host, port=self.__cfg.port, maxsize=self.__cfg.threads, timeout=Timeout(connect=self.__cfg.timeout, read=self.__cfg.timeout), block=True) <NEW_LINE> if self._HTTP_DBG_LEVEL <= self.__debug.level: <NEW_LINE> ... | Create HTTP connection pool
:raise HttpsRequestError
:return: urllib3.HTTPConnectionPool | 625941c47d847024c06be2a4 |
def eu2qu(eu): <NEW_LINE> <INDENT> ee = 0.5*eu <NEW_LINE> cPhi = np.cos(ee[...,1:2]) <NEW_LINE> sPhi = np.sin(ee[...,1:2]) <NEW_LINE> qu = np.block([ cPhi*np.cos(ee[...,0:1]+ee[...,2:3]), -P*sPhi*np.cos(ee[...,0:1]-ee[...,2:3]), -P*sPhi*np.sin(ee[...,0:1]-ee[...,2:3]), -P*cPhi*np.sin(ee[...,0:1]+ee[...,2:3])]) <NEW_... | Bunge-Euler angles to quaternion. | 625941c4ec188e330fd5a78c |
def enqueue(self,element) : <NEW_LINE> <INDENT> raise NotImplementedError() | put an element into queue. | 625941c455399d3f0558869e |
def get_args(type_) -> typing.Tuple: <NEW_LINE> <INDENT> if hasattr(typing, 'get_args'): <NEW_LINE> <INDENT> _getter = getattr(typing, "get_args") <NEW_LINE> res = _getter(type_) <NEW_LINE> <DEDENT> elif hasattr(typing.List, "_special"): <NEW_LINE> <INDENT> if ( isinstance(type_, GenericClass) and not type_._special ):... | Get type arguments with all substitutions performed.
For unions, basic simplifications used by Union constructor are performed.
Examples:
```python
from typing_utils import get_args
get_args(Dict[str, int]) == (str, int)
get_args(int) == ()
get_args(Union[int, Union[T, int], str][int]) == (int, str)
... | 625941c46aa9bd52df036d8d |
def get_positions(self): <NEW_LINE> <INDENT> positions = self.get_account_info( fields=["positions"])["securitiesAccount"]["positions"] <NEW_LINE> for pos in positions: <NEW_LINE> <INDENT> pos.update({k: v for k, v in pos["instrument"].items()}) <NEW_LINE> del pos["instrument"] <NEW_LINE> <DEDENT> return pd.DataFrame.f... | Get the account positions.
returns (pandas DataFrame): Account positions. | 625941c444b2445a33932081 |
def Destroy(self): <NEW_LINE> <INDENT> lib.tera_scan_descriptor_destroy(self.desc) | 销毁这个scan_descriptor,释放底层资源,以后不得再使用这个对象 | 625941c463f4b57ef0001107 |
def mobilenetv2b_w1(**kwargs): <NEW_LINE> <INDENT> return get_mobilenetv2(width_scale=1.0, remove_exp_conv=True, model_name="mobilenetv2b_w1", **kwargs) | 1.0 MobileNetV2b-224 model from 'MobileNetV2: Inverted Residuals and Linear Bottlenecks,'
https://arxiv.org/abs/1801.04381.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters. | 625941c48c3a8732951583a3 |
def get_host_system_by_uuid(self, uuid): <NEW_LINE> <INDENT> esx = self.get_service("searchIndex").FindByUuid(uuid=uuid, vmSearch=False) <NEW_LINE> if not esx: <NEW_LINE> <INDENT> raise NotFound("Host system with uuid {0} not found".format(uuid)) <NEW_LINE> <DEDENT> return ESX(esx) | Returns an item by searching for its UUID.
An exception will be raised if the VM cannot be found.
- `uuid` (str) is the UUID of the desired VM. | 625941c456ac1b37e62641bd |
def step(self): <NEW_LINE> <INDENT> cfg = self.cfg <NEW_LINE> cheerio = self.cheerio <NEW_LINE> allowable = cfg.stones.open_direction_for_circle(cheerio, cfg.cheerio_radius, self.speed) <NEW_LINE> if not allowable: <NEW_LINE> <INDENT> raise SimulationError() <NEW_LINE> <DEDENT> if self.sigma: <NEW_LINE> <INDENT> if not... | Perform one time step of the simulation.
:return: cheerio - next load location (point P), False - signifying the simulation is not
finished. | 625941c450485f2cf553cd83 |
def create_stream(self, output_queue, market_ids): <NEW_LINE> <INDENT> listener = betfairlightweight.StreamListener(output_queue=output_queue) <NEW_LINE> stream = self.api.streaming.create_stream(listener=listener) <NEW_LINE> market_filter = filters.streaming_market_filter( market_ids=market_ids ) <NEW_LINE> market_dat... | Create Betfair stream that allow to establish
connection once and receive MarketBook updates in real time | 625941c463f4b57ef0001108 |
def __init__(self, nodes, FL_DISTR, VEL_DISTR, WT_DISTR=None, border_policy='reflect', model=None): <NEW_LINE> <INDENT> self.b = [0] <NEW_LINE> self.nodes = nodes <NEW_LINE> self.collect_fl_stats = False <NEW_LINE> self.collect_wt_stats = False <NEW_LINE> self.border_policy = border_policy <NEW_LINE> self.nr_nodes = le... | Base implementation for models with direction uniformly chosen from [0,pi]:
random_direction, random_walk, truncated_levy_walk
Required arguments:
*nr_nodes*:
Integer, the number of nodes.
*dimensions*:
Tuple of Integers, the x and y dimensions of the simulation area.
*FL_DISTR*:
A function that, ... | 625941c45510c4643540f3d2 |
def reverse(self): <NEW_LINE> <INDENT> raise NotImplementedError("Passive Plugin must have reverse pdns") | Required reverse pdns functionality for passive plugin
Raises:
NotImplementedError: subclasses must implement | 625941c4442bda511e8be405 |
def test_specificId(self): <NEW_LINE> <INDENT> a = Base(8) <NEW_LINE> self.assertEqual(a.id, 8) | assigned id. | 625941c485dfad0860c3ae45 |
def test_drop_table_failure(self): <NEW_LINE> <INDENT> table_name = 'test_droptable_failure' <NEW_LINE> with nested( mock.patch('pika.SelectConnection'), mock.patch('replugin.sqlworker.SQLWorker.notify'), mock.patch('replugin.sqlworker.SQLWorker.send')): <NEW_LINE> <INDENT> worker = sqlworker.SQLWorker( MQ_CONF, logger... | Verify drop_table fails when the table does not exist. | 625941c4a219f33f34628956 |
def _check_params(self): <NEW_LINE> <INDENT> if self.n_estimators <= 0: <NEW_LINE> <INDENT> raise ValueError("n_estimators must be greater than 0 but " "was %r" % self.n_estimators) <NEW_LINE> <DEDENT> if self.learning_rate <= 0.0: <NEW_LINE> <INDENT> raise ValueError("learning_rate must be greater than 0 but " "was %r... | Check validity of parameters and raise ValueError if not valid. | 625941c4925a0f43d2549e60 |
def test_retreive_recipes(self): <NEW_LINE> <INDENT> sample_recipe(user=self.user) <NEW_LINE> sample_recipe(user=self.user) <NEW_LINE> res = self.client.get(RECIPES_URL) <NEW_LINE> recipes = Recipe.objects.all().order_by('id') <NEW_LINE> serailizer = RecipeSerializer(recipes, many=True) <NEW_LINE> self.assertEqual(res.... | Test retreiving recipes | 625941c4be8e80087fb20c2f |
def _ra_file(dev, kind): <NEW_LINE> <INDENT> fileutils.ensure_tree(CONF.networks_path) <NEW_LINE> return os.path.abspath('%s/patron-ra-%s.%s' % (CONF.networks_path, dev, kind)) | Return path to a pid or conf file for a bridge/device. | 625941c4097d151d1a222e46 |
def _do_compare(file1, file2): <NEW_LINE> <INDENT> bufsize = BUFSIZE <NEW_LINE> try: <NEW_LINE> <INDENT> with open(file1, 'rb') as fp1, open(file2, 'rb') as fp2: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> b1 = fp1.read(bufsize) <NEW_LINE> b2 = fp2.read(bufsize) <NEW_LINE> if b1 != b2: <NEW_LINE> <INDENT> retur... | Compare contents of two files. | 625941c45510c4643540f3d3 |
def convert_2d_to_1d(coordinate, n): <NEW_LINE> <INDENT> return coordinate[0] + 2**n * coordinate[1] | Convert a 2D coordinate to a coordinate on a line.
Args:
coordinate(tuple): 2D coordinate
n(int): Number of scales
Returns:
int: 1D coordinate | 625941c40a50d4780f666e7c |
def judgeCircle(self, moves): <NEW_LINE> <INDENT> c = collections.Counter(moves) <NEW_LINE> return c["U"] == c["D"] and c["L"] == c["R"] | :type moves: str
:rtype: bool | 625941c4507cdc57c6306cc2 |
def hasBothChildren(self): <NEW_LINE> <INDENT> return self.rightChild and self.leftChild | :return: | 625941c4627d3e7fe0d68e39 |
def Kcross_grad_X(self, Xstar, d): <NEW_LINE> <INDENT> return _core.CKroneckerCF_Kcross_grad_X(self, Xstar, d) | Kcross_grad_X(CKroneckerCF self, limix::CovarInput const & Xstar, limix::muint_t const d)
Parameters
----------
Xstar: limix::CovarInput const &
d: limix::muint_t const | 625941c49c8ee82313fbb75f |
def _time_axis(self, n): <NEW_LINE> <INDENT> res = self.res(n) <NEW_LINE> size = self._time_window(n) <NEW_LINE> t = np.arange(0, size * res, res, np.float) <NEW_LINE> return t | Get time axis accounting for resolution
Parameters
----------
n : int
Curve number
Returns
-------
`numpy.ndarray`
Time axis as numpy array | 625941c4ab23a570cc25016c |
def __pow__(self, p): <NEW_LINE> <INDENT> if type(p) is int: <NEW_LINE> <INDENT> return Bruch(self.zaehler ** p, self.nenner ** p) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('incompatible types:' + type(p).__name__ + ' should be an int') | Overwrites from Object
Returns the Bruch to a given Power
:param p: the Bruch is multiplied to that power
:return: the result | 625941c423849d37ff7b307b |
def __str__(self): <NEW_LINE> <INDENT> return self.absolute_path | Return the string representation of an entry | 625941c4b545ff76a8913e01 |
def test_get_owned_projects(self): <NEW_LINE> <INDENT> self.user.create_project("projectname") <NEW_LINE> projects = self.user.get_my_projects() <NEW_LINE> self.assertEqual(projects.count(), 1) | Test getting projects owned by a user | 625941c4a4f1c619b28b0028 |
def count(self, func=lambda x: True): <NEW_LINE> <INDENT> return len(self.filter(func)) | Counts the number of elements satisfying a given criterion.
Args:
func (element -> bool): A function that takes in an element
and returns a boolean (True/False). Only those elements
that return True will be counted.
Returns:
int: The number of elements e for which func(e) is True. | 625941c42ae34c7f2600d11c |
def test_ensure_pghops_schema_exists(self): <NEW_LINE> <INDENT> context = pghops.Context(CLUSTER_A_DIRECTORY) <NEW_LINE> context.database = 'db_a3' <NEW_LINE> context.init_pghops_schema = True <NEW_LINE> temp_file = utils.make_temp_file('pghops-unit-test-init-version-script', '.sql') <NEW_LINE> context.sql_file_path = ... | Ensure pghops can find init scripts outside of the target database
directory. | 625941c4656771135c3eb857 |
def wm_to_ergscm(flux): <NEW_LINE> <INDENT> flux = u.Quantity(flux, u.W/u.m**2) <NEW_LINE> dflux = flux.to(u.erg*u.s**(-1)*u.cm**(-2)) <NEW_LINE> return dflux | From W/m^2 to erg/s/cm^2 | 625941c4d10714528d5ffccc |
def finesse_coefficient(R): <NEW_LINE> <INDENT> return 4 * R / (1 - R)**2 | Finesse coefficient of the etalon
Parameters
----------
R : np.float64
Reflectance of the etalon mirrors
Returns
-------
np.float64
Finesse coefficient of the etalon | 625941c4d18da76e235324bf |
def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None): <NEW_LINE> <INDENT> if isinstance(url_or_request, (compat_str, str)): <NEW_LINE> <INDENT> url_or_request = url_or_request.partition('#')[0] <NEW_LINE> <DEDENT> urlh = self._request_webpage(url_or_request, video_id, note, errnote) <NE... | Returns a tuple (page content as string, URL handle) | 625941c426238365f5f0ee57 |
def sampleContext(N): <NEW_LINE> <INDENT> return np.random.uniform(low=-0.05, high=0.05, size=(N, 4)) | Samples N random contexts. | 625941c4009cb60464c6339e |
def persist(data, filename=DB): <NEW_LINE> <INDENT> table_name = datetime.datetime.utcnow().strftime('date%d%m%Y') <NEW_LINE> create = not os.path.exists(filename) <NEW_LINE> db = lite.connect(filename) <NEW_LINE> cursor = db.cursor() <NEW_LINE> cursor.execute("SELECT name FROM sqlite_master WHERE type='table' and " "n... | Bonus1: Persist the results in SQLite3.
Struct of bd:
Tablename: Data of the day (i.e., date280320016)
Items: Id (Autoincrement)
Web
Vowels
Extra: If table exist, update new news. | 625941c423e79379d52ee550 |
def extract_VOC_detections(raw_target): <NEW_LINE> <INDENT> targets = [] <NEW_LINE> annotation = raw_target['annotation'] <NEW_LINE> height = int(annotation['size']['height']) <NEW_LINE> width = int(annotation['size']['width']) <NEW_LINE> objects = annotation['object'] <NEW_LINE> if not isinstance(objects, list): <NEW_... | Given a VOC target, as an XML tree, extract an array of all bounding boxes
and class IDs, each in the format (y1, x1, y2, x2, ID), where bounding box
coordinates are normalized | 625941c476e4537e8c35165c |
def list( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.LocalNetworkGatewayListResult"]: <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('e... | Gets all the local network gateways in a resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either LocalNetworkGatewayListResult or the ... | 625941c407d97122c4178873 |
def admission_days(self): <NEW_LINE> <INDENT> for idx, g in self.grouped: <NEW_LINE> <INDENT> sortedf = g.sort_values(by=self.col_admission) <NEW_LINE> oldi = None <NEW_LINE> for i, row in sortedf.iterrows(): <NEW_LINE> <INDENT> if oldi is None: <NEW_LINE> <INDENT> oldi = i <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>... | Creates a new column containing the days passed between a discharge and the following admission
:return: Self | 625941c424f1403a92600b53 |
def get_partner_to_dm(dm_matching): <NEW_LINE> <INDENT> u, v = dm_matching <NEW_LINE> if u not in ['dm1', 'dm2']: <NEW_LINE> <INDENT> assert v in ['dm1', 'dm2'] <NEW_LINE> return u <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return v | Retrieves the defect the dummy matched to.
:param dm_matching: The tuple containing the dummy and the defect the
the dummy matched to.
:type dm_matching: tuple
:return: The defect the dummy defect matched to.
:rtype: str | 625941c44527f215b584c444 |
def update_team_member(self, owner, team, member_user, body, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.update_team_member_with_http_info(owner, team, member_user, body, **kwargs) | Update team member # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_team_member(owner, team, member_user, body, async_req=True)
>>> result = thread.get()
:param owner: Owner of the namespace (required)
:typ... | 625941c4ec188e330fd5a78d |
def _VersionList(release): <NEW_LINE> <INDENT> return [int(part) for part in str(release).split('.')] | Parse a version string into a list of ints.
Args:
release: The 'release' version, e.g. '1.2.4'.
(Due to YAML parsing this may also be an int or float.)
Returns:
A list of ints corresponding to the parts of the version string
between periods. Example:
'1.2.4' -> [1, 2, 4]
'1.2.3.4' -> [1, 2, 3, 4]... | 625941c496565a6dacc8f6b7 |
def test_for_featured_explorations(self): <NEW_LINE> <INDENT> activity_services.update_featured_activity_references([ activity_domain.ActivityReference( feconf.ACTIVITY_TYPE_EXPLORATION, self.EXP_ID_2) ]) <NEW_LINE> featured_activity_summaries = ( summary_services.get_featured_activity_summary_dicts([ feconf.DEFAULT_LA... | Note that both EXP_ID_1 and EXP_ID_2 are public. However, only
EXP_ID_2 is featured, so the call to get_featured_explorations() should
only return [EXP_ID_2]. | 625941c4b57a9660fec3386e |
def __init__(self, credit_note=None, authorisation=None): <NEW_LINE> <INDENT> if credit_note is None: <NEW_LINE> <INDENT> self._credit_note = None <NEW_LINE> self._authorisation = None <NEW_LINE> return <NEW_LINE> <DEDENT> if not isinstance(credit_note, _CreditNote): <NEW_LINE> <INDENT> raise TypeError("The credit note... | Create a refund for the transaction that resulted in the passed
credit note. Specify the authorisation of the refund. Note
that transactions can only be refunded in full. If you want
to give a partial refund then this is better handled as
a new transaction from the credited to debited accounts.
Note also that you can ... | 625941c47d43ff24873a2c8b |
def find_closest_point(self, target, newset): <NEW_LINE> <INDENT> target = numpy.array(target) <NEW_LINE> newset = numpy.array(newset) <NEW_LINE> ind = numpy.nonzero( numpy.all(distance.cdist(target, newset) > self.alpha[self.level], axis=0)) <NEW_LINE> points = newset[ind] <NEW_LINE> outliers = zip(ind[0], points) <NE... | Find the closest point of each of the new point to the target set. It will return the points that have
a closest point farther than alpha.
@param target: the current set of scans
@param newset: the new set of scans | 625941c491af0d3eaac9ba02 |
def test_upload_view(self): <NEW_LINE> <INDENT> handler_link = reverse('misago:usercp_upload_avatar_handler') <NEW_LINE> response = self.client.get(handler_link) <NEW_LINE> self.assertEqual(response.status_code, 405) <NEW_LINE> ajax_header = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'} <NEW_LINE> response = self.client.... | upload view renders on get | 625941c4c4546d3d9de72a1e |
def getInputCount(self): <NEW_LINE> <INDENT> return _yarp.BufferedPortImageMono16_getInputCount(self) | getInputCount(BufferedPortImageMono16 self) -> int | 625941c466673b3332b9207c |
def remove(token): <NEW_LINE> <INDENT> pass | Remove token. | 625941c47c178a314d6ef448 |
def test_polygon_values(self): <NEW_LINE> <INDENT> nside = 2**15 <NEW_LINE> rng = np.random.RandomState(8312) <NEW_LINE> nrand = 10000 <NEW_LINE> ra_range = 200.0, 200.1 <NEW_LINE> dec_range = 0.1, 0.2 <NEW_LINE> ra = [ra_range[0], ra_range[1], ra_range[1], ra_range[0]] <NEW_LINE> dec = [dec_range[0], dec_range[0], dec... | make sure we get out the value we used for the map
Use a box so "truth" is easy to calculate. Note however
that we do not use inclusive intersections, we we will
test values from a slightly smaller box | 625941c4925a0f43d2549e61 |
def _populate_country_combo(self): <NEW_LINE> <INDENT> script = self._get_script() <NEW_LINE> language = self._get_language() <NEW_LINE> codes = self._manager.get_countries(script, language) <NEW_LINE> names = list(map(aeidon.countries.code_to_name, codes)) <NEW_LINE> items = [(codes[i], names[i]) for i in range(len(co... | Populate the country combo box. | 625941c4fbf16365ca6f61ac |
def generator(z, out_channel_dim, is_train=True): <NEW_LINE> <INDENT> alpha = 0.2 <NEW_LINE> with tf.variable_scope('generator', reuse=False if is_train==True else True): <NEW_LINE> <INDENT> x_1 = tf.layers.dense(z, 2*2*512) <NEW_LINE> deconv_2 = tf.reshape(x_1, (-1, 2, 2, 512)) <NEW_LINE> batch_norm2 = tf.layers.batch... | Create the generator network | 625941c43eb6a72ae02ec4c4 |
def words_ranked(self): <NEW_LINE> <INDENT> rank_dict = self._words_list_sort() <NEW_LINE> counts = sorted(rank_dict.keys(), reverse = True) <NEW_LINE> return [ (c, sorted(rank_dict[c])) for c in counts] | This function returns a list of tuples, where each tuple contains
(frequency, [list of words]). | 625941c4adb09d7d5db6c77c |
def clear_mappers(): <NEW_LINE> <INDENT> mapperlib._COMPILE_MUTEX.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> for mapper in list(_mapper_registry): <NEW_LINE> <INDENT> mapper.dispose() <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> mapperlib._COMPILE_MUTEX.release() | Remove all mappers that have been created thus far.
The mapped classes will return to their initial "unmapped"
state and can be re-mapped with new mappers. | 625941c4cc0a2c11143dce7c |
def source(self, *labels): <NEW_LINE> <INDENT> raise NotImplementedError | Returns a PTransform that reads the PCollection cache. | 625941c44e696a04525c9437 |
def _cmp(self, other: _DimensionRecordKey) -> int: <NEW_LINE> <INDENT> for attribute, ordering in zip(self.attributes, self.ordering): <NEW_LINE> <INDENT> attrgetter = operator.attrgetter(attribute) <NEW_LINE> lhs = attrgetter(self.rec) <NEW_LINE> rhs = attrgetter(other.rec) <NEW_LINE> if not ordering: <NEW_LINE> <INDE... | Compare two records using provided comparison operator.
Parameters
----------
other : `_DimensionRecordKey`
Key for other record.
Returns
-------
result : `int`
0 if keys are identical, negative if ``self`` is ordered before
``other``, positive otherwise. | 625941c4e64d504609d7482b |
def export_to_png(self, filename, *args): <NEW_LINE> <INDENT> if self.parent is not None: <NEW_LINE> <INDENT> canvas_parent_index = self.parent.canvas.indexof(self.canvas) <NEW_LINE> self.parent.canvas.remove(self.canvas) <NEW_LINE> <DEDENT> fbo = Fbo(size=self.size, with_stencilbuffer=True) <NEW_LINE> with fbo: <NEW_L... | Saves an image of the widget and its children in png format at the
specified filename. Works by removing the widget canvas from its
parent, rendering to an :class:`~kivy.graphics.fbo.Fbo`, and calling
:meth:`~kivy.graphics.texture.Texture.save`.
.. note::
The image includes only this widget and its children. If y... | 625941c457b8e32f52483485 |
def data_save(self): <NEW_LINE> <INDENT> period_pool = self.pool.get('account.period') <NEW_LINE> account_move_obj = self.pool.get('account.move') <NEW_LINE> mode = 'done' <NEW_LINE> for form in self: <NEW_LINE> <INDENT> if form['sure']: <NEW_LINE> <INDENT> for id in self.env.context.get('active_ids', []): <NEW_LINE> <... | This function close fiscalyear
@param cr: the current row, from the database cursor,
@param uid: the current user’s ID for security checks,
@param ids: account period close’s ID or list of IDs
| 625941c466656f66f7cbc196 |
def call(self, x, activate=True, norm=True): <NEW_LINE> <INDENT> if self.activate_last: <NEW_LINE> <INDENT> x = self.conv(x) <NEW_LINE> if norm and self.with_norm: <NEW_LINE> <INDENT> x = self.norm(x) <NEW_LINE> <DEDENT> if activate and self.with_activatation: <NEW_LINE> <INDENT> x = self.activate(x) <NEW_LINE> <DEDENT... | Forward compute of Conv Module with Normalization. | 625941c4e8904600ed9f1f17 |
def recombine_hyps(hyps): <NEW_LINE> <INDENT> final = [] <NEW_LINE> for hyp in hyps: <NEW_LINE> <INDENT> seq_final = [f.yseq for f in final if f.yseq] <NEW_LINE> if hyp.yseq in seq_final: <NEW_LINE> <INDENT> seq_pos = seq_final.index(hyp.yseq) <NEW_LINE> final[seq_pos].score = np.logaddexp(final[seq_pos].score, hyp.sco... | Recombine hypotheses with equivalent output sequence.
Args:
hyps (list): list of hypotheses
Returns:
final (list): list of recombined hypotheses | 625941c4b545ff76a8913e02 |
def executable_command(self, cpu): <NEW_LINE> <INDENT> if self.server_type == 'multicore': <NEW_LINE> <INDENT> return self.command <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return f"pdsh -w {cpu} '{self.command}'" | Wrap command according to the server type. | 625941c4be383301e01b5474 |
def get_start(self): <NEW_LINE> <INDENT> return self.start | Get the starting offset of this basic block
:return: starting offset
:rtype: int | 625941c491af0d3eaac9ba03 |
def test_write_missing_unique_identifiers(self): <NEW_LINE> <INDENT> payload = derive_key.DeriveKeyRequestPayload( object_type=enums.ObjectType.SYMMETRIC_KEY ) <NEW_LINE> args = (utils.BytearrayStream(), ) <NEW_LINE> self.assertRaisesRegexp( ValueError, "invalid payload missing unique identifiers", payload.write, *args... | Test that a ValueError gets raised when encoding a DeriveKey request
payload missing the unique identifiers. | 625941c47cff6e4e81117971 |
def get_folder_name(self): <NEW_LINE> <INDENT> return self.dsType + '-' + self.code | 获取文件夹名称 | 625941c47b25080760e39445 |
def quaternion_inverse(quaternion): <NEW_LINE> <INDENT> q = numpy.array(quaternion, dtype=numpy.float64, copy=True) <NEW_LINE> numpy.negative(q[1:], q[1:]) <NEW_LINE> return q / numpy.dot(q, q) | Return inverse of quaternion.
q0 = random_quaternion()
q1 = quaternion_inverse(q0)
numpy.allclose(quaternion_multiply(q0, q1), [1, 0, 0, 0])
True | 625941c438b623060ff0add9 |
def time2depth_trace(ttrace, vrmsmodel, tt): <NEW_LINE> <INDENT> dt = tt[1] - tt[0] <NEW_LINE> nt = len(tt) <NEW_LINE> vintmodel = np.zeros(nt) <NEW_LINE> vintmodel[0] = vrmsmodel[0] <NEW_LINE> for it in range(1, nt): <NEW_LINE> <INDENT> v2diff = tt[it]*vrmsmodel[it]**2 - tt[it-1]*vrmsmodel[it-1]**2 <NEW_LINE> vin... | time2depth: Convert a single trace in the time domain to the depth domaing
using a RMS-velocity model
Usage:
[ztrace,zz]=time2depth_trace(ttrace,vrmsmodel,tt)
Output: ztrace - depth-converted trace
zz - depth vector
Input: ttrace - trace in time domain
vmodel - 1D RMS-... | 625941c460cbc95b062c652e |
def get_assignment_map_from_checkpoint(tvars, init_checkpoint, num_of_group=0): <NEW_LINE> <INDENT> assignment_map = {} <NEW_LINE> initialized_variable_names = {} <NEW_LINE> name_to_variable = collections.OrderedDict() <NEW_LINE> for var in tvars: <NEW_LINE> <INDENT> name = var.name <NEW_LINE> m = re.match("^(.*):\\d+$... | Compute the union of the current variables and checkpoint variables. | 625941c4187af65679ca510a |
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument('--limit', type=int, default=10) <NEW_LINE> parser.add_argument('--width', type=int, default=None) <NEW_LINE> args = parser.parse_args() <NEW_LINE> limit = args.limit <NEW_LINE> width = args.width <NEW_LINE> if width is No... | Main entry-point for following streams. | 625941c44f88993c3716c054 |
def setup(self): <NEW_LINE> <INDENT> self._logger.debug('Setting up ' + str(self._tunnel_operation)) <NEW_LINE> if self._tunnel_operation == "encapsulation": <NEW_LINE> <INDENT> self._setup_encap() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if settings.getValue('VSWITCH').endswith('Vanilla'): <NEW_LINE> <INDENT> sel... | Sets up the switch for overlay P2P (tunnel encap or decap)
| 625941c40a366e3fb873e805 |
def create_entry(self, name, entities): <NEW_LINE> <INDENT> self.entry_list.append(code_entry(name, entities)) | Creates a new entry (will store all code for a specific object) | 625941c43eb6a72ae02ec4c5 |
def retrieve_from_id(oid): <NEW_LINE> <INDENT> db, con = connect('results') <NEW_LINE> result = db.entries.find_one( { '_id' : ObjectId(oid) } ) <NEW_LINE> disconnect(con) <NEW_LINE> return result | Gets a single result for a given id | 625941c4236d856c2ad447c4 |
def vgg16(): <NEW_LINE> <INDENT> return VGG(make_layers(cfg['D'],0),0) | VGG 16-layer model (configuration "D") | 625941c4004d5f362079a320 |
def decrease_priority(self, infohash_list): <NEW_LINE> <INDENT> data = self._process_infohash_list(infohash_list) <NEW_LINE> return self._post('command/decreasePrio', data=data) | Decrease priority of torrents.
:param infohash_list: Single or list() of infohashes. | 625941c43346ee7daa2b2d57 |
def setUp(self): <NEW_LINE> <INDENT> np.set_printoptions(precision=4) | Create a simple dice rolling HMM | 625941c492d797404e304175 |
def prepare_roidb(roidb_batch): <NEW_LINE> <INDENT> for roidb in roidb_batch: <NEW_LINE> <INDENT> gt_overlaps = roidb['gt_overlaps'].toarray() <NEW_LINE> max_overlaps = gt_overlaps.max(axis=1) <NEW_LINE> max_classes = gt_overlaps.argmax(axis=1) <NEW_LINE> roidb['max_classes'] = max_classes <NEW_LINE> roidb['max_overlap... | Enrich the imdb's roidb by adding some derived quantities that
are useful for training. This function precomputes the maximum
overlap, taken over ground-truth boxes, between each ROI and
each ground-truth box. The class with maximum overlap is also
recorded. | 625941c4851cf427c661a4fc |
def query_can_belong_in_slot(self, q, s): <NEW_LINE> <INDENT> return not self.mapper.query_in_slot(q, s) and q.cost <= self.using(s) | Override to exclude queries already present in the slot or too large. | 625941c4046cf37aa974cd35 |
def set_widget_connections(self): <NEW_LINE> <INDENT> self.parent.dock_widget.PBAddField.clicked.connect(self.run) <NEW_LINE> self.parent.dock_widget.PBRemoveField.clicked.connect(self.remove_field) <NEW_LINE> self.parent.dock_widget.PBViewFields.clicked.connect(self.view_fields) | Function that sets the main widget connections. | 625941c476e4537e8c35165d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.