code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def evaluate(db, db2, sample_db_fn, depth=None, d_type='d1'): <NEW_LINE> <INDENT> samples = sample_db_fn(db) <NEW_LINE> print(len(samples)) <NEW_LINE> samples2 = sample_db_fn(db2) <NEW_LINE> print(len(samples2)) <NEW_LINE> classes = db.get_class() <NEW_LINE> classes.add(samples2[0]['cls']) <NEW_LINE> print(classes) <NE... | infer the whole database
arguments
db : an instance of class Database
sample_db_fn: a function making samples, should be given if Database != None
depth : retrieved depth during inference, the default depth is equal to database size
d_type : distance type | 625941e14f6381625f114dd6 |
def parse_page(url) -> str: <NEW_LINE> <INDENT> page = '' <NEW_LINE> for p in url.split('&'): <NEW_LINE> <INDENT> if 'o=' in p: <NEW_LINE> <INDENT> page = p.lstrip('o=') <NEW_LINE> <DEDENT> <DEDENT> return page | Parses and retrieves a page from URL parameter. | 625941e1e1aae11d1e74a055 |
def simplify_ingredients(allergens: defaultdict) -> Dict[str, Set[str]]: <NEW_LINE> <INDENT> return {a: reduce(operator.and_, ing_sets) for a, ing_sets in allergens.items()} | For each allergen, finds ingredients common to all its ingredient sets. | 625941e1d6c5a102081443e8 |
def __init__(self, image, rows, columns, item_width=None, item_height=None, row_padding=0, column_padding=0): <NEW_LINE> <INDENT> super().__init__(image.width, image.height) <NEW_LINE> self.image = image <NEW_LINE> self.rows = rows <NEW_LINE> self.columns = columns <NEW_LINE> self.item_width = item_width or (image.widt... | Construct a grid for the given image.
You can specify parameters for the grid, for example setting
the padding between cells. Grids are always aligned to the
bottom-left corner of the image.
:Parameters:
`image` : AbstractImage
Image over which to construct the grid.
`rows` : int
Number of ro... | 625941e132920d7e50b2856e |
def test_parse_exhibit_url(self): <NEW_LINE> <INDENT> parser = ForeignPrincipalsSpider() <NEW_LINE> with open('foreign_principals/tests/exhibit_url.html', 'r') as file: <NEW_LINE> <INDENT> body = file.read().replace('\n', '') <NEW_LINE> url = 'https://efile.fara.gov/pls/apex/f?p=171:200:0::NO:RP,200:P200_REG_NUMBER,P20... | Test the scrapping of the exhibit_url, asserting that all values returned were complete items to serialize | 625941e110dbd63aa1bd2f3d |
def delete_record(self): <NEW_LINE> <INDENT> index = self.selection.currentIndex() <NEW_LINE> if index.isValid(): <NEW_LINE> <INDENT> record = index.data(role=Qt.UserRole) <NEW_LINE> self.orm.delete_record(record) <NEW_LINE> self.records.removeRows(index.row(), 1) | Deletes the budget record from DB and GUI. | 625941e1dc8b845886cb58d1 |
def source(self): <NEW_LINE> <INDENT> return self.fetch('BODY[]') | Returns the message source, untreated.
| 625941e13cc13d1c6d3c7713 |
@app.task(routing_key='store.get_summoners') <NEW_LINE> def store_summoners(result, region): <NEW_LINE> <INDENT> logger.debug("result: %s, region: %s", result, region) <NEW_LINE> region = region.upper() <NEW_LINE> storage_result = {'created': 0, 'updated': 0} <NEW_LINE> if result: <NEW_LINE> <INDENT> for entry in resul... | Callback that stores the result of RiotWatcher get_summoners calls. | 625941e18a349b6b435e850e |
@slim.add_arg_scope <NEW_LINE> def stack_blocks_dense(net, blocks, outputs_collections=None): <NEW_LINE> <INDENT> for block in blocks: <NEW_LINE> <INDENT> with tf.variable_scope(block.scope, 'block', [net]) as sc: <NEW_LINE> <INDENT> for i, unit in enumerate(block.args): <NEW_LINE> <INDENT> with tf.variable_scope('unit... | Args:
net: A Tensor of size [batch, height, width, channels].输入
blocks: 是之前定义的Block的class的列表。
outputs_collections: 收集各个end_points的collections
Returns:
net: Output tensor | 625941e1097d151d1a2231f2 |
def __init__(self): <NEW_LINE> <INDENT> self.InstanceId = None <NEW_LINE> self.Accounts = None | :param InstanceId: 数据库实例ID,形如mssql-njj2mtpl
:type InstanceId: str
:param Accounts: 数据库实例账户信息
:type Accounts: list of AccountCreateInfo | 625941e19f2886367277ac26 |
def addTwoNumbers(self, l1, l2): <NEW_LINE> <INDENT> count=self.getNumbers(l1)+self.getNumbers(l2) <NEW_LINE> return self.getNodes(count) | :type l1: ListNode
:type l2: ListNode
:rtype: ListNode | 625941e14428ac0f6e5bab90 |
def run_vc(): <NEW_LINE> <INDENT> if vc_exists(): <NEW_LINE> <INDENT> log.debug("Running vc") <NEW_LINE> subprocess.call("./vc", shell=True) | Run the vc tool. | 625941e1fff4ab517eb2f7d9 |
def calcAB(dist,rads): <NEW_LINE> <INDENT> c = math.sqrt(dist) <NEW_LINE> b = math.sin(rads)*c <NEW_LINE> a = math.cos(rads)*c <NEW_LINE> return (a,b) | pythagoras theorem to calcuate SOH CAH TOA | 625941e1f9cc0f698b140993 |
def get(self, storagemodel) -> StorageTableModel: <NEW_LINE> <INDENT> modeldefinition = self.getmodeldefinition(storagemodel, True) <NEW_LINE> try: <NEW_LINE> <INDENT> pk = storagemodel.getPartitionKey() <NEW_LINE> rk = storagemodel.getRowKey() <NEW_LINE> entity = modeldefinition['tableservice'].get_entity(modeldefinit... | load entity data from storage to vars in self | 625941e1be8e80087fb20fd8 |
def validate_varnames(varnames): <NEW_LINE> <INDENT> if isinstance(varnames, basestring): <NEW_LINE> <INDENT> varnames = [varnames] <NEW_LINE> <DEDENT> for varname in varnames: <NEW_LINE> <INDENT> varname = varname.split('_')[0] <NEW_LINE> if varname not in GENERIC_VAR_NAMES: <NEW_LINE> <INDENT> raise SONATError('Inval... | Check that all variable names are in
:attr:`vacumm.data.cf.GENERIC_VAR_NAMES` list
Suffixes in the ``_<suffix>`` are removed before searching.
Raises
------
:class:`sonat.SONATError` if var name is invalid. | 625941e1fbf16365ca6f6565 |
@app.route('/restaurant/<int:restaurant_id>') <NEW_LINE> @app.route('/restaurant/<int:restaurant_id>/menu') <NEW_LINE> def showMenu(restaurant_id): <NEW_LINE> <INDENT> restaurant = getRestaurant(restaurant_id) <NEW_LINE> menu = getMenu(restaurant_id) <NEW_LINE> return render_template("menu.html", restaurant=restaurant,... | Show all menu items for a restaurant. | 625941e1d8ef3951e32438d9 |
def halt(self): <NEW_LINE> <INDENT> self.lock.acquire() <NEW_LINE> self.com_watchdog_timer.cancel() <NEW_LINE> self.com_pipe.send('die!') <NEW_LINE> self.network_process.terminate() <NEW_LINE> self.network_process.join() <NEW_LINE> self.ipc_thread.stop() <NEW_LINE> self.ipc_thread.join() <NEW_LINE> self.lock.release() | Shutdown the drone.
This method does not land or halt the actual drone, but the
communication with the drone. You should call it at the end of your
application to close all sockets, pipes, processes and threads related
with this object. | 625941e1ab23a570cc250520 |
@pytest.mark.repeat(10) <NEW_LINE> def test_1(): <NEW_LINE> <INDENT> distribute_tasks(example_func, *get_random_request()) | Test a random request.
This test simply evaluates a random request. It automatically checks whether a distributed
evaluation is an option. | 625941e15e10d32532c5f2c0 |
def testSudo(self): <NEW_LINE> <INDENT> cmd = [EXT_WHOAMI] <NEW_LINE> checkSudo(cmd) <NEW_LINE> ret, stdout, stderr = utils.execCmd(cmd, sudo=True) <NEW_LINE> self.assertEquals(stdout[0], SUDO_USER) | Tests that when running with sudo the user really is root (or other
desired user). | 625941e121bff66bcd684cea |
def unmold_detections(detections, original_image_shape, image_shape, window): <NEW_LINE> <INDENT> zero_ix = np.where(detections[:, 4] == 0)[0] <NEW_LINE> N = zero_ix[0] if zero_ix.shape[0] > 0 else detections.shape[0] <NEW_LINE> boxes = detections[:N, :4] <NEW_LINE> class_ids = detections[:N, 4].astype(np.int32) <NEW_L... | Reformats the detections of one image from the format of the neural
network output to a format suitable for use in the rest of the
application.
detections: [N, (y1, x1, y2, x2, class_id, score)] in
normalized coordinates
original_image_shape: [H, W, C] Original image shape before resizing
image_shape: [H,... | 625941e1d6c5a102081443e9 |
def construct_request( svid: int, timestamp: int, ) -> dict: <NEW_LINE> <INDENT> return { "satellite_id": svid, "info": [ {"timestamp": time, "raw_data": None} for time in range( timestamp - SETTINGS.window, timestamp + SETTINGS.window + 1, SETTINGS.window_step, ) if time != timestamp ], } | Constructs the dict of the request that will be made to Ublox-Api to retrieve the data of interest
:param svid: Satellite Identifier
:param timestamp: Timestamp associated to the measure
:return: Data to ask to Ublox-Api | 625941e11b99ca400220ae4e |
def gerador_booleano_nulo (tamanho) : <NEW_LINE> <INDENT> booleano = [] <NEW_LINE> for i in range (tamanho) : <NEW_LINE> <INDENT> booleano.append(0) <NEW_LINE> <DEDENT> return booleano | Cria um vetor nulo de len = tamanho. | 625941e1925a0f43d254a215 |
def add_callback(instance, prop, callback, echo_old=False): <NEW_LINE> <INDENT> p = getattr(type(instance), prop) <NEW_LINE> if not isinstance(p, CallbackProperty): <NEW_LINE> <INDENT> raise TypeError("%s is not a CallbackProperty" % prop) <NEW_LINE> <DEDENT> p.add_callback(instance, callback, echo_old=echo_old) | Attach a callback function to a property in an instance
:param instance: Instance of a class with callback properties
:param prop: Name of callback property in `instance`
:type prop: str
:param callback: Callback function
:type callback: Callable
Example::
class Foo:
bar = CallbackProperty(0)
def ... | 625941e1ad47b63b2c50a319 |
def __init__(self): <NEW_LINE> <INDENT> self.toggled = False <NEW_LINE> self.args = None <NEW_LINE> self.kwargs = None | Construct a new latch. | 625941e14f6381625f114dd7 |
def read(fp, encoding, depth): <NEW_LINE> <INDENT> logger.debug('reading layers and masks information...') <NEW_LINE> length = read_fmt("I", fp)[0] <NEW_LINE> start_position = fp.tell() <NEW_LINE> logger.debug('length=%d, start_position=%d', length, start_position) <NEW_LINE> layers = _read_layers(fp, encoding, depth) ... | Reads layers and masks information. | 625941e1cc0a2c11143dd22d |
def test_logout_all(self): <NEW_LINE> <INDENT> token_list = [] <NEW_LINE> response_list = self.get_n_tokens(self.test_logout_all_client_number) <NEW_LINE> for i in range(0, self.test_logout_all_client_number): <NEW_LINE> <INDENT> token = response_list[i].data['token'] <NEW_LINE> token_list.append(token) <NEW_LINE> <DED... | In this test we prove that a single request against the 'logout_all' endpoint will invalidate all the tokens
related to a single user
:return: | 625941e17b180e01f3dc4b91 |
def isRegular(self): <NEW_LINE> <INDENT> usedInRhs = {} <NEW_LINE> notAllowedInRhs = [] <NEW_LINE> for rule in self.P: <NEW_LINE> <INDENT> lhs, rhs = rule <NEW_LINE> hasTerminal = False <NEW_LINE> hasNonTerminal = False <NEW_LINE> if len(rhs) > 2: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for char in rhs: <N... | verifiy if the grammar is right liner
and S does not appear in the right hand side of the produc | 625941e1de87d2750b860131 |
def __init__(self, obs2state_fn): <NEW_LINE> <INDENT> self._experienced_states = set() <NEW_LINE> self._experienced_transitions = set() <NEW_LINE> self._obs2state = obs2state_fn | Initialized ExpericedStatesLogger
Args:
obs2state_fn: Function mapping observation to hashable state. | 625941e13539df3088e2e6e6 |
def wait_until_pending_futures_and_users_flushed(timeout: int = 20) -> None: <NEW_LINE> <INDENT> start = time.time() <NEW_LINE> while True: <NEW_LINE> <INDENT> debug_info = _rref_context_get_debug_info() <NEW_LINE> num_pending_futures = int(debug_info["num_pending_futures"]) <NEW_LINE> num_pending_users = int(debug_inf... | The RRef protocol holds forkIds of rrefs in a map until those forks are
confirmed by the owner. The message confirming the fork may arrive after
our tests check whether this map is empty, which leads to failures and
flaky tests. to_here also does not guarantee that we have finished
processind the owner's confirmation m... | 625941e1dc8b845886cb58d2 |
def _transfer_common(old_cobj, new_cobj): <NEW_LINE> <INDENT> new_cobj.illuminant = old_cobj.illuminant <NEW_LINE> new_cobj.observer = old_cobj.observer | Transfer illuminant and observer data to a new color object. This is | 625941e19b70327d1c4e1172 |
def double(value, digits=2): <NEW_LINE> <INDENT> return six.u(_format(value, digits)) | Converts a number to a formatted double based on the current locale.
:param value: number
:param digits: default ``2``
>>> print(double(42))
42.00
>>> print(double(42, digits=1))
42.0
>>> print(double(12.34))
12.34
>>> print(double(1234.56))
1,234.56 | 625941e101c39578d7e751d7 |
def set_password(self, password, secret): <NEW_LINE> <INDENT> self.password_hash = crypt(word=password, salt=secret) <NEW_LINE> return self.password_hash | :param password:
:param secret:
:return: | 625941e14d74a7450ccd4560 |
def get_earliest_offsets(self): <NEW_LINE> <INDENT> offsets = {p: _get_partition_earliest_offset(self._consumers[p]) for p in self.partitions} <NEW_LINE> logger.info("get earliest offsets %s", offsets) <NEW_LINE> return offsets | Get earliest offsets of each partitions
Args:
None
Returns:
dict : offsets of each partitions { pid (int) : offset (int) } | 625941e1379a373c97cfaee2 |
def camel_to_snake_case(camel_string: str): <NEW_LINE> <INDENT> return re.sub(r"(?<!^)(?=[A-Z])", "_", camel_string.replace(" ", "")).lower() | Converts a string with Camel case formatting to one with snake case.
E.g. "SomeName" -> "some_name" | 625941e1d4950a0f3b08c6e5 |
def copyPosFrom(self, step): <NEW_LINE> <INDENT> self.step_x = step.step_x <NEW_LINE> self.step_y = step.step_y <NEW_LINE> self.step_z = step.step_z <NEW_LINE> self.step_e = step.step_e <NEW_LINE> self.step_f = step.step_f <NEW_LINE> self.comment = step.comment <NEW_LINE> return | Copies positions of step into self | 625941e15fcc89381b1e1a5c |
def redirect_to_get_code(func): <NEW_LINE> <INDENT> def wrapper(inst, request, obj): <NEW_LINE> <INDENT> redirect_url = get_redirect_url(obj, request) <NEW_LINE> payload = { 'client_id': obj.client_id, 'response_type': 'code', 'redirect_uri': redirect_url, 'scope': 'manage_pages, publish_pages, pages_show_list, user_ph... | Decorator for ModelAdmin method.
Overrides redirect. It goes to Facebook for login and grant access
with permission in 'scope'. As a result we get 'code' in 'redirect_url' URL
:param func:
:return: Redirect to Facebook | 625941e1460517430c394517 |
def check_all(self): <NEW_LINE> <INDENT> for c in self.checks: <NEW_LINE> <INDENT> c.check(c) | Execute all checks which are present in the Checker-object | 625941e10383005118ecf97d |
def winfo_id(self): <NEW_LINE> <INDENT> return self._call(int, 'winfo', 'id', self) | Calls ``winfo id``. Returns an integer.
Manual page: :man:`winfo(3tk)` | 625941e1f9cc0f698b140994 |
def make_metadata_request(self, filenames): <NEW_LINE> <INDENT> filemap = {} <NEW_LINE> metadata = self.make_pb("metadata_request") <NEW_LINE> for filename in filenames: <NEW_LINE> <INDENT> if not filename.split(".")[-1] == "mp3": <NEW_LINE> <INDENT> self.log.error("Cannot upload '%s' because it is not an mp3.") <NEW_L... | Returns (Metadata protobuff, dictionary mapping ClientId to filename) for the given mp3s. | 625941e156ac1b37e6264565 |
def build(config, host=None, verbose=False): <NEW_LINE> <INDENT> dockerfile.buildDockerfile(config) <NEW_LINE> dockerignore.buildDockerignore(config) <NEW_LINE> buildCMD = DockerCommandBuilder(host=host).build(config.getImageName()) <NEW_LINE> try: <NEW_LINE> <INDENT> status = execute(buildCMD, err_msg="Docker Build Fa... | Build the Docker Image after building the Dockerfile and .dockerignore from Config | 625941e1462c4b4f79d1da6b |
def get_mngmnt_ip_of_ctrllrs(self): <NEW_LINE> <INDENT> controllers = self.env.get_nodes_by_role('controller') <NEW_LINE> ctrl_ips = [] <NEW_LINE> for one in controllers: <NEW_LINE> <INDENT> ip = [x['ip'] for x in one.data['network_data'] if x['name'] == 'management'][0] <NEW_LINE> ip = ip.split("/")[0] <NEW_LINE> ctrl... | Get host IP of management network from all controllers | 625941e1adb09d7d5db6cb29 |
def as_spherical(self): <NEW_LINE> <INDENT> r = self.length() <NEW_LINE> if r == 0.0: <NEW_LINE> <INDENT> return (0.0, 0.0, 0.0) <NEW_LINE> <DEDENT> theta = _math.degrees(_math.acos(self._z / r)) <NEW_LINE> phi = _math.degrees(_math.atan2(self._y, self._x)) <NEW_LINE> return (r, theta, phi) | returns a tuple with radial distance, inclination and azimuthal angle. | 625941e1d4950a0f3b08c6e6 |
def count(inp): <NEW_LINE> <INDENT> def getyear(row): <NEW_LINE> <INDENT> return row[12:16] <NEW_LINE> <DEDENT> res = dict((int(year),len(list(rows))) for year,rows in itertools.groupby(sorted(inp, key=getyear), getyear)) <NEW_LINE> return res | *inp* is a file in v2.mean format. Counts the number of rows in
each year. The result is a dict that maps from year (a number) to
count (also a number). | 625941e163b5f9789fde7482 |
def copy(): <NEW_LINE> <INDENT> return mycopy.deepcopy(opts) | 复制配置 | 625941e167a9b606de4a8253 |
def sequence_alignment(mobile, reference, **kwargs): <NEW_LINE> <INDENT> import Bio.pairwise2 <NEW_LINE> kwargs.setdefault('match_score', 2) <NEW_LINE> kwargs.setdefault('mismatch_penalty', -1) <NEW_LINE> kwargs.setdefault('gap_penalty', -2) <NEW_LINE> kwargs.setdefault('gapextension_penalty', -0.1) <NEW_LINE> aln = Bi... | Generate a global sequence alignment between residues in *reference* and *mobile*.
The global alignment uses the Needleman-Wunsch algorith as
implemented in :mod:`Bio.pairwise2`. The parameters of the dynamic
programming algorithm can be tuned with the keywords. The defaults
should be suitable for two similar sequence... | 625941e1a219f33f34628d01 |
def get_attribute_element_id(web_gui, get_value, attribute): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return web_gui.find_element_by_id(get_value).get_attribute(attribute) <NEW_LINE> <DEDENT> except NoSuchElementException: <NEW_LINE> <INDENT> return None | To get the value of attribute of UI element via id.
:param web_gui: web driver after initializing page
:type web_gui: string
:param get_value: web element id for the element
:type get_value: string
:param attribute: web element value of attribute which is required
:type get_value: string
:raises Exception: If error th... | 625941e1cdde0d52a9e533d1 |
def less_shitty_error_messages(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def inner(self, sql, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return func(self, sql, *args, **kwargs) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> exc_info = sys.exc_info() <NEW_LINE> msg = '{}\nSQL... | Wraps functions where the first param is a SQL statement and enforces
any exceptions thrown will also contain the statement in the message. | 625941e191f36d47f21ac892 |
def _cusp_index(self, cusp): <NEW_LINE> <INDENT> g = self._known_gens <NEW_LINE> N = self.level() <NEW_LINE> for i in xrange(len(g)): <NEW_LINE> <INDENT> t, eps = self._is_equiv(cusp, g[i]) <NEW_LINE> if t: <NEW_LINE> <INDENT> return i, eps <NEW_LINE> <DEDENT> <DEDENT> return -1, 0 | Returns a pair (i, t), where i is the index of the first cusp in
self._known_cusps() which is equivalent to cusp, and t is 1 or -1
as cusp is GammaH-equivalent to plus or minus
self._known_cusps()[i]. If cusp is not equivalent to any known
cusp, return (-1, 0).
EXAMPLES::
sage: M = ModularSymbols(GammaH(9,[4]), 3... | 625941e199cbb53fe6792f82 |
def _loss(self, logits, labels): <NEW_LINE> <INDENT> cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels, name='xentropy') <NEW_LINE> loss = tf.reduce_mean(cross_entropy, name='xentropy_mean') <NEW_LINE> (_, int_targets) = tf.nn.top_k(labels, 1) <NEW_LINE> (_, int_predictions) = tf.nn.t... | Calculate loss for both pos and chunk
Args:
logits from the decoder
labels - one-hot
returns:
loss as tensor of type float | 625941e107d97122c4178c2f |
def test_unauthorized_access(self): <NEW_LINE> <INDENT> response = self.client.get('/?json={0}'.format(self.JSON['JSON_1']), follow=True) <NEW_LINE> print(response.content) | Should redirect to login page if not
authenticated ssc/. | 625941e155399d3f05588a52 |
def first(self): <NEW_LINE> <INDENT> self._ll_tree.first() | Seeks to the first tree in the sequence. This can be called whether
the tree is in the null state or not. | 625941e132920d7e50b2856f |
def get_cache_destination_path(): <NEW_LINE> <INDENT> if (_MANAGER_CACHE_DESTINATION and os.path.exists(_MANAGER_CACHE_DESTINATION)): <NEW_LINE> <INDENT> return _MANAGER_CACHE_DESTINATION <NEW_LINE> <DEDENT> cache_path = get_preference_file_cache_destination_path() <NEW_LINE> if cache_path: <NEW_LINE> <INDENT> return c... | Returns the cache destination path
This methods returns a path pointing to where the cache manager will store
the GPU caches.
If the **MGEAR_CACHE_MANAGER_CACHE_DESTINATION** environment
variable has been set it will return whatever path has been set if valid.
If none has been set or fails to use that path this metho... | 625941e1be7bc26dc91cd996 |
def cleanup(self): <NEW_LINE> <INDENT> d = [] <NEW_LINE> for k in self.d.keys(): <NEW_LINE> <INDENT> if self.d[k].__abs__() <= PolynomialOverARingItem.epsilon: <NEW_LINE> <INDENT> d.append(k) <NEW_LINE> <DEDENT> <DEDENT> for k in d: <NEW_LINE> <INDENT> del self.d[k] <NEW_LINE> <DEDENT> if not self.d[0]: <NEW_LINE> <IND... | Удалить нулевые коэффициенты. | 625941e13eb6a72ae02ec882 |
def trigger_macd_trend(symbol, index, a, b, success_window=0): <NEW_LINE> <INDENT> trigger = [] <NEW_LINE> n = a + b <NEW_LINE> df = pd.read_csv(os.path.join(settings['folder']['trading'], index, symbol + '_ta.csv')) <NEW_LINE> for i in xrange(n, df.shape[0] - n - success_window): <NEW_LINE> <INDENT> if isnan(df.ix[i, ... | a is num of days with macd diff neg
b is num of days with macd diff pos
success_window is num of days keeping track of price after trigger | 625941e1fb3f5b602dac3a33 |
def plot_decision_boundary2D(X, y, num_row=200, num_col=200): <NEW_LINE> <INDENT> sigma = 1 <NEW_LINE> x1_min, x1_max = np.min(X[:, 0]) - sigma, np.max(X[:, 0]) <NEW_LINE> x2_min, x2_max = np.min(X[:, 1]) - sigma, np.max(X[:, 1]) <NEW_LINE> t1 = np.linspace(x1_min, x1_max, num_row) <NEW_LINE> t2 = np.linspace(x2_min, x... | 绘制决策边界的核心代码
:param clf: 分类器, 即使用的模型
:param X: 输入的数据X
:param y: 真实的分类结果y
:param num_row: 绘制决策边界时,行数据生成的个数
:param num_col: 列数据生成的个数 | 625941e1d58c6744b4257ffa |
def _TestQuantize_FCWithBatchNorm(self, activation, activation_op_name, with_bypass, delay, fused_batch_norm, use_resource): <NEW_LINE> <INDENT> graph = ops.Graph() <NEW_LINE> with graph.as_default(): <NEW_LINE> <INDENT> variable_scope.get_variable_scope().set_use_resource(use_resource) <NEW_LINE> batch_size, depth = 5... | Tests quantization: inputs -> FC with batch norm -> Activation.
Args:
activation: Callable that returns an Operation, a factory method for the
Activation.
activation_op_name: String, name of the Activation operation.
with_bypass: Bool, when true there is an extra connection added from
inputs to just befo... | 625941e1507cdc57c630707f |
def backSearch(self): <NEW_LINE> <INDENT> node = self.root <NEW_LINE> if not node: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nodeStack1 = [] <NEW_LINE> nodeStack2 = [] <NEW_LINE> result = [] <NEW_LINE> while node or nodeStack1: <NEW_LINE> <INDENT> while node: <NEW_LINE> <INDENT> node... | 后序遍历的非递归方法 | 625941e1ff9c53063f47c58e |
def consent_questions(self): <NEW_LINE> <INDENT> if self.pk: <NEW_LINE> <INDENT> return ConsentQuestion.objects.filter(experiment=self.pk).order_by('position') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Returns a Queryset of all questions added to the consent form. | 625941e1d10714528d600083 |
def __init__(self, gameStateController, boardView): <NEW_LINE> <INDENT> super(animationEngine, self).__init__() <NEW_LINE> self.gameStateController = gameStateController <NEW_LINE> self.boardView = boardView | Constructor. | 625941e18c3a87329515875b |
def isOpaque(self, observer): <NEW_LINE> <INDENT> return observer is not self.wearer.thing | I am opaque, so that clothing will show up only once (in your "wearing"
list, rather than there and in your "contained" list), and obscured
clothing won't show up at all. | 625941e1cdde0d52a9e533d2 |
def init(): <NEW_LINE> <INDENT> logging.getLogger("requests").setLevel(logging.WARNING) <NEW_LINE> logging.basicConfig(filename='log/wangyi_article.log', format='[%(asctime)s-%(levelname)s:%(message)s]', level=logging.INFO, filemode='a', datefmt='%Y-%m-%d%I:%M:%S %p') <NEW_LINE> console = logging.StreamHandler() <NEW_L... | 读取配置文件,设置日志输出规则等初始化工作
:return: | 625941e115fb5d323cde0eb1 |
def get(self, request, format=None, version="v1"): <NEW_LINE> <INDENT> date = request.query_params.get('date', None) <NEW_LINE> if date is None: <NEW_LINE> <INDENT> date = datetime.date.today() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> date = datetime.datetime.strptime(date, '%Y-%m-%d') <NEW_LINE> <DEDENT> last_wee... | Return list rate and average per data by date | 625941e17c178a314d6ef801 |
def get_metadata(self): <NEW_LINE> <INDENT> ret = super(LumeneraCamera, self).get_metadata() <NEW_LINE> camid=self.cam.GetCameraId() <NEW_LINE> version = self.cam.QueryVersion() <NEW_LINE> interface = self.cam.QueryExternInterface() <NEW_LINE> frame, fps = self.cam.GetFormat() <NEW_LINE> depth = self.cam.GetTruePixelDe... | Return a dictionary of camera settings and parameters. | 625941e130bbd722463cc164 |
def create_logtail_config(self, project_name, config_detail): <NEW_LINE> <INDENT> if config_detail.logstore_name: <NEW_LINE> <INDENT> self.get_logstore(project_name, config_detail.logstore_name) <NEW_LINE> <DEDENT> headers = {} <NEW_LINE> params = {} <NEW_LINE> resource = "/configs" <NEW_LINE> headers['Content-Type'] =... | create logtail config in a project
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type config_detail: LogtailConfigGenerator or SeperatorFileConfigDetail or SimpleFileConfigDetail or FullRegFileConfigDetail or JsonFileConfigDetail or ApsaraFileCon... | 625941e194891a1f4081be47 |
def scale(val, src, dst): <NEW_LINE> <INDENT> return ((val - src[0]) / (src[1]-src[0])) * (dst[1]-dst[0]) + dst[0] | Scale the given value from the scale of src to the scale of dst. | 625941e1498bea3a759b9e4b |
def deserialize_numpy(self, str, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> 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> end += length <NEW_LINE> if python3: <NEW_LINE> <INDENT> self.tag_name = str[start:end].decod... | unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module | 625941e15510c4643540f778 |
def process_board(self, board): <NEW_LINE> <INDENT> self.board_size = board['size'] <NEW_LINE> tiles = board['tiles'] <NEW_LINE> map_line = "" <NEW_LINE> char = None <NEW_LINE> for y in range(0, len(tiles), self.board_size * 2): <NEW_LINE> <INDENT> line = tiles[y:y+self.board_size*2] <NEW_LINE> for x in range(0, len(li... | Process the board datas
- Retrieve walls locs, tavern locs
- Converts tiles in a displayable form | 625941e13eb6a72ae02ec883 |
def add(elems, units, inplace_units=False, unitdict=None, key=None): <NEW_LINE> <INDENT> return operate(elems, units, inplace_units=inplace_units, unitdict=unitdict, key=key, operation='+') | Add elements considering their units | 625941e173bcbd0ca4b2c412 |
def adjust_time(hapitime, ndays): <NEW_LINE> <INDENT> from datetime import datetime, date, timedelta <NEW_LINE> from hapiclient import hapitime2datetime <NEW_LINE> dt = hapitime2datetime(hapitime)[0] <NEW_LINE> if dt.strftime('%Y-%m-%dT%H:%M:%D.%f') != dt.strftime('%Y-%m-%dT00:00:00.000000'): <NEW_LINE> <INDENT> dt = d... | Convert HAPI Time to %Y-%m-%d and add +/1 day | 625941e1e64d504609d74bdc |
def node_value(node, entities=DEFAULT_ENTITIES): <NEW_LINE> <INDENT> v = '' <NEW_LINE> for x in node.childNodes: <NEW_LINE> <INDENT> v += x.toxml().strip() <NEW_LINE> <DEDENT> return saxutils.unescape(''.join(v.split('\n')), entities) | Return the flattened body value of the given node. If the given
node has elements as children, they will be converted to textual XML.
>>> from xml.dom.minidom import parseString
>>> node = parseString('<foo> abc --</foo>').childNodes[0]
>>> node.tagName
u'foo'
>>> node_value(node)
u'abc --'
>>> node =... | 625941e1d18da76e23532877 |
def __init__(self, *perms): <NEW_LINE> <INDENT> self.perms = perms <NEW_LINE> self.tup_rep = self.get_tup_rep() | perms: list of Perm2 objects | 625941e131939e2706e4d201 |
def card_help(card_name): <NEW_LINE> <INDENT> help(card_classes[card_name]) | Print help of a given card.
Parameters
----------
card_name : str
Name of the card.
Examples
--------
>>> get_card_help('GRID') | 625941e1091ae356686672f5 |
def git_am_patch_split(f, encoding=None): <NEW_LINE> <INDENT> encoding = encoding or getattr(f, "encoding", "ascii") <NEW_LINE> contents = f.read() <NEW_LINE> if (isinstance(contents, bytes) and getattr(email.parser, "BytesParser", None)): <NEW_LINE> <INDENT> parser = email.parser.BytesParser() <NEW_LINE> msg = parser.... | Parse a git-am-style patch and split it up into bits.
:param f: File-like object to parse
:param encoding: Encoding to use when creating Git objects
:return: Tuple with commit object, diff contents and git version | 625941e10383005118ecf97e |
def _loadPlugins(self) -> None: <NEW_LINE> <INDENT> self._plugin_registry.setCheckIfTrusted(ApplicationMetadata.IsEnterpriseVersion) <NEW_LINE> self._plugin_registry.addType("profile_reader", self._addProfileReader) <NEW_LINE> self._plugin_registry.addType("profile_writer", self._addProfileWriter) <NEW_LINE> if Platfor... | Handle loading of all plugin types (and the backend explicitly)
:py:class:`Uranium.UM.PluginRegistry` | 625941e157b8e32f5248383a |
def change(gt, priors): <NEW_LINE> <INDENT> num_priors = priors.size(0) <NEW_LINE> num_gt = gt.size(0) <NEW_LINE> gt_w = (gt[:, 2] - gt[:, 0])[:, None].expand(num_gt, num_priors) <NEW_LINE> gt_h = (gt[:, 3] - gt[:, 1])[:, None].expand(num_gt, num_priors) <NEW_LINE> gt_mat = gt[:, None, :].expand(num_gt, num_pri... | Compute the d_change metric proposed in Box2Pix:
https://lmb.informatik.uni-freiburg.de/Publications/2018/UB18/paper-box2pix.pdf
Input should be in point form (xmin, ymin, xmax, ymax).
Output is of shape [num_gt, num_priors]
Note this returns -change so it can be a drop in replacement for | 625941e16e29344779a629ac |
def test_get_namespaced_deployment(self): <NEW_LINE> <INDENT> pass | Test case for get_namespaced_deployment
read the specified Deployment | 625941e14f6381625f114dd8 |
def __init__(self, width=320, height=240, minDt=5): <NEW_LINE> <INDENT> pg.init() <NEW_LINE> self.width = width <NEW_LINE> self.height = height <NEW_LINE> self.minDt = minDt <NEW_LINE> self.gameOver = False <NEW_LINE> self.screen = pg.display.set_mode((self.width, self.height), pg.HWSURFACE|pg.DOUBLEBUF|pg.RE... | Initialises the screen size and minimum step delay(milliseconds) | 625941e191f36d47f21ac893 |
def test_package_info_created_with_upstream_data(self): <NEW_LINE> <INDENT> version = '2.0.0' <NEW_LINE> url = 'http://some.url.here' <NEW_LINE> dehs = [ { 'package': self.package.name, 'status': 'Newer version available', 'upstream-url': url, 'upstream-version': version, } ] <NEW_LINE> self.set_upstream_status_content... | Tests that a new PackageData is created with key 'general' and upstream
data | 625941e1f7d966606f6aa3a5 |
def __init__(self, name=None, reference=None, warnings=None, errors=None): <NEW_LINE> <INDENT> self._name = None <NEW_LINE> self._reference = None <NEW_LINE> self._warnings = None <NEW_LINE> self._errors = None <NEW_LINE> self.discriminator = None <NEW_LINE> if name is not None: <NEW_LINE> <INDENT> self.name = name <NE... | ProductMessage - a model defined in Swagger | 625941e110dbd63aa1bd2f3f |
def read_velocity(self): <NEW_LINE> <INDENT> return int(self.sendcmds('TV')[-1]) / KV | Return the current velocity of the actuator in mm/s. | 625941e1287bf620b61d3dfe |
@click.command() <NEW_LINE> @click.argument("files_to_add", nargs=-1) <NEW_LINE> @click.argument("project_file", nargs=1) <NEW_LINE> @click.option("--host", "-h", default="127.0.0.1", help="Host at which to run labeling") <NEW_LINE> @click.option( "--port", "-p", default=5000, help="Port at which to run labeling", type... | Launch the simplified labeling application. | 625941e116aa5153ce362814 |
def credit_point_check(self, user=None): <NEW_LINE> <INDENT> if not user: <NEW_LINE> <INDENT> user = self.env.user <NEW_LINE> <DEDENT> self.ensure_one() <NEW_LINE> if not self.partner_id.sudo(user.id).credit_point_bypass_check(): <NEW_LINE> <INDENT> if self.amount_total > self.partner_id.credit_point: <NEW_LINE> <INDEN... | Verify order amount against credit point budget. | 625941e1f7d966606f6aa3a6 |
def test_after_import_import_pickings(self): <NEW_LINE> <INDENT> expect = mock.MagicMock() <NEW_LINE> with mock.patch.multiple( self.unit, binder_for=mock.DEFAULT, unit_for=mock.DEFAULT, ): <NEW_LINE> <INDENT> with mock.patch.object(self.unit, '_import_dependency') as depend: <NEW_LINE> <INDENT> self.unit.binder_for().... | It should import pickings if all lines are imported | 625941e126068e7796caf081 |
def _xfer_atom_info(self): <NEW_LINE> <INDENT> data = self.parm_data <NEW_LINE> data['POINTERS'][NATOM] = self.pointers['NATOM'] = len(self.atoms) <NEW_LINE> data['ATOM_NAME'] = [a.name for a in self.atoms] <NEW_LINE> data['MASS'] = [a.mass for a in self.atoms] <NEW_LINE> data['CHARGE'] = [0.0 for a in self.atoms] <NEW... | Transfers atom info to the topology file data arrays | 625941e182261d6c526ab841 |
def startElement_svg(self, name, attrs): <NEW_LINE> <INDENT> width = attrs.get("width", None) <NEW_LINE> height = attrs.get("height", None) <NEW_LINE> self.pageBounds.x2 = self.parseCoordinates(width) <NEW_LINE> self.pageBounds.y2 = self.parseCoordinates(height) | Callback hook which handles the start of an svg image | 625941e167a9b606de4a8254 |
def get_mbobs(self): <NEW_LINE> <INDENT> all_band_obj = self._get_band_objects() <NEW_LINE> mbobs = ngmix.MultiBandObsList() <NEW_LINE> for band in range(self['nband']): <NEW_LINE> <INDENT> band_objects = [o[band] for o in all_band_obj] <NEW_LINE> obj = galsim.Sum(band_objects) <NEW_LINE> im = obj.drawImage( nx=self['d... | get a simulated MultiBandObsList | 625941e121a7993f00bc8093 |
def create_window(title, url=None, html=None, js_api=None, width=800, height=600, x=None, y=None, resizable=True, fullscreen=False, min_size=(200, 100), hidden=False, frameless=False, easy_drag=True, minimized=False, on_top=False, confirm_close=False, background_color='#FFFFFF', transparent=False, text_select=False, lo... | Create a web view window using a native GUI. The execution blocks after this function is invoked, so other
program logic must be executed in a separate thread.
:param title: Window title
:param url: URL to load
:param width: window width. Default is 800px
:param height:window height. Default is 600px
:param resizable T... | 625941e16aa9bd52df037142 |
def college_coords(name): <NEW_LINE> <INDENT> size = panda_to_list('Private_oncampus.csv', 'Institution Size') <NEW_LINE> case1 = panda_to_list('Private_oncampus.csv', 'Sex offenses - Forcible') <NEW_LINE> case2 = panda_to_list('Private_oncampus.csv', 'Sex offenses - Non-forcible') <NEW_LINE> names_with_coords = panda_... | returns the latitude and longitude depending of the list of colleges
determined by the input variable "name". The variable name is a list of
the name of colleges in a file matching to assault data (a dataset that
does not contain college coordinates). The purpose of this function is to
match a college to it's coordina... | 625941e15e10d32532c5f2c2 |
def extendSALT2_flatline( salt2dir = 'models/SALT2/SALT2.Guy10_UV2IR', wjoinblue = 2000, wjoinred = 8500 , wmin = 300, wmax = 18000, tmin=-20, tmax=100, wstep = 10, showplots=False ): <NEW_LINE> <INDENT> sndataroot = os.environ['SNDATA_ROOT'] <NEW_LINE> salt2dir = os.path.join( sndataroot, salt2dir ) <NEW_LINE> filelis... | extrapolate the *lc* and *spec* .dat files for SALT2
using a flatline to the blue and red | 625941e1ab23a570cc250522 |
def inorderSuccessor(self, root, p): <NEW_LINE> <INDENT> ptr = root <NEW_LINE> path = [] <NEW_LINE> while ptr.val != p.val: <NEW_LINE> <INDENT> path.append(ptr) <NEW_LINE> ptr = ptr.left if ptr.val > p.val else ptr.right <NEW_LINE> <DEDENT> if ptr.right: <NEW_LINE> <INDENT> ptr = ptr.right <NEW_LINE> while ptr.left: <N... | :type root: TreeNode
:type p: TreeNode
:rtype: TreeNode | 625941e1cc40096d61595cec |
def decode_tx29(binaryMsg): <NEW_LINE> <INDENT> givenLength = take(binaryMsg, 0, 4) <NEW_LINE> actualLength = len(binaryMsg) / 4 - 1 <NEW_LINE> print("Length: actual={:02X}, received={:02X}, valid={}".format(actualLength, givenLength, "yes" if (givenLength == actualLength) else "no")) <NEW_LINE> givenCRC = take(binaryM... | Decoding a LaCrosse/TFA sensor message. | 625941e15fdd1c0f98dc05d2 |
def make_title(label): <NEW_LINE> <INDENT> tag = remove_punctuation(label.lower().strip().replace(" ", "_").replace("%20","_")) <NEW_LINE> if tag == "": <NEW_LINE> <INDENT> tag = "unknown" <NEW_LINE> <DEDENT> return tag | Given a string, returns the string in the format we use for
identifying grids. This is used mostly to build internal link
structures | 625941e131939e2706e4d202 |
def targetTensor(line): <NEW_LINE> <INDENT> letter_indexes = [all_letters.find(line[li]) for li in range(1, len(line))] <NEW_LINE> letter_indexes.append(n_letters - 1) <NEW_LINE> return torch.LongTensor(letter_indexes) | list of next letter indice. | 625941e1fb3f5b602dac3a34 |
def test_default_version(self): <NEW_LINE> <INDENT> call = Call() <NEW_LINE> self.assertEqual(call.version, "2009-11-30") | If no version is explicitly requested, C{version} is set to
2009-11-30, which is the earliest version we support. | 625941e16fece00bbac2dadf |
def test_parity_set(self): <NEW_LINE> <INDENT> f = FenwickTree(16) <NEW_LINE> for j in range(1, 16): <NEW_LINE> <INDENT> parity_set_nodes = f.get_parity_set(j) <NEW_LINE> parity_set = [node.index for node in parity_set_nodes] <NEW_LINE> correct = _parity_set(j - 1) <NEW_LINE> self.assertEqual(set(parity_set), set(corre... | Test getting the parity set. | 625941e130dc7b7665901cff |
def serialize_foreign_revid(self, foreign_revid): <NEW_LINE> <INDENT> raise NotImplementedError(self.serialize_foreign_revid) | Serialize a foreign revision id for this VCS.
:param foreign_revid: Foreign revision id
:return: Bytestring with serialized revid, will not contain any
newlines. | 625941e1925a0f43d254a217 |
def posterior_prob (source, withcount=False): <NEW_LINE> <INDENT> logging.debug('Calculating Posterior Probablity on %d data observations', len(source)) <NEW_LINE> groupby = {} <NEW_LINE> for x_i in source: <NEW_LINE> <INDENT> key = eval(x_i) if isinstance(x_i, str) else x_i <NEW_LINE> if key in groupby.keys(): <NEW_LI... | Calculate posterior probability for set of observations | 625941e16fece00bbac2dae0 |
def test_month_year_field(self): <NEW_LINE> <INDENT> self.assertIn('month_year', self.admin.list_display) <NEW_LINE> self.assertIn('month_year', self.admin.readonly_fields) | month_year must be installed | 625941e1e8904600ed9f22cf |
def register(): <NEW_LINE> <INDENT> print("--" * 25) <NEW_LINE> print(" Register/Sign-In") <NEW_LINE> print("--" * 25) <NEW_LINE> user_name, master_pwd = prompt_for_new_user() <NEW_LINE> print(user_name, master_pwd) <NEW_LINE> while os.path.exists(f'{filepath}/{user_name}.ini'): <NEW_LINE> <INDENT> print('Enter... | Registration section:
| 625941e1099cdd3c635f0ff6 |
def create_address(self, customer_id, request, idempotency_key=None): <NEW_LINE> <INDENT> _url_path = '/customers/{customer_id}/addresses' <NEW_LINE> _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customer_id': customer_id }) <NEW_LINE> _query_builder = Configuration.base_uri <NEW_LINE> _query_... | Does a POST request to /customers/{customer_id}/addresses.
Creates a new address for a customer
Args:
customer_id (string): Customer Id
request (CreateAddressRequest): Request for creating an address
idempotency_key (string, optional): TODO: type description here.
Example:
Returns:
GetAddres... | 625941e163b5f9789fde7483 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.