code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _get_target_class(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from publicapi.items import ItemsResource <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> self.fail("Could not import class under test (ItemsResource).") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ItemsResource | Return the class under test.
Make the test fail immediately if the class cannot be imported. | 625941e1236d856c2ad44b74 |
def show_formats(): <NEW_LINE> <INDENT> from packaging.fancy_getopt import FancyGetopt <NEW_LINE> formats = sorted(('formats=' + name, None, desc) for name, desc in get_archive_formats()) <NEW_LINE> FancyGetopt(formats).print_help( "List of available source distribution formats:") | Print all possible values for the 'formats' option (used by
the "--help-formats" command-line option). | 625941e1f548e778e58cd914 |
def __create_declaration(self): <NEW_LINE> <INDENT> return_type = self.return_type <NEW_LINE> if self.return_type is None: <NEW_LINE> <INDENT> raise CBackEndException("Unsupported return type (%s)" % self.return_type) <NEW_LINE> <DEDENT> name = self.name <NEW_LINE> if self.has_parameters: <NEW_LINE> <IND... | Create the function declaration with its return type, attributes,
function name and paramaters (if any). | 625941e1ad47b63b2c50a313 |
def theta2chord(theta): <NEW_LINE> <INDENT> return 2*np.sin(theta/2) | compute chord length on unit sphere from angle
Parameters
----------
theta: float
angle
Returns
-------
c: float
chord or euclidean distance between normalized direction vectors | 625941e1442bda511e8be7a8 |
def parse(self, data: str) -> int: <NEW_LINE> <INDENT> self._data = data.encode() <NEW_LINE> self._current_position = 1 <NEW_LINE> self._current_line = 1 <NEW_LINE> current_pos = 0 <NEW_LINE> while current_pos < len(data): <NEW_LINE> <INDENT> if self._abort is True: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> size = ... | Parse data.
:param data: Textual data to be parsed
:return: Current position in data | 625941e1d7e4931a7ee9e2b4 |
def __repr__(self): <NEW_LINE> <INDENT> context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) <NEW_LINE> return '<Twilio.Trusthub.V1.TrustProductsChannelEndpointAssignmentContext {}>'.format(context) | Provide a friendly representation
:returns: Machine friendly representation
:rtype: str | 625941e1cad5886f8bd2736e |
def get_serializer_class(self): <NEW_LINE> <INDENT> if self.action == 'retrieve': <NEW_LINE> <INDENT> serializer_class = PickupSerializer <NEW_LINE> <DEDENT> return serializer_class | Sets the serializer for the pickup | 625941e1293b9510aa2c3627 |
def trim_rmdup_subsamp_reads(inBam, clipDb, outBam, n_reads=100000): <NEW_LINE> <INDENT> infq = list(map(util.file.mkstempfname, ['.in.1.fastq', '.in.2.fastq'])) <NEW_LINE> tools.picard.SamToFastqTool().execute(inBam, infq[0], infq[1]) <NEW_LINE> trimfq = list(map(util.file.mkstempfname, ['.trim.1.fastq', '.trim.2.fast... | Take reads through Trimmomatic, Prinseq, and subsampling.
This should probably move over to read_utils or taxon_filter. | 625941e17d847024c06be654 |
def deploy(): <NEW_LINE> <INDENT> remote_tmp_tar = '/tmp/example.tar.gz' <NEW_LINE> tag = datetime.now().strftime('%Y-%M-%d_%H.%M.%S') <NEW_LINE> run('rm -f %s' % remote_tmp_tar) <NEW_LINE> put('example.tar.gz', remote_tmp_tar) <NEW_LINE> remote_dist_dir = '/srv/www.example.com-%s' % tag <NEW_LINE> remote_dist_link = '... | 定义一个部署任务 | 625941e1099cdd3c635f0fef |
def _apply_slicing(self, data: _TData, slice_start: int = 0, slice_end: int = -1) -> _TData: <NEW_LINE> <INDENT> if isinstance(data, dict): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for key in data.keys(): <NEW_LINE> <INDENT> result[key] = self._apply_slicing(data[key], slice_start, slice_end) <NEW_LINE> <DEDENT> <DED... | Apply array-like slicing to data (including dictionaries)
:param data: Data to be sliced
:param slice_start: Start index
:param slice_end: End index
:return: Sliced data | 625941e1cb5e8a47e48b7e3a |
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=10, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): <NEW_LINE> <INDENT> plt.figure() <NEW_LINE> plt.title(title) <NEW_LINE> if ylim is not None: <NEW_LINE> <INDENT> plt.ylim(*ylim) <NEW_LINE> <DEDENT> plt.xlabel("Training examples") <NEW_LINE> plt.ylabel("Sc... | Generate a simple plot of the test and training learning curve.
Parameters
----------
estimator : object type that implements the "fit" and "predict" methods
An object of that type which is cloned for each validation.
title : string
Title for the chart.
X : array-like, shape (n_samples, n_features)
Train... | 625941e1be383301e01b5814 |
def __init__(self, source, filename=None, lineno=-1, lookup='strict', xform=None): <NEW_LINE> <INDENT> if isinstance(source, str): <NEW_LINE> <INDENT> self.source = source <NEW_LINE> node = _parse(source, mode=self.mode) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert isinstance(source, _ast.AST), '... | Create the code object, either from a string, or from an AST node.
:param source: either a string containing the source code, or an AST
node
:param filename: the (preferably absolute) name of the file containing
the code
:param lineno: the number of the line on which the code was found
... | 625941e1e76e3b2f99f3ab9c |
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument('-o', '--out', help='Name of output file.', dest='out', default=OUT_FILE, metavar='out_file') <NEW_LINE> parser.add_argument('-r', '--rows', help='Number of rows to fill.', type=int, dest='rows', default=ROWS, metavar='row... | Setup. | 625941e1fbf16365ca6f6560 |
def _get_lifetime_sparseness(self, unit_id): <NEW_LINE> <INDENT> df = self.conditionwise_statistics.drop(index=self.null_condition, level=1, errors='ignore') <NEW_LINE> responses = df.loc[unit_id]['spike_count'].values <NEW_LINE> return lifetime_sparseness(responses) | Computes lifetime sparseness of responses for one unit | 625941e1a934411ee3751a2a |
def summary(self, shorten=False, *args, **kwargs): <NEW_LINE> <INDENT> summary = super().summary(shorten=shorten, *args, **kwargs) <NEW_LINE> if self.ugrid and not shorten: <NEW_LINE> <INDENT> detail_lines = str(self.ugrid).split("\n") <NEW_LINE> (i_wanted_line,) = [ i for i, line in enumerate(detail_lines) if "topolog... | Provide cube summaries, extended to include mesh information. | 625941e101c39578d7e751d1 |
def disable_hostgroup_passive_svc_checks( hostgroup_name, command_file=None, timestamp=0 ): <NEW_LINE> <INDENT> return send_command("DISABLE_HOSTGROUP_PASSIVE_SVC_CHECKS", command_file, timestamp, hostgroup_name) | Disables passive checks for all services associated with hosts
in a particular hostgroup. | 625941e1e1aae11d1e74a050 |
@check_disabled <NEW_LINE> def delete_data_set(name): <NEW_LINE> <INDENT> endpoint_url = '{url}/data-sets/{name}'.format(url=settings.BACKDROP_URL, name=name) <NEW_LINE> backdrop_request = lambda: requests.delete( endpoint_url, headers=_get_headers()) <NEW_LINE> _send_backdrop_request(backdrop_request) | Connect to Backdrop and delete a collection called ``name``. | 625941e12eb69b55b151cc49 |
def discovery(name: str) -> Optional[Type["GitlabRegistry"]]: <NEW_LINE> <INDENT> if name == "gitlab_registry": <NEW_LINE> <INDENT> return GitlabRegistry <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Function expected by the `bakerman.handler.discoverLookupHandler` factory
function to determine `bakerman.plugin.lookup.gitlab_registry.Handler` is
the required Plugin for `name`.
Arguments:
name: The name of the lookup type
Returns:
The `GitlabRegistry` class or None | 625941e107f4c71912b1181a |
def __GetRatio(self): <NEW_LINE> <INDENT> return _Box2D.b2GearJoint___GetRatio(self) | __GetRatio(self) -> float32 | 625941e1656771135c3ebc08 |
@network.group(short_help='work with routed org vdc networks') <NEW_LINE> @click.pass_context <NEW_LINE> def routed(ctx): <NEW_LINE> <INDENT> pass | Work with routed org vdc networks.
Examples
vcd network routed create routed_net1
--gateway-name gateway1
--subnet 5.5.6.1/20
--description 'Routed VDC network'
--dns1 7.7.7.3
--dns2 7.7.7.4
--dns-suffix examp... | 625941e14d74a7450ccd455a |
def create_filename(self, name: str): <NEW_LINE> <INDENT> output_dir = self.args["--output-dir"] <NEW_LINE> if not os.path.isdir(output_dir): <NEW_LINE> <INDENT> os.makedirs(output_dir) <NEW_LINE> <DEDENT> output_file = name + "." + self.args["--format"] <NEW_LINE> output_file = os.path.join(output_dir, output_file) <N... | . | 625941e1b5575c28eb68e399 |
def checkMixedQuote(): <NEW_LINE> <INDENT> print("My cat's name is \"Button\"") | This function displays single and double quotes | 625941e1baa26c4b54cb14b2 |
def __init__(self): <NEW_LINE> <INDENT> self.i={} <NEW_LINE> self.p={} <NEW_LINE> self.c={} <NEW_LINE> self.cityi={} <NEW_LINE> self.protali={} <NEW_LINE> self.ic={} <NEW_LINE> self.ip={} <NEW_LINE> self.wm={} <NEW_LINE> self.CXi={} <NEW_LINE> self.CXc={} <NEW_LINE> self.CXp={} <NEW_LINE> self.CXwm={} <NEW_LINE> self.i... | 初始化 | 625941e1baa26c4b54cb14b1 |
def test_3_check_orientdb_dashboard_app(self, orientdb_api, orientdb_instance): <NEW_LINE> <INDENT> orientdb_dashboard = next((s for s in ServiceInstance.get_list() if s.offering_label == ServiceLabels.ORIENT_DB if s.name == orientdb_instance.name), None) <NEW_LINE> step("Create OrientDB dashboard application API") <NE... | <b>Description:</b>
Check orientdb dashboard app.
<b>Input data:</b>
1. tested database name
<b>Expected results:</b>
Test passes if all orientdb dashboard application functionalities work properly.
<b>Steps:</b>
1. Retrieve database names using application.
2. Check that database name is in retrieved list.
3. Get d... | 625941e17d43ff24873a3038 |
def GetAddressByteSize(self): <NEW_LINE> <INDENT> return _lldb.SBTarget_GetAddressByteSize(self) | GetAddressByteSize(SBTarget self) -> uint32_t | 625941e144b2445a33932429 |
def update_attrs(self, attrs, url, localhost, stages, headers): <NEW_LINE> <INDENT> if not self.applies_to_stages(stages): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> parent = super(GifImage, self) <NEW_LINE> parent.update_attrs(attrs, url, localhost, stages, headers) <NEW_LINE> attrs['gifparser'] = GifParser(url) | Add GIF parser to attributes. | 625941e1a17c0f6771cbe3e5 |
def stmt_alias(self, node, chans): <NEW_LINE> <INDENT> if node.slice.symbol.type == T_VAR_ARRAY: <NEW_LINE> <INDENT> self.asm('add %0, %1, %2', outop=node.left.name, inops=[node.slice.name, '({})*{}'.format( self.expr(node.slice.base), defs.BYTES_PER_WORD)]) <NEW_LINE> <DEDENT> elif node.slice.symbol.type == T_REF_ARRA... | Generate an alias statement. If the slice target is an array we must use
some inline assembly to get xcc to load the address for us. Otherwise,
we can just perform arithmetic on the pointer. | 625941e173bcbd0ca4b2c40b |
def delete(self, hash_id, identity): <NEW_LINE> <INDENT> redis = StrictRedis(connection_pool=self.redis_pool) <NEW_LINE> hash_key = key_generator(self.hash_key, hash_id) <NEW_LINE> key = key_generator(self.key, identity) <NEW_LINE> try: <NEW_LINE> <INDENT> i = redis.hdel(hash_key, key) <NEW_LINE> return i <NEW_LINE> <D... | For Deleting a key inside the hash
:param hash_id:
:param identity:
:return: | 625941e163d6d428bbe44886 |
@replication.route('/pull_request', methods=["POST"]) <NEW_LINE> def pull_request(): <NEW_LINE> <INDENT> payload = request.get_json() <NEW_LINE> bugsnag.configure_request(meta_data={"payload": payload}) <NEW_LINE> pr_data = payload.get("pull_request") <NEW_LINE> if not pr_data: <NEW_LINE> <INDENT> resp = jsonify({"erro... | Webhook endpoint for ``pull_request`` events on Github. | 625941e157b8e32f52483833 |
def process_song_file(cur, filepath): <NEW_LINE> <INDENT> df = pd.read_json(filepath, lines=True) <NEW_LINE> song_data = df[['song_id', 'title', 'artist_id', 'year', 'duration']].values[0] <NEW_LINE> cur.execute(song_table_insert, song_data) <NEW_LINE> artist_data = df[['artist_id', 'artist_name', 'artist_location', 'a... | Create the songs and artists dimensional tables.
Parameters:
cur (Object): cursor of psycopg2 connect
filepath (String): file path of datasets
Returns:
Null | 625941e199cbb53fe6792f7b |
def _buildNetwork(*layers, **options): <NEW_LINE> <INDENT> bias = options['bias'] if 'bias' in options else False <NEW_LINE> net = FeedForwardNetwork() <NEW_LINE> layerParts = iter(layers) <NEW_LINE> firstPart = iter(next(layerParts)) <NEW_LINE> firstLayer = next(firstPart) <NEW_LINE> net.addInputModule(firstLayer) <NE... | This is a helper function to create different kinds of networks.
`layers` is a list of tuples. Each tuple can contain an arbitrary number of
layers, each being connected to the next one with IdentityConnections. Due
to this, all layers have to have the same dimension. We call these tuples
'parts.'
Afterwards, the la... | 625941e10a366e3fb873ebb3 |
def set_line_alpha(self, *args, **kwargs): <NEW_LINE> <INDENT> return _qtgui_swig.ber_sink_b_sptr_set_line_alpha(self, *args, **kwargs) | set_line_alpha(ber_sink_b_sptr self, int which, double alpha) | 625941e1b7558d58953c52a3 |
def corrupt(array, corr): <NEW_LINE> <INDENT> array = np.array(array) <NEW_LINE> for row in array: <NEW_LINE> <INDENT> row[np.random.choice(len(row), int(corr*len(row)))] = 0.0 <NEW_LINE> <DEDENT> return array | Set a fraction ('corr') of the entries in a matrix to zero. May or may not be equivalent to a dropout function in tensorflow. | 625941e11f5feb6acb0c4ee0 |
def set_viewport(*args): <NEW_LINE> <INDENT> x, y, w, h = args[0] if len(args) == 1 else args <NEW_LINE> gl.glViewport(int(x), int(y), int(w), int(h)) | Set the OpenGL viewport
This is a wrapper for gl.glViewport.
Parameters
----------
x, y, w, h : int | tuple
X and Y coordinates, plus width and height. Can be passed in as
individual components, or as a single tuple with four values. | 625941e13317a56b86939fe6 |
def apply_filters(self, filters, force_clear_all=True): <NEW_LINE> <INDENT> logger.debug('Setting filters: {}'.format(filters)) <NEW_LINE> _pre_filters = [] <NEW_LINE> if force_clear_all: <NEW_LINE> <INDENT> self.page.filter.clear_all() <NEW_LINE> assert len(self.page.filter.active_filters) == 0 <NEW_LINE> <DEDENT> els... | Apply supplied filter in to UI and assert with supplied and applied filters
Parameters
----------
filters : list
A list for filter. filter should be a dict.
filter = {'name': 'Health', 'value': 'Healthy'}
Take filter name from pre defined enum
force_clear_all : boolean
Default False.
If this value ... | 625941e1283ffb24f3c55c93 |
def key_to_data(key, n): <NEW_LINE> <INDENT> x, y = key <NEW_LINE> xbin = bin(x)[2:] <NEW_LINE> ybin = bin(y)[2:] <NEW_LINE> databin = '1' +xbin.zfill(len(bin(n)[2:])) + ybin <NEW_LINE> data = int(databin, 2) <NEW_LINE> return data | Calculates a congruent integer to the numerator that is divisible by the denominator.
Args:
key (int, int): The key pair to be encoded.
n (int): The maximum number the first term in the key can be.
Returns:
int: data. The key pair encoded as an integer. | 625941e123849d37ff7b3422 |
def getDataKW(self): <NEW_LINE> <INDENT> return self._get_data_kw( ) | @rtype: SubstitutionList | 625941e17cff6e4e81117d1b |
def create_product(file, url, prod_name, prod_date, md5_hash): <NEW_LINE> <INDENT> settings = {} <NEW_LINE> try: <NEW_LINE> <INDENT> settings_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'settings.json') <NEW_LINE> settings = json.load(open(settings_file)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <IND... | Create skeleton directory structure for product and run configured
metadata extractor. | 625941e13c8af77a43ae3b39 |
def filter_links(iterable, rargname, post): <NEW_LINE> <INDENT> if rargname is None and post is None: <NEW_LINE> <INDENT> raise Exception("Specify either 'rargname' or 'post'") <NEW_LINE> <DEDENT> elif rargname is None: <NEW_LINE> <INDENT> return (x for x in iterable if x.post == post) <NEW_LINE> <DEDENT> elif post is ... | Filter links according to the label.
None specifies a wildcard. | 625941e1ab23a570cc25051b |
def prune_data(input_name, output_name, min_reviews_per_user, percent): <NEW_LINE> <INDENT> random.seed(3) <NEW_LINE> review_counts = dict() <NEW_LINE> users = {} <NEW_LINE> restaurants = {} <NEW_LINE> with open(input_name, 'rb') as input_file: <NEW_LINE> <INDENT> for i in input_file.readlines(): <NEW_LINE> <INDENT> da... | :param input_name:
:param output_name:
:param min_reviews_per_user:
:param percent: what % of the eligible data to keep
:return: | 625941e1d4950a0f3b08c6e0 |
@add_arg_scope <NEW_LINE> def temporal_latent_to_dist(name, x, hparams, output_channels=None): <NEW_LINE> <INDENT> res_channels = common_layers.shape_list(x)[-1] <NEW_LINE> if output_channels is None: <NEW_LINE> <INDENT> output_channels = res_channels <NEW_LINE> <DEDENT> with tf.variable_scope(name, reuse=tf.AUTO_REUSE... | Network that maps a time-indexed list of 3-D latents to a gaussian.
Args:
name: variable scope.
x: List of 4-D Tensors indexed by time, (NHWC)
hparams: tf.contrib.training.Hparams.
output_channels: int, Number of channels of the output gaussian mean.
Returns:
dist: tfp.distributions.Normal | 625941e1cb5e8a47e48b7e3b |
def get_type(self): <NEW_LINE> <INDENT> return self.__alert_type | Returns the type | 625941e18c3a873295158754 |
def xa(self, x_surface, geom): <NEW_LINE> <INDENT> mu = np.zeros(self.n_state) <NEW_LINE> mu[self.idx_lamb] = self.mean.copy() <NEW_LINE> return mu | Mean of prior distribution. | 625941e15510c4643540f771 |
def setup_method(self, method): <NEW_LINE> <INDENT> cls = self.__class__ <NEW_LINE> common.write_to([cls.log.info, DEBUG_LOG.info], common.MAKE_CAP(method.__name__, '-')) <NEW_LINE> server_test_file = os.path.join(cls.server_dir, cls.test_file) <NEW_LINE> create = cls.bridge.sudo("touch %s" % server_test_file) <NEW_LIN... | Test setup for a method level (will run for every method in class).
Writes header with this method's name to the test log and `DEBUG_LOG`.
Setup nfs server: creates test file.
Setup nfs client: executes `set_up.Case.client` (read description).
Writes setup results to the current test log | 625941e14c3428357757c6bc |
def test_authorized_user_can_view_entry_update_view(self): <NEW_LINE> <INDENT> self.assertTrue(self.client.login(username=self.user, password='password')) <NEW_LINE> r = self.client.get('/blogs/author_kawaztan/1/update/') <NEW_LINE> self.assertTemplateUsed(r, 'blogs/entry_form.html') <NEW_LINE> self.assertTrue('object'... | Tests authorized user can view EntryUpdateView | 625941e1091ae356686672ee |
def get_test_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples( self._read_file(os.path.join(data_dir, "test.txt")), "test") | See base class. | 625941e123e79379d52ee8f5 |
def preprocess_googleplus(activity): <NEW_LINE> <INDENT> return post | Tweaks a Google+ activity before rendering and posting.
Args:
activity: dict, decoded JSON Google+ activity.
Returns: the processed activity dict, or None if it should not be posted | 625941e1cdde0d52a9e533cb |
def _populateValues(values, dataName, prefix, data, totalRows, start, count, pageSize, order): <NEW_LINE> <INDENT> values[dataName] = data <NEW_LINE> values[(prefix and prefix + 'Start' or 'start')] = start <NEW_LINE> values[(prefix and prefix + 'Count' or 'count')] = count <NEW_LINE> values[(prefix and prefix + 'Range... | Populate the values list with the data about the list provided. | 625941e191f36d47f21ac88c |
def createMIP(np_img, slices_num=15): <NEW_LINE> <INDENT> img_shape = np_img.shape <NEW_LINE> np_mip = np.zeros(img_shape) <NEW_LINE> for i in range(img_shape[0]): <NEW_LINE> <INDENT> start = max(0, i - slices_num) <NEW_LINE> np_mip[i, :, :] = np.amax(np_img[start:i + 1], 0) <NEW_LINE> <DEDENT> return np_mip | create the mip image from original image, slice_num is the number of
slices for maximum intensity projection | 625941e1a05bb46b383ecbb5 |
def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return self.create(request, *args, **kwargs) | Give this view the ability to create.
Or could just use a mixin | 625941e12ae34c7f2600d4c7 |
def _comp_cancelled_proportion(stream): <NEW_LINE> <INDENT> prepared_data = map(lambda f: np.array([1, 1 if f.cancelled else 0]), stream) <NEW_LINE> results = functools.reduce(lambda x, y: x+y, prepared_data, 0) <NEW_LINE> if isinstance(results, int) and results == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> e... | Compute proportion (in percentage) of number of cancelled flights over number of flights of a stream. | 625941e14527f215b584c7e9 |
def test_getreader(self): <NEW_LINE> <INDENT> reader = codecs.getreader('imap4-utf-7')(StringIO('Hello&AP8-world')) <NEW_LINE> self.assertEqual(reader.read(), u'Hello\xffworld') | C{codecs.getreader('imap4-utf-7')} returns the I{imap4-utf-7} stream
reader class. | 625941e1090684286d50f080 |
def isCircular(n): <NEW_LINE> <INDENT> a = [] <NEW_LINE> for i in range(len(str(n))): <NEW_LINE> <INDENT> a.append(int(rotate(str(n), i))) <NEW_LINE> <DEDENT> for val in a: <NEW_LINE> <INDENT> if not pe.isPrime(val): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True | Returns true if all permutations of a given prime are also prime. | 625941e130c21e258bdfa836 |
def create_user(self, username, email, password=None): <NEW_LINE> <INDENT> if not email: <NEW_LINE> <INDENT> raise ValueError("Users must have an email address") <NEW_LINE> <DEDENT> if not username: <NEW_LINE> <INDENT> raise ValueError("Users must have an username") <NEW_LINE> <DEDENT> now = timezone.now() <NEW_LINE> u... | Creates and saves a Usera | 625941e18e05c05ec3eea70e |
def testBaseModelMemcacheWrappedGet(self): <NEW_LINE> <INDENT> key_name = 'foo_key_name' <NEW_LINE> memcache_key_name = 'mwg_%s_%s' % (models.BaseModel.kind(), key_name) <NEW_LINE> self.mox.StubOutWithMock(models, 'memcache', True) <NEW_LINE> self.mox.StubOutWithMock(models.BaseModel, 'get_by_key_name', True) <NEW_LINE... | Test BaseModel.MemcacheWrappedGet() when not cached. | 625941e13eb6a72ae02ec87c |
def addmv_(self, x, y): <NEW_LINE> <INDENT> return self.params_func("addmv_", [x.id, y.id]) | Performs a matrix-vector product of the matrix x and the vector vec.
The vector tensor is added to the final result inplace.
Parameters
----------
x : FloatTensor
tensor for multiplication
vec : FloatTensor
Vector for Matrix-Vector Product
Returns
-------
FloatTensor
Caller with values inplace | 625941e1d164cc61757830e5 |
def test_date_trunc(self): <NEW_LINE> <INDENT> timezone.activate("Australia/Adelaide") <NEW_LINE> n = datetime.datetime(2017, 12, 31, 20, 10, 30, 123456) <NEW_LINE> a = timezone.make_aware(n) <NEW_LINE> o = NaiveDateTimeTestModel.objects.create(aware=a, naive=n) <NEW_LINE> o.refresh_from_db() <NEW_LINE> def query_trunc... | Test that date truncating works regardless of active timezone. | 625941e1b545ff76a89141ac |
def get_plot_df(top_left, bot_right, api_key=None, n_vert=15, n_horiz=30): <NEW_LINE> <INDENT> if api_key is None: <NEW_LINE> <INDENT> raise ValueError('remember to enter a api key for the Google Elevation API') <NEW_LINE> <DEDENT> v_range, h_range = _make_ranges(top_left, bot_right, n_vert=n_vert, n_horiz=n_horiz) <NE... | Function to get the dataframe to plot the joyplot of the geography
---------
Args:
top_left (tuple): tuple of (lat,lng), both floats, that is the top left of the area you want to query
bot_right (tuple): tuple of (lat,lng), both floats, that is the bottom right of the area you want to query
api_key (str): t... | 625941e115fb5d323cde0eab |
def _create_tbl_stmt(name, keys, pkey="id", pktype="INTEGER"): <NEW_LINE> <INDENT> kts = ["{} {}".format(k, pktype + " PRIMARY KEY" if k == pkey else "TEXT") for k in keys] <NEW_LINE> return "CREATE TABLE IF NOT EXISTS '{}' ({})".format(name, ", ".join(kts)) | :param name: Table name
:param keys: Keys
:param pkey: Primary key name
:param pktype: SQL type of primary key
:return: SQL statement to create a table | 625941e115baa723493c430e |
def text_params(self, pos, is_curr): <NEW_LINE> <INDENT> pos_x, pos_y = 0,0 <NEW_LINE> if is_curr: <NEW_LINE> <INDENT> pos_x, pos_y = -self.pos_x, self.pos_y <NEW_LINE> <DEDENT> return self.picture_textures[pos][1]==pos, { "text":str(self.picture_textures[pos][1]), "start_x":X_OFFSET+PIECE_SCALED_SIZE//2+PIECE_SCALED_S... | returns draw text parameters | 625941e145492302aab5e65e |
def create_output_from_token(name: str, description: str, token: str): <NEW_LINE> <INDENT> no_prompt = False <NEW_LINE> if 'noprompt' in token: <NEW_LINE> <INDENT> no_prompt = True <NEW_LINE> token = token.replace(' noprompt', '') <NEW_LINE> <DEDENT> output_type = token.lower().strip() <NEW_LINE> out = None <NEW_LINE> ... | Creates an output (or destination parameter) definition from a token string | 625941e194891a1f4081be41 |
def authenticate(self): <NEW_LINE> <INDENT> self.connection.authenticate() | Authenticate against the server.
Normally this is called automatically when you first access the API,
but you can call this method to force authentication right now.
Returns on success; raises :exc:`~openstack.compute.Unauthorized` if
the credentials are wrong. | 625941e107d97122c4178c2a |
def users(self): <NEW_LINE> <INDENT> return self.list | Users list. | 625941e144b2445a3393242a |
def main(): <NEW_LINE> <INDENT> strategies = ['nothanks', 'threshold', 'sequence_threshold'] <NEW_LINE> for name in ['nothanks'] + strategies: <NEW_LINE> <INDENT> logger = logging.getLogger(name) <NEW_LINE> logger.setLevel(level=logging.WARNING) <NEW_LINE> logger.addHandler(logging.StreamHandler(sys.stdout)) <NEW_LINE>... | Select strategies for No Thanks competition, run, and print results. | 625941e131939e2706e4d1fb |
def test_dpp_reconfig_connector_different_groups(dev, apdev): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> run_dpp_reconfig_connector(dev, apdev, conf_curve="secp384r1") <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> dev[0].set("dpp_config_processing", "0", allow_fail=True) | DPP reconfiguration connector with different groups | 625941e1d486a94d0b98e4dd |
def run_once(model, losses, weights, saver, summary_writer, summary_op): <NEW_LINE> <INDENT> model_path = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) <NEW_LINE> if not model_path: <NEW_LINE> <INDENT> tf.logging.info("Skipping evaluation. No checkpoint found in: %s", FLAGS.checkpoint_dir) <NEW_LINE> return <NEW_LIN... | Evaluates the latest model checkpoint.
Args:
model: Instance of SkipThoughtsModel; the model to evaluate.
losses: Tensor; the target cross entropy losses for the current batch.
weights: A Tensor of weights corresponding to losses.
saver: Instance of tf.train.Saver for restoring model Variables.
summary_writer... | 625941e13eb6a72ae02ec87d |
def __init__(self, tag, class_val, id_val, text_re, char_lim): <NEW_LINE> <INDENT> if not tag: <NEW_LINE> <INDENT> self.tag = None <NEW_LINE> <DEDENT> elif isinstance(tag, str): <NEW_LINE> <INDENT> self.tag = [tag] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.tag = tag <NEW_LINE> <DEDENT> if not class_val: <NEW_L... | Initialize a _Pattern instance. An element matches if its
tag, class and id equal tag, class_val and id_val (or, in case
of lists, are contained therein), and if its text content has
length <= char_lim and matches text_re. To skip any of these
checks, set the correspongin argument to None. | 625941e150485f2cf553d132 |
def new_physic_machine(self,num=1): <NEW_LINE> <INDENT> while num>0: <NEW_LINE> <INDENT> self.pm_size+=1; <NEW_LINE> npm = { 're_cpu':self.machine_info['CPU'], 're_mem':self.machine_info['MEM'], 'vm_size':0 }; <NEW_LINE> self.PM_status.append(npm); <NEW_LINE> self.PM.append({}); <NEW_LINE> num-=1; <NEW_LINE> <DEDENT> r... | 创建num个新的物理机,返回物理机数量 | 625941e13539df3088e2e6e1 |
def checkParameterValuesBeforeExecuting(alg, parameters, context): <NEW_LINE> <INDENT> start = alg.parameterAsDouble(parameters, 'start', context) <NEW_LINE> end = alg.parameterAsDouble(parameters, 'end', context) <NEW_LINE> step = alg.parameterAsDouble(parameters, 'step', context) <NEW_LINE> if start >= end: <NEW_LINE... | Verify if we have the right parameters | 625941e176e4537e8c351a0c |
def predict_dist(self,X): <NEW_LINE> <INDENT> mu_pred = self._decision_function(X) <NEW_LINE> data_noise = 1./self.beta_ <NEW_LINE> model_noise = np.sum(np.dot(X,self.eigvecs_)**2 * self.eigvals_,1) <NEW_LINE> var_pred = data_noise + model_noise <NEW_LINE> return [mu_pred,var_pred] | Calculates mean and variance of predictive distribution for each data
point of test set.(Note predictive distribution for each data point is
Gaussian, therefore it is uniquely determined by mean and variance)
Parameters
----------
x: array-like of size (n_test_samples, n_features)
... | 625941e1596a897236089e53 |
def pdu_received(self, data): <NEW_LINE> <INDENT> if data.__class__ == pdu.A_ASSOCIATE_AC: <NEW_LINE> <INDENT> self.A_ASSOCIATE_AC_PDU_received(data) <NEW_LINE> <DEDENT> elif data.__class__ == pdu.A_ASSOCIATE_RJ: <NEW_LINE> <INDENT> self.A_ASSOCIATE_RJ_PDU_received(data) <NEW_LINE> <DEDENT> elif data.__class__ == pdu.A... | Dispatch PDU messages to the respective *_received handlers. | 625941e171ff763f4b549a28 |
def test_baidu_search(self): <NEW_LINE> <INDENT> driver = self.driver <NEW_LINE> driver.get(self.base_url) <NEW_LINE> driver.find_element_by_id("kw").send_keys("HTNMLTestRunner") <NEW_LINE> driver.find_element_by_id("su").click() | 百度搜索用例 | 625941e1091ae356686672ef |
def get_imported_module_from_file(file_path): <NEW_LINE> <INDENT> if PYTHON_VERSION == 3: <NEW_LINE> <INDENT> imported_module = importlib.machinery.SourceFileLoader( 'module_name', file_path).load_module() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> imported_module = imp.load_source('module_name', file_path) <NEW_LIN... | import module from python file path and return imported module
| 625941e1b57a9660fec33c20 |
def archive(self): <NEW_LINE> <INDENT> archived_container = None <NEW_LINE> with timer_print("Archiving the container"): <NEW_LINE> <INDENT> with open(self.get_archive_flag_path(), "w") as f: <NEW_LINE> <INDENT> f.write(datetime.datetime.now().isoformat()) <NEW_LINE> <DEDENT> if config.RUNTIME_CONFIG_PATH == config.ARC... | Archive the given container to ARCHIVE_CONFIG_PATH | 625941e10fa83653e465734f |
def vara_cfg() -> s.Configuration: <NEW_LINE> <INDENT> global _CFG <NEW_LINE> if not _CFG: <NEW_LINE> <INDENT> _CFG = create_new_varats_config() <NEW_LINE> s.setup_config( _CFG, ['.varats.yaml', '.varats.yml'], "VARATS_CONFIG_FILE" ) <NEW_LINE> s.update_env(_CFG) <NEW_LINE> <DEDENT> return _CFG | Get the current vara config. | 625941e1a8ecb033257d3462 |
def populate_keys_tree(self): <NEW_LINE> <INDENT> for group in HOTKEYS: <NEW_LINE> <INDENT> parent = self.store.append(None, [None, group['label'], None, None]) <NEW_LINE> for item in group['keys']: <NEW_LINE> <INDENT> if item['key'] == "show-hide" or item['key'] == "show-focus": <NEW_LINE> <INDENT> accel = self.settin... | Reads the HOTKEYS global variable and insert all data in
the TreeStore used by the preferences window treeview. | 625941e15fdd1c0f98dc05cb |
def generate_disk_grid(center_x, center_y, grid_step, disk_radius): <NEW_LINE> <INDENT> grid_cells = [] <NEW_LINE> for i in range(grid_step, 2 * disk_radius + grid_step, grid_step): <NEW_LINE> <INDENT> for j in range(grid_step, 2 * disk_radius + grid_step, grid_step): <NEW_LINE> <INDENT> grid_cell = { 'x': center_x - d... | Defining the umbrella cloud:
1) generate equidistant points in the square enclosing the disk using a grid step
2) keep only the points enclosed by disk radius | 625941e1fff4ab517eb2f7d4 |
def __init__(self, _admin_property_err): <NEW_LINE> <INDENT> self.admin_property_err = _admin_property_err <NEW_LINE> return | Constructor. | 625941e1d268445f265b5205 |
def resolveA(self): <NEW_LINE> <INDENT> resolved_hosts = {} <NEW_LINE> active_queries = {} <NEW_LINE> host_queue = self.hosts[:] <NEW_LINE> def collect_results(): <NEW_LINE> <INDENT> for query in self.adns.completed(): <NEW_LINE> <INDENT> answer = query.check() <NEW_LINE> host = active_queries[query] <NEW_LINE> del act... | Resolves hosts and returns a dictionary of { 'host': 'ip' }. | 625941e18e7ae83300e4b364 |
def _post(endpoint, payload): <NEW_LINE> <INDENT> if ENV.use_v2(): <NEW_LINE> <INDENT> return _device_request_v2(payload) <NEW_LINE> <DEDENT> if ENV.use_mqtt(): <NEW_LINE> <INDENT> return _mqtt_request(payload) <NEW_LINE> <DEDENT> return _device_request('POST', endpoint, payload) | Post a payload to the device Farmware API.
Since the only available endpoint is 'celery_script',
use `send_celery_script(command)` instead.
Args:
endpoint (str): 'celery_script'
payload (dict): i.e., {'kind': 'take_photo', 'args': {}}
Returns:
requests response object | 625941e18c0ade5d55d3ed55 |
def __init__(self, hass, driver, name, entity_id, aid, config, category=CATEGORY_OTHER): <NEW_LINE> <INDENT> super().__init__(driver, name, aid=aid) <NEW_LINE> model = split_entity_id(entity_id)[0].replace("_", " ").title() <NEW_LINE> self.set_info_service( firmware_revision=__version__, manufacturer=MANUFACTURER, mode... | Initialize a Accessory object. | 625941e126068e7796caf07b |
def emitterUpHasDimensions(self,dim1,dim2,dim3): <NEW_LINE> <INDENT> return self.emitterUp.hasDimensions(dim1,dim2,dim3) | Check if the EmitterUp variable has the given dimensions
:param dim1: first dimension
:param dim2: second dimension
:param dim3: third dimension
:return: Boolean | 625941e171ff763f4b549a29 |
def resnet101(pretrained=False, **kwargs): <NEW_LINE> <INDENT> model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) <NEW_LINE> print("model loading...") <NEW_LINE> if pretrained: <NEW_LINE> <INDENT> model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) <NEW_LINE> <DEDENT> print("model load end...") <NEW_LIN... | Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet | 625941e10c0af96317bb857f |
def letter_body(amount): <NEW_LINE> <INDENT> body = ( f'Thank you for your generous donation of ${float(amount):,.2f}. Your gracious support ' 'helps us continue our important work doing what we do. We look forward to continuing to ' 'partner with you in the future. Please contact us if you have any questions or have a... | Return body of Thank You letter. | 625941e17b25080760e397ee |
def _4ZZZ(self): <NEW_LINE> <INDENT> if self.registers[self.vx] != (self.opcode & 0x00ff): <NEW_LINE> <INDENT> self.pc += 2 | Skips the next instruction if VX doesn't equal NN.
| 625941e138b623060ff0b184 |
def histogram_solution_1(): <NEW_LINE> <INDENT> sol_string = ["I've used matplotlib's hist function to plot the data.", "I have also used numpy's arange function to set the bin edges.", "A bin size of 5 hits the main cut points, revealing a smooth,", "but skewed curves. Are there similar characteristics among", "Pokemo... | Solution for Question 1 in histogram practice: create a histogram of
Pokemon special defense values. | 625941e14527f215b584c7ea |
def update_all_wkn(new_data): <NEW_LINE> <INDENT> if not 'boersenbewertung' in new_data: return 0 <NEW_LINE> shareinfolist = [] <NEW_LINE> for block in new_data['boersenbewertung']: <NEW_LINE> <INDENT> shareinfo = {} <NEW_LINE> blockkeys = new_data['boersenbewertung'][block].keys()&['wkns','isins'] <NEW_LINE> for entri... | It takes the wkn/isin information out of the table "boersenbwertung"
and update the data in "all_wkn_entries". | 625941e15fdd1c0f98dc05cc |
def get_last_next_match(team): <NEW_LINE> <INDENT> last_result = {} <NEW_LINE> next_match = {} <NEW_LINE> data = {} <NEW_LINE> url = "http://api.football-data.org/v1/teams/" + str(team) + "/fixtures" <NEW_LINE> api_key = "09fe2c72430f482d8a40307334ca6147" <NEW_LINE> headers = {'X-Auth-Token': api_key} <NEW_LINE> try: <... | Utilisation de l'api http://api.football-data.org/
pour récupérer le dernier résultat d'une équipe
et le prochain match | 625941e1796e427e537b095f |
def test_selectGraphicRendition(self): <NEW_LINE> <INDENT> self.protocol.selectGraphicRendition(str(BLINK), str(UNDERLINE)) <NEW_LINE> self.assertEqual( self.transport.value(), self.CSI + b"%d;%d" % (BLINK, UNDERLINE) + CSFinalByte.SGR.value, ) | L{ServerProtocol.selectGraphicRendition} writes a control
sequence containing the requested attributes and ending with
L{CSFinalByte.SGR} | 625941e16aa9bd52df03713d |
def iter_alignment(self, table_name): <NEW_LINE> <INDENT> table_name = table_name if table_name else self.master_table <NEW_LINE> try: <NEW_LINE> <INDENT> lock.acquire(True) <NEW_LINE> for tx, seq in self.cur.execute( "SELECT taxon, seq " "FROM [{}] " "WHERE aln_idx=?".format(table_name), (self.db_idx,)): <NEW_LINE> <I... | Generator for (taxon, sequence) tuples.
Generator that yields (taxon, sequence) tuples from the database.
Sequence data is retrieved from a database table specified either by
the `db_idx` or `table_suffix` arguments. `db_idx` will always
take precedence over `table_suffix` if both are provided. If none
are provided, t... | 625941e182261d6c526ab83c |
def getAction(self, gameState): <NEW_LINE> <INDENT> numAgents = gameState.getNumAgents() <NEW_LINE> def pacMax(gameState, depth, returnMove=False): <NEW_LINE> <INDENT> if gameState.isWin() or gameState.isLose() or depth == 0: <NEW_LINE> <INDENT> return self.evaluationFunction(gameState) <NEW_LINE> <DEDENT> value = floa... | Returns the expectimax action using self.depth and self.evaluationFunction
All ghosts should be modeled as choosing uniformly at random from their
legal moves. | 625941e1cc0a2c11143dd228 |
def sign_candidates(args): <NEW_LINE> <INDENT> def sign_file(filename): <NEW_LINE> <INDENT> asc_file = open(filename + '.asc', 'a') <NEW_LINE> logging.info("Signing %s" % filename) <NEW_LINE> proc = subprocess.check_call(['gpg', '-ba', '-o', '-', filename], stdout=asc_file) <NEW_LINE> asc_file.close() <NEW_LINE> <DEDEN... | Sign candidate artifacts in the dist development directory. | 625941e1be8e80087fb20fd5 |
def _check_error_code(self, response): <NEW_LINE> <INDENT> if "Error: 0x9001003c" in response['msg']: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif "Error: 0x9002002b" in response['msg']: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif "Error: 0x09010023" in response['msg']: <NEW_LINE> <INDENT> raise ViolinBacken... | Raise an exception when backend returns certain errors.
Error codes returned from the backend have to be examined
individually. Not all of them are fatal. For example, lun attach
failing becase the client is already attached is not a fatal error.
:param response: a response dict result from the vmemclient request | 625941e1d6c5a102081443e5 |
def parse_pathways(soup): <NEW_LINE> <INDENT> return { name: body for name, body in zip(parse_pathway_names(soup), parse_pathway_bodies(soup)) } | Given a BeautifulSoup of the pathways page, return a parsed dict | 625941e1099cdd3c635f0ff0 |
def get_animation_integral_bounds_change( self, graph, new_t_min, new_t_max, fade_close_to_origin=True, run_time=1.0 ): <NEW_LINE> <INDENT> curr_t_min = self.x_axis.point_to_number(self.area.get_left()) <NEW_LINE> curr_t_max = self.x_axis.point_to_number(self.area.get_right()) <NEW_LINE> if new_t_min is None: <NEW_LINE... | This method requires a lot of prerequisites:
self.area must be defined from self.get_area()
self.left_v_line and self.right_v_line must be defined from self.get_v_line
self.left_T_label_group and self.right_T_label_group must be defined from self.add_T_label
This method will return a VGroup of new mobjects for each of... | 625941e1cc0a2c11143dd229 |
def _bidirectional_selection_from_app(self): <NEW_LINE> <INDENT> self.talk_msgr.send_mess('bidirectional_selection') <NEW_LINE> response = self.talk_msgr.get_mess(expect=['bidirectional_selection_resp']) <NEW_LINE> return response[1]['value'] | does editor support selections with cursor at left?
Get this value directly from the external editor
**INPUTS**
*none*
**OUTPUTS**
*BOOL* -- true if editor allows setting the selection at the
left end of the selection | 625941e1d7e4931a7ee9e2b6 |
def test_noHeaders(self): <NEW_LINE> <INDENT> header = None <NEW_LINE> langs = headers.parseAcceptLanguage(header) <NEW_LINE> self.assertIsInstance(langs, list) <NEW_LINE> self.assertEqual(len(langs), 0) | No header should return an empty list. | 625941e1cad5886f8bd27370 |
def git_push(commit): <NEW_LINE> <INDENT> gitric.git_seed(get_project_root(), commit) <NEW_LINE> gitric.git_reset(get_project_root(), 'master') | Push the current tree to the remote server and reset the remote git
repository to the given commit. The commit can be any git object, be it a
hash, a tag or a branch. | 625941e18e71fb1e9831db3f |
def snow(self): <NEW_LINE> <INDENT> self.refl39_chan() <NEW_LINE> self.check_channels("_IR39Refl", 0.8, 1.63, 3.75) <NEW_LINE> lonlats = self[3.9].area.get_lonlats() <NEW_LINE> sunz = sza(self.time_slot, lonlats[0], lonlats[1]) <NEW_LINE> sunz = np.ma.masked_outside(sunz, 0.0, 88.0) <NEW_LINE> sunzmask = sunz.mask <NEW... | Make a 'Snow' RGB as suggested in the MSG interpretation guide
(rgbpart04.ppt). It is kind of special as it requires the derivation of
the daytime component of the mixed Terrestrial/Solar 3.9 micron
channel. Furthermore the sun zenith angle is used. | 625941e1a8ecb033257d3463 |
def reset(event): <NEW_LINE> <INDENT> for i in range(len_vector): <NEW_LINE> <INDENT> check_b1[i].deselect() <NEW_LINE> check_b2[i].deselect() <NEW_LINE> check_b3[i].deselect() | Функция сброса образов для запоминания. | 625941e1e76e3b2f99f3ab9d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.