code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _info_name(info): <NEW_LINE> <INDENT> if isinstance(info, zipfile.ZipInfo): <NEW_LINE> <INDENT> return info.filename.replace('\\', '/') <NEW_LINE> <DEDENT> return info.name.replace('\\', '/') | Returns a normalized file path for an archive info object
:param info:
An info object from _list_archive_members()
:return:
A unicode string with all directory separators normalized to "/" | 625941cc5f7d997b87174b7e |
def handle_delete(self): <NEW_LINE> <INDENT> if not self.resource_id: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.client().queue(self.resource_id, auto_create=False).delete() <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> self.client_plugin().ignore_not_found(exc) | Delete a zaqar message queue. | 625941cc236d856c2ad448c0 |
def parse_add_value(add_value): <NEW_LINE> <INDENT> region = None <NEW_LINE> rest = add_value <NEW_LINE> if add_value.startswith('r'): <NEW_LINE> <INDENT> i = 1 <NEW_LINE> while i < len(add_value) and add_value[i].isdigit(): <NEW_LINE> <INDENT> i += 1 <NEW_LINE> <DEDENT> region = int(add_value[1:i]) <NEW_LINE> rest = a... | Convert an add value, like 'r1z2-10.1.2.3:7878/sdf', to a dictionary.
If the string does not start with 'r<N>', then the value of 'region' in
the returned dictionary will be None. Callers should check for this and
set a reasonable default. This is done so callers can emit errors or
warnings if desired.
Similarly, 're... | 625941ccd164cc6175782e34 |
def test_search_across_multiple_journals_with_DOC_type(self): <NEW_LINE> <INDENT> response = self.client.get(self.multi_journal_search_path, { PARAM_QUERY: self.common_query_string, PARAM_OPERATOR: OPERATOR_OR, PARAM_TYPE: TYPE_DOCUMENT }) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> doc_count = Jo... | Testing Document type search
common query string is substring of all types(i.e video, images and doc etc)
but we should get search results for Doc type | 625941cc26068e7796caedc5 |
def get_parameters(data,epoch,sent_len,sent_numb,embedding_size): <NEW_LINE> <INDENT> dists = dict( vocab_size = data._data["vocab_size"], label_num = data._data["label_num"], num_blocks = 90, sent_len = sent_len, sent_numb = sent_numb, embedding_size = embedding_size, embeddings_mat = data._data["embeddings_mat"], lea... | create final conf
:return: neural network parameters for create_model | 625941cc4e4d5625662d44be |
def __init__(self, parent=None): <NEW_LINE> <INDENT> super(trialPurposeDialog, self).__init__(parent) <NEW_LINE> self.setupUi(self) | Constructor. | 625941ccff9c53063f47c2da |
def test_read_without_permission(self): <NEW_LINE> <INDENT> restricted_forum = _restricted_forum() <NEW_LINE> response = get(self.client, 'forums.threads', args=[restricted_forum.slug]) <NEW_LINE> eq_(404, response.status_code) | Listing threads without the view_in_forum permission should 404.
| 625941cc851cf427c661a5f5 |
def test(): <NEW_LINE> <INDENT> logging.info('Starting test recording (10sec)') <NEW_LINE> name = 'test-%i' % get_timestamp() <NEW_LINE> logging.info('Recording name: %s', name) <NEW_LINE> directory = '%s/%s' % (CONFIG['capture']['directory'], name) <NEW_LINE> logging.info('Recording directory: %s', directory) <NEW_LIN... | Make a test run doing a 10sec recording.
| 625941cc5fdd1c0f98dc0319 |
def stage(self, time): <NEW_LINE> <INDENT> if self.time_stages: <NEW_LINE> <INDENT> pairs = sorted(self.time_stages, key=lambda time_stage: time_stage[0]) <NEW_LINE> x_col, y_col = zip(*pairs) <NEW_LINE> fill_value = (y_col[0], y_col[-1]) <NEW_LINE> y_interp = interpolate.interp1d(x_col, y_col, bounds_error=False, fill... | Get the elevation that corresponds to a time.
Args:
time (float): In :math:`hours`.
Returns:
float: Elevation, in :math:`feet`.
Notes:
- If time is below the minimum time_stage, the lowest stage will be used.
- If time is above the maximum time_stage, the highest stage will be used. | 625941cc091ae35668667045 |
@jtui.route('/experiments/<experiment_id>/project', methods=['POST']) <NEW_LINE> @jwt_required() <NEW_LINE> @assert_form_params('project') <NEW_LINE> @decode_query_ids() <NEW_LINE> def update_project(experiment_id): <NEW_LINE> <INDENT> logger.info('save jterator project of experiment %d', experiment_id) <NEW_LINE> data... | Saves modifications of the pipeline and module descriptions to the
corresponding `.pipe` and `.handles` files. | 625941cc8e71fb1e9831d88f |
def HasRolloutGroup(self): <NEW_LINE> <INDENT> return self.rollout_group != _UNASSIGNED_ROLLOUT_GROUP | Indicates if this User has a rollout_group assigned. | 625941cc55399d3f0558879a |
def hex_and_ascii(data, bytes_per_line=10): <NEW_LINE> <INDENT> num_lines = ((len(data) - 1) // bytes_per_line) + 1 <NEW_LINE> if num_lines == 0: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> lines = [] <NEW_LINE> for i in range(num_lines): <NEW_LINE> <INDENT> str_hex = [] <NEW_LINE> str_ascii = [] <NEW_LINE> for j... | Convert a QByteArray to hex + ascii output. | 625941cc0a50d4780f666f79 |
def predict(self, features, num_predictions_per_location): <NEW_LINE> <INDENT> class_predictions_net = features <NEW_LINE> num_class_slots = self._num_classes + 1 <NEW_LINE> if self._use_dropout: <NEW_LINE> <INDENT> class_predictions_net = slim.dropout( class_predictions_net, keep_prob=self._dropout_keep_prob) <NEW_LIN... | Predicts boxes.
Args:
features: A float tensor of shape [batch_size, height, width, channels]
containing image features.
num_predictions_per_location: Number of box predictions to be made per
spatial location.
Returns:
class_predictions_with_background: A tensor of shape
[batch_size, num_anchors, nu... | 625941cc1b99ca400220ab98 |
def _gen_sturct_impls(self, structs, namespace, class_name): <NEW_LINE> <INDENT> if structs is None: <NEW_LINE> <INDENT> raise GenerateError("Structs is None") <NEW_LINE> <DEDENT> return u"\n".join([self._gen_struct_impl( x, namespace, class_name) for x in structs]) | Generate structs implementation for source file.
Generates implementation code of methods that provide schema items for
structs. This code should be used in the source file.
Keyword arguments:
structs -- list of structs to generate methods for.
namespace -- name of destination namespace.
class_name -- name of the par... | 625941ccec188e330fd5a886 |
def validate(*args) -> bool: <NEW_LINE> <INDENT> validity = True <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> if (type(arg) == tuple) or (type(arg) == list): <NEW_LINE> <INDENT> for item in arg: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> number = float(item) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDEN... | Sprawdzamy, czy wprowadzono poprawne liczby do kalkulatora | 625941ccc4546d3d9de72b1a |
def __get_object_by_id(self, identity: str) -> "Window|Pane": <NEW_LINE> <INDENT> if identity not in self.objects_by_id: <NEW_LINE> <INDENT> raise NameError("No such object: {0}!".format(identity)) <NEW_LINE> <DEDENT> return self.objects_by_id.get(identity) | Gets an object using the given ID
Parameters
----------
identity : string
The identity to look up
Returns
-------
Window|Pane
The object for this identity | 625941cc1f5feb6acb0c4c37 |
def __init__(self, all_hparams, all_flags, args): <NEW_LINE> <INDENT> all_hparams = process_hparams(all_hparams) <NEW_LINE> all_flags = process_flags(all_flags) <NEW_LINE> self.all_params = all_hparams + all_flags <NEW_LINE> print('OPTIMIZING OVER:') <NEW_LINE> pprint(self.all_params) <NEW_LINE> self.all_hparams = all_... | Speeds up hyperparameter search by parallelizing over GPUs
Argument:
all_hparams: dict
keys are hyperparameter names
values are list of values to try out for each
hyperparameter
all_flags: dict
key is name of flag
value is "fixed" or "param"
if "fixed", this ... | 625941cca8ecb033257d31b4 |
def test_max_value(self): <NEW_LINE> <INDENT> with pytest.raises(ValidationError): <NEW_LINE> <INDENT> score = Float(max_value=5.5) <NEW_LINE> score._load(5.6) | Test maximum value validation for the float field | 625941cc596a897236089ba7 |
def send_files_2(self): <NEW_LINE> <INDENT> fsize = os.path.getsize(QUERY_ORIGINAL_DATASET_FILE) <NEW_LINE> self.client_socket.send(str(fsize).encode('utf-8')) <NEW_LINE> if fsize: <NEW_LINE> <INDENT> with open(QUERY_ORIGINAL_DATASET_FILE, 'rb') as f: <NEW_LINE> <INDENT> data_buffer = f.read(BUFFER_SIZE) <NEW_LINE> whi... | docstring | 625941cc67a9b606de4a7fa0 |
def __check(self, name, other, is_match): <NEW_LINE> <INDENT> if not isinstance(other, basestring): <NEW_LINE> <INDENT> if is_match != isinstance(other, Matcher): <NEW_LINE> <INDENT> if is_match: <NEW_LINE> <INDENT> msg = 'The operator {0} for {1} was applied to something ' 'that is not a matcher... | Provide some diagnostics if the syntax is completely mixed up. | 625941cc66673b3332b92178 |
@remote_compatible <NEW_LINE> def test_ap_wps_from_event(dev, apdev): <NEW_LINE> <INDENT> ssid = "test-wps-conf" <NEW_LINE> hapd = hostapd.add_ap(apdev[0], {"ssid": ssid, "eap_server": "1", "wps_state": "2", "wpa_passphrase": "12345678", "wpa": "2", "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}) <NEW_LINE> dev[0].... | WPS PBC event on AP to enable PBC | 625941cc0383005118ecf6c9 |
def __init__(self, factory_function): <NEW_LINE> <INDENT> self.cache = {} <NEW_LINE> self.factory = factory_function | INPUT:
factory_function -- a function that returns objects (which this
class will weakref cache) | 625941cc3d592f4c4ed1d155 |
def dist_repo_init(tag, keys, task_opts): <NEW_LINE> <INDENT> state = koji.REPO_INIT <NEW_LINE> tinfo = get_tag(tag, strict=True) <NEW_LINE> tag_id = tinfo['id'] <NEW_LINE> event = task_opts.get('event') <NEW_LINE> volume = task_opts.get('volume') <NEW_LINE> if volume is not None: <NEW_LINE> <INDENT> volume = lookup_na... | Create a new repo entry in the INIT state, return full repo data | 625941cccc40096d61595a37 |
def cli(): <NEW_LINE> <INDENT> arguments = docopt(__doc__) <NEW_LINE> options = ''.join([ key for key, value in arguments.items() if value is True ]) <NEW_LINE> result = getSearchData(arguments) <NEW_LINE> available_trains = result['data'] <NEW_LINE> TrainsCollection(available_trains, options).pretty_print() | command-line interface | 625941ccf9cc0f698b1406e2 |
def GetCycleNumberFromScanNumber(self, scanNumber): <NEW_LINE> <INDENT> pbstrScanEvent = comtypes.automation.BSTR() <NEW_LINE> pnCycleNumber = c_long() <NEW_LINE> error = self.source.GetCycleNumberFromScanNumber( c_long(scanNumber), byref(pnCycleNumber)) <NEW_LINE> if error: <NEW_LINE> <INDENT> raise IOError("GetCycleN... | This function returns the cycle number for the scan specified by scanNumber from the scan
index structure in the raw file. | 625941cca79ad161976cc22c |
def __init__(self, config): <NEW_LINE> <INDENT> self._config = config <NEW_LINE> self._mon_client = None <NEW_LINE> self._api_version = '2_0' <NEW_LINE> self._failure_reason = None <NEW_LINE> self._log_interval_remaining = 1 <NEW_LINE> self._current_number_measurements = 0 <NEW_LINE> self._max_buffer_size = int(config[... | Initialize Mon api client connection. | 625941cc66656f66f7cbc291 |
def _get_valid_email_addrs(self, et, special=False, sort=False): <NEW_LINE> <INDENT> addrs = [(r['local_part'], r['domain']) for r in et.get_addresses(special=special)] <NEW_LINE> if sort: <NEW_LINE> <INDENT> addrs.sort(lambda x, y: cmp(x[1], y[1]) or cmp(x[0], y[0])) <NEW_LINE> <DEDENT> return ["%s@%s" % a for a in ad... | Return a list of all valid e-mail addresses for an EmailTarget.
Keep special domain names intact if special is True, otherwise re-write
them into real domain names. | 625941ccfb3f5b602dac377a |
def create_vradio(self, cf, bandwidth): <NEW_LINE> <INDENT> return _hydra_swig.hydra_source_sptr_create_vradio(self, cf, bandwidth) | create_vradio(hydra_source_sptr self, double cf, double bandwidth) -> size_t | 625941cc92d797404e304271 |
def _handle_flag_grasp_move(self): <NEW_LINE> <INDENT> if self.modify_grasps: <NEW_LINE> <INDENT> self.current_grasp.flag = not self.current_grasp.flag | Toggle the flag boolean for the current grasp. | 625941cc96565a6dacc8f7b2 |
def check_error(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return unicode(value) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return unicode('#N/A') | Tries to convert Error" else N/A | 625941cc596a897236089ba8 |
def test__get_port_autoneg_failed(self): <NEW_LINE> <INDENT> self.snmp_handler.get = mock.MagicMock(side_effect=[Exception]) <NEW_LINE> self.assertEqual(self.tested_instance._get_port_autoneg("port_index"), "False") | Failed to check state. Return status False | 625941cc0c0af96317bb82cf |
def cache(function, maxsize=300, expire=0): <NEW_LINE> <INDENT> cache_store = {} <NEW_LINE> state = { "enabled": True, "expire": expire, "maxsize": maxsize } <NEW_LINE> def clear_cache(): <NEW_LINE> <INDENT> cache_store.clear() <NEW_LINE> <DEDENT> def set_expire(new_expire): <NEW_LINE> <INDENT> state["expire"] = expire... | Decorator that generate cache wrapper and that adds cache feature to
target function. A max cache size and and expiration time (in seconds) can
be set too.
Args:
function (func): Decorated function:
maxsize: Number of value stored in cache (300 by default).
expire: Time to live in seconds of stored value (... | 625941cc925a0f43d2549f5e |
def create_update_sqlserver(self): <NEW_LINE> <INDENT> self.log("Creating / Updating the SQL Server instance {0}".format(self.name)) <NEW_LINE> try: <NEW_LINE> <INDENT> response = self.mgmt_client.servers.create_or_update(self.resource_group, self.name, self.parameters) <NEW_LINE> if isinstance(response, AzureOperation... | Creates or updates SQL Server with the specified configuration.
:return: deserialized SQL Server instance state dictionary | 625941cc7d847024c06be3a2 |
def shrink(self): <NEW_LINE> <INDENT> new_zoomlevel = self._zoomlevel / self.__class__.ZOOM_STEP <NEW_LINE> if (new_zoomlevel > self.__class__.ZOOM_MIN): <NEW_LINE> <INDENT> self._zoomlevel = new_zoomlevel <NEW_LINE> self._update_font() | Shrinks the font down to a defined minimum. | 625941cc7cff6e4e81117a6d |
def test_gap_peaks(self): <NEW_LINE> <INDENT> data = [1,1,1,1,0,0,1,1,1,1] <NEW_LINE> xvals = arange(len(data)) <NEW_LINE> fitter = Classic(xvals, data, max_width=20, min_width=1, max_gap=1) <NEW_LINE> starts_and_stops = fitter.peaks(False) <NEW_LINE> self.assertListEqual(starts_and_stops, [(0,4, 0), (6,10, 6)]) | Tests finding gaps between peaks | 625941cc30bbd722463cbead |
def followers(self, number=-1, etag=None): <NEW_LINE> <INDENT> url = self._build_url('followers', base_url=self._api) <NEW_LINE> return self._iter(int(number), url, User, etag=etag) | Iterate over the followers of this user.
:param int number: (optional), number of followers to return. Default:
-1 returns all available
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of :class:`User <User>`\ s | 625941cc656771135c3eb956 |
def taylor(self, inicial, final, n): <NEW_LINE> <INDENT> expr = "" <NEW_LINE> inicial = int(inicial) <NEW_LINE> final = int(final) <NEW_LINE> h = (final - inicial) / float(n) <NEW_LINE> x = self.px <NEW_LINE> py = self.pt <NEW_LINE> y = [] <NEW_LINE> y.append(self.solve(x[0])) <NEW_LINE> for i in range(0, int(n)) : <NE... | Resolvemos por metodo de taylor | 625941cc91af0d3eaac9bb00 |
def conv_backward_naive(dout, cache): <NEW_LINE> <INDENT> dx, dw, db = None, None, None <NEW_LINE> N, F, H_dout, W_dout = dout.shape <NEW_LINE> N, C, H, W = cache[0].shape <NEW_LINE> F, C, HH, WW = cache[1].shape <NEW_LINE> pad = cache[3]['pad'] <NEW_LINE> stride = cache[3]['stride'] <NEW_LINE> x = cache[0] <NEW_LINE> ... | A naive implementation of the backward pass for a convolutional layer.
Inputs:
- dout: Upstream derivatives.
- cache: A tuple of (x, w, b, conv_param) as in conv_forward_naive
Returns a tuple of:
- dx: Gradient with respect to x
- dw: Gradient with respect to w
- db: Gradient with respect to b | 625941ccd8ef3951e3243624 |
def test_combineTests_spotcheck(): <NEW_LINE> <INDENT> table = [[True, True],[False, True]] <NEW_LINE> result = combineTests.combineTests(table) <NEW_LINE> assert result[0][0:2] == [[[0]], [True, True]] <NEW_LINE> assert result[1][0:2] == [[[1]], [False, True]] <NEW_LINE> assert result[2][0:2] == [[[0], [1]], [True, Tr... | check if a particular example works out the way it should | 625941cc7d43ff24873a2d88 |
def __init__(self, clock, rect): <NEW_LINE> <INDENT> super(ClockGradient, self).__init__() <NEW_LINE> self.clock = clock <NEW_LINE> self.setSpread(QGradient.RepeatSpread) <NEW_LINE> self.setStart(rect.left(),0) <NEW_LINE> self.setFinalStop(rect.right(),0) <NEW_LINE> self.prepareClock() | Initialise the clocking gradient display.
inputs:
clock : object with clock.length and clock.waveform(x)
rect : bounding rect of object to display gradient | 625941cc0383005118ecf6ca |
def _init_mapping(self) -> NoReturn: <NEW_LINE> <INDENT> initial_value = 0 <NEW_LINE> if len(self.operand[0]) == len(self.answer[0]): <NEW_LINE> <INDENT> all_words = self.operand + self.answer <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> all_words = self.answer + self.operand <NEW_LINE> <DEDENT> for word in all_words:... | Menginisialisasi pemetaan awal antara huruf dengan angka dari 1 sampai 9. | 625941cc07d97122c4178972 |
def test_20_message_set_star(self): <NEW_LINE> <INDENT> cr, uid = self.cr, self.uid <NEW_LINE> msg_id = self.group_pigs.message_post(body='My Body', subject='1') <NEW_LINE> msg = self.mail_message.browse(cr, uid, msg_id) <NEW_LINE> msg_raoul = self.mail_message.browse(cr, self.user_raoul_id, msg_id) <NEW_LINE> self.mai... | Tests for starring messages and its related access rights | 625941ccd8ef3951e3243625 |
def nio(self): <NEW_LINE> <INDENT> return self._nio | Returns the NIO attached to this port.
:returns: NIO instance | 625941cccc40096d61595a38 |
def GetMode(messages, mode): <NEW_LINE> <INDENT> enum_class = messages.ManagedInstanceOverrideDiskOverride.ModeValueValuesEnum <NEW_LINE> if isinstance(mode, six.string_types): <NEW_LINE> <INDENT> return { 'ro': enum_class.READ_ONLY, 'rw': enum_class.READ_WRITE, }[mode] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret... | Returns mode message basing on short user friendly string. | 625941ccb5575c28eb68e0e7 |
def _loglik_subterm_2(self, uj, t_indices, T): <NEW_LINE> <INDENT> terms = [ self.A[self.u[i]][uj] * (1 - np.exp(- self.beta * (T - self.t[i])) + np.inner(self.m[i], self.m[t_indices[-1]])) for i in t_indices] <NEW_LINE> return np.array(terms) | subterm 2 in log-likelihood function | 625941ccb5575c28eb68e0e8 |
def _convert_to_os_map(self, os): <NEW_LINE> <INDENT> os_map = {} <NEW_LINE> for os_name in self.os: <NEW_LINE> <INDENT> os_map[os_name] = os_name == os <NEW_LINE> <DEDENT> return os_map | Converts an OS string to a map from os name -> bool
N.B. also adds an entry for None os, which makes it easier for
vectorizing and checking if an exploit will work (since exploits can
have os=None) | 625941cc379a373c97cfac2c |
def unset_jwt_cookies(response): <NEW_LINE> <INDENT> if not config.jwt_in_cookies: <NEW_LINE> <INDENT> raise RuntimeWarning("unset_refresh_cookies() called without " "'JWT_TOKEN_LOCATION' configured to use cookies") <NEW_LINE> <DEDENT> response.set_cookie(config.refresh_cookie_name, value='', expires=0, secure=config.c... | Takes a flask response object, and configures it to unset (delete) JWTs
stored in cookies.
:param response: The Flask response object to delete the JWT cookies in. | 625941cc2c8b7c6e89b358a8 |
def create_clf(self, model, X_train, X_test, y_train, y_test, parameters=None, description=None, version=1): <NEW_LINE> <INDENT> clf = model <NEW_LINE> if parameters is not None: <NEW_LINE> <INDENT> clf.set_params(**parameters) <NEW_LINE> <DEDENT> clf.fit(X_train, y_train) <NEW_LINE> clf_name = self.__create_name('clf_... | Creates a classifier based on given train and test data and parameters.
Saves clf and created description for it's results.
Args:
model -- sklearn model that shoud be trained.
X_train -- train objects set (vectors).
X_test -- test objects set (vectors).
y_train -- rubrics of X_train.
y_test --... | 625941cc31939e2706e4cf52 |
def querying_purchase_price(self): <NEW_LINE> <INDENT> purchase_prices = [] <NEW_LINE> for user in self.users: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> purchase_prices.append( [i for i in self.client.query(self.queries.get( 'purchase_price' ).format(user))][0].values()[2] ) <NEW_LINE> <DEDENT> except IndexError: <N... | This functions queries user most recent purchase price.
Returns
-------
purchase_prices : iterator
User most recent purchase price. | 625941cce1aae11d1e749d9e |
def downLoad(self): <NEW_LINE> <INDENT> import retrieval <NEW_LINE> if self.havePETSc: <NEW_LINE> <INDENT> isClone = self.petscclone.isClone <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> isClone = True <NEW_LINE> <DEDENT> retriever = retrieval.Retriever(self.sourceControl, argDB = self.argDB) <NEW_LINE> retriever.setup... | Downloads a package; using hg or ftp; opens it in the with-packages-build-dir directory | 625941ccaad79263cf390b28 |
def test_getlyrics_threaded(): <NEW_LINE> <INDENT> def source_1(_): <NEW_LINE> <INDENT> time.sleep(1) <NEW_LINE> return 'Lyrics 1' <NEW_LINE> <DEDENT> def source_2(_): <NEW_LINE> <INDENT> return 'Lyrics 2' <NEW_LINE> <DEDENT> def source_3(_): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> song = Song(artist='Slipkno... | Test the `get_lyrics_threaded()` function, which should launch a pool of
processes to search for lyrics in all the available sources, and return the
result from the first one that returns valid lyrics. | 625941cc07f4c71912b11569 |
def profile(request, username): <NEW_LINE> <INDENT> user = get_object_or_404(User, username=username) <NEW_LINE> return render_to_response("profiles/profile.html", { "profile_user": user, }, context_instance=RequestContext(request)) | Profile detail page | 625941cc99cbb53fe6792cce |
def get_synoptic_list(self): <NEW_LINE> <INDENT> syn_list = [] <NEW_LINE> default_is_none_synoptic = True <NEW_LINE> for k, v in self._synoptic_pvs.items(): <NEW_LINE> <INDENT> is_default = False <NEW_LINE> if bytes(f"<name>{k}</name>", encoding="utf-8") in self._default_syn_xml: <NEW_LINE> <INDENT> default_is_none_syn... | Gets the names and associated pvs of the synoptic files in the synoptics directory.
Returns:
list : Alphabetical list of synoptics files on the server, along with their associated pvs | 625941ccbe7bc26dc91cd6e8 |
def conditional(Xnew, X, kern, f, full_cov=False, q_sqrt=None, whiten=False): <NEW_LINE> <INDENT> num_data = tf.shape(X)[0] <NEW_LINE> Kmn = kern.K(X, Xnew) <NEW_LINE> Kmm = kern.K(X) + eye(num_data) * jitter_level <NEW_LINE> Lm = tf.cholesky(Kmm) <NEW_LINE> A = tf.matrix_triangular_solve(Lm, Kmn, lower=True) <NEW_LINE... | Given F, representing the GP at the points X, produce the mean and
(co-)variance of the GP at the points Xnew.
Additionally, there my be Gaussian uncertainty about F as represented by
q_sqrt. In this case `f` represents the mean of the distribution and
q_sqrt the square-root of the covariance.
Additionally, the GP ma... | 625941cc6e29344779a626f9 |
def test_limit_choices_to(self): <NEW_LINE> <INDENT> actor = Actor.objects.create(name="Palin", age=27) <NEW_LINE> Inquisition.objects.create(expected=True, leader=actor, country="England") <NEW_LINE> Inquisition.objects.create(expected=False, leader=actor, country="Spain") <NEW_LINE> response = self.client.get('/test_... | Regression test for 14880 | 625941cc15baa723493c405d |
def minimum(liste: list)-> str: <NEW_LINE> <INDENT> assert(type(l1)== list) <NEW_LINE> petit = l1[0] <NEW_LINE> for élément in liste: <NEW_LINE> <INDENT> if élément < petit: <NEW_LINE> <INDENT> petit = élément <NEW_LINE> <DEDENT> <DEDENT> if liste != []: <NEW_LINE> <INDENT> return petit <NEW_LINE> <DEDENT> else: <NEW_L... | Fonction qui renvoit l'élément le plus petit de la liste ('banane' < 'pastèque') | 625941cc82261d6c526ab586 |
def get_points_adjacent_cells(self, point_indices): <NEW_LINE> <INDENT> return self._instance.GetPointsAdjacentCells(point_indices) | Get adjacent cells common to a set of points.
Args:
point_indices: The indices of the points to find adjacent cells of
Returns:
List of cell indices of cells adjacent to point_indices | 625941cc4f88993c3716c14f |
def addDependency( self, rel, l_index, r_index): <NEW_LINE> <INDENT> assert int(r_index) == self.tokens[int(r_index)]['id'] and int(l_index) == self.tokens[int(l_index)]['id'] <NEW_LINE> self.tokens[int(r_index)]['head'] = int(l_index) <NEW_LINE> self.tokens[int(r_index)]['rel'] = rel | CoNLL dependency format | 625941cccc0a2c11143dcf78 |
def get_field_info(self, field): <NEW_LINE> <INDENT> field_info = OrderedDict() <NEW_LINE> field_info['type'] = self.label_lookup[field] <NEW_LINE> field_info['required'] = getattr(field, 'required', False) <NEW_LINE> attrs = [ 'read_only', 'label', 'help_text', 'min_length', 'max_length', 'min_value', 'max_value' ] <N... | Given an instance of a serializer field, return a dictionary
of metadata about it.
Differences comparing to original `get_field_info`:
* don't evaluate related field query (just provide url to this
particular resource) | 625941ccb545ff76a8913efe |
def read_dictionary(filepath): <NEW_LINE> <INDENT> with open(filepath, 'r') as dict_file: <NEW_LINE> <INDENT> return dict_file.read().splitlines() | Open dictionary file for reading and return its content
Args:
filepath (string): file path for the dictionary file
Returns:
list: list of strings containing the word list | 625941cc3617ad0b5ed67fdf |
def relativepath(path: str, start: Optional[str] = None) -> str: <NEW_LINE> <INDENT> import platform <NEW_LINE> if platform == 'Windows': <NEW_LINE> <INDENT> return path <NEW_LINE> <DEDENT> return os.path.relpath(path, start) | A cross-platform wrapper for `os.path.relpath()`, which returns `path` if
under Windows, otherwise returns the relative path of `path`.
This avoids problems under Windows when the current working directory is
on a different drive letter from `path`. | 625941cc099cdd3c635f0d42 |
@meta.rule(Parser, "Base.string") <NEW_LINE> def read_cstring(self) -> bool: <NEW_LINE> <INDENT> self._stream.save_context() <NEW_LINE> idx = self._stream.index <NEW_LINE> if self.read_char('\"') and self.read_until('\"', '\\'): <NEW_LINE> <INDENT> txt = self._stream[idx:self._stream.index] <NEW_LINE> res = Node(self._... | Read following BNF rule else return False
'"' -> ['/'| '"'] | 625941cc5f7d997b87174b7f |
def validate_num(ccnum): <NEW_LINE> <INDENT> ccnum = str(ccnum) <NEW_LINE> ccnum_double = ccnum[-2::-2] <NEW_LINE> ccnum_single = ccnum[-1::-2] <NEW_LINE> ccnum_double = "".join([str(int(x) * 2) for x in ccnum_double]) <NEW_LINE> mysum = sum(map(int, ccnum_double)) + sum(map(int, ccnum_single)) <NEW_LINE> if mysum % 10... | Apply the Luhn Algorithm against a card number to verify its validity
Returns True or False | 625941cc435de62698dfdd34 |
def __init__(self, email1=None, email2=None, facebook=None, id=None, phone1=None, phone2=None, phone3=None, skype=None): <NEW_LINE> <INDENT> self.swagger_types = { 'email1': 'str', 'email2': 'str', 'facebook': 'str', 'id': 'int', 'phone1': 'str', 'phone2': 'str', 'phone3': 'str', 'skype': 'str' } <NEW_LINE> self.attrib... | ContactInfoDTO - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | 625941cc21bff66bcd684a3b |
def __init__(self, x, y, w, h): <NEW_LINE> <INDENT> assert w > 0 <NEW_LINE> assert h > 0 <NEW_LINE> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.w = w <NEW_LINE> self.h = h | initialize | 625941cc0a366e3fb873e902 |
def save_answer(out_file, output): <NEW_LINE> <INDENT> with open(out_file, 'w') as f: <NEW_LINE> <INDENT> for item in output: <NEW_LINE> <INDENT> f.write("%s\n" % item) | Expects output to be list of Strings. Writes output to out_file. | 625941cca8370b7717052987 |
def get_column_formatters(df): <NEW_LINE> <INDENT> formatters = {} <NEW_LINE> for p in df.columns: <NEW_LINE> <INDENT> (a, b) = p <NEW_LINE> if b.endswith("Q"): <NEW_LINE> <INDENT> formatters[p] = lambda x: "%.2f" % x <NEW_LINE> <DEDENT> elif b.startswith("T_"): <NEW_LINE> <INDENT> formatters[p] = lambda x: "%.1f" % x ... | Get the formatters for a dataframe.
Parameters
----------
df : pandas dataframe
table
Returns
-------
dict
dictionary of formatters for columns. | 625941ccd164cc6175782e35 |
def update_avatar(self, token, image=None, **kwargs): <NEW_LINE> <INDENT> params = { 'token': token } <NEW_LINE> files = {'image': image} if image else None <NEW_LINE> return self._post('updateAvatar', params, files, **kwargs) | Update a registered Todoist user's avatar.
:param token: The user's login token.
:type token: str
:param image: The image file. The maximum size is 2mb.
:type image: fileIO[str]
:param delete: If ``1``, delete the current avatar and use the default.
:type delete: int
:return: The HTTP response to the request.
:rtype: ... | 625941cccdde0d52a9e5311b |
def scale_for_display(image): <NEW_LINE> <INDENT> out = image - image.min() <NEW_LINE> out = (out / out.max() * 256) <NEW_LINE> return out.astype(int) | Scales numpy array containing image data to be integers in range [0, 256] | 625941cc3539df3088e2e433 |
def get_all_products(self): <NEW_LINE> <INDENT> result = None <NEW_LINE> if self.pk: <NEW_LINE> <INDENT> result = Product.objects.filter(product_group_id=self.pk) <NEW_LINE> if result.count() == 0: <NEW_LINE> <INDENT> result = None <NEW_LINE> <DEDENT> <DEDENT> return result | returns a query set that contains all Products | 625941cc8c3a8732951584a2 |
def set_parameters(otype, M): <NEW_LINE> <INDENT> if otype == 1: <NEW_LINE> <INDENT> S0 = 36. <NEW_LINE> T = 1.0 <NEW_LINE> r = 0.06 <NEW_LINE> sigma = 0.2 <NEW_LINE> <DEDENT> elif otype == 2: <NEW_LINE> <INDENT> S0 = 100 <NEW_LINE> T = 1.0 <NEW_LINE> r = 0.05 <NEW_LINE> sigma = 0.5 <NEW_LINE> <DEDENT> else: <NEW_LINE>... | Sets parameters depending on valuation case.
Parameters
==========
otype: int
option type
1 = American put option
2 = Short Condor Spread | 625941ccf8510a7c17cf97e4 |
def build_pooled_gru(num_classes, vocab_size, max_seq_len, embedding_matrix, embedding_dims=300): <NEW_LINE> <INDENT> sequence_input = Input(shape=(max_seq_len,)) <NEW_LINE> x = Embedding(vocab_size, embedding_dims, weights=[embedding_matrix])(sequence_input) <NEW_LINE> x = SpatialDropout1D(0.25)(x) <NEW_LINE> x = Bidi... | Build a token encoder model for a classification task.
Args:
num_classes: int: number of classes for classification
vocab_size: int: vocab_size
max_seq_len: int: max number of features or token types considered
embedding_matrix: np.array: matrix of [word, word_vector]
embedding_dims: int: word vecto... | 625941ccbde94217f3682ed9 |
def test_get_root(self): <NEW_LINE> <INDENT> self.ihelper = ih.IrodsHelper() <NEW_LINE> self.assertNotEqual(self.ihelper, None) <NEW_LINE> root = self.ihelper.root() <NEW_LINE> self.assertNotEqual(root, None) <NEW_LINE> self.assertEqual(type(root), str) | Get the root directory from the helper | 625941cc6e29344779a626fa |
def __len__ (self) : <NEW_LINE> <INDENT> return len(self.params) | Return the number of parameters, aka the arity of the action.
>>> len(Action('a', True, [Value(1), Variable('x')]))
2
@return: the arity of the action
@rtype: non negative `int` | 625941cc099cdd3c635f0d43 |
def add_common_args(parser): <NEW_LINE> <INDENT> parser.add_argument( '--version', action='version', version='%(prog)s {version}'.format( version=__version__ ) ) <NEW_LINE> parser.add_argument( "-v", "--verbose", action="store_true", dest="verbose", help="Increase output verbosity" ) <NEW_LINE> parser.add_argument( "-d... | Add the common args to a parser: version, verbose, debug | 625941cc6fece00bbac2d826 |
def show_env(): <NEW_LINE> <INDENT> print("Available environment variables: \n") <NEW_LINE> table = PrettyTable() <NEW_LINE> table.field_names = ["ENV", "DEFAULT", ""] <NEW_LINE> table.align = 'l' <NEW_LINE> for step in app.steps: <NEW_LINE> <INDENT> for x in step.additional_input: <NEW_LINE> <INDENT> default = colored... | Shows environment variables from post deploy actions
| 625941cc73bcbd0ca4b2c15e |
def validate(self, cube): <NEW_LINE> <INDENT> issues = [] <NEW_LINE> tables = set() <NEW_LINE> aliases = set() <NEW_LINE> alias_map = {} <NEW_LINE> for join in cube.joins: <NEW_LINE> <INDENT> self.logger.debug("join: %s" % (join, )) <NEW_LINE> if not join.master.column: <NEW_LINE> <INDENT> issues.append(("join", "maste... | Validate physical representation of model. Returns a list of
dictionaries with keys: ``type``, ``issue``, ``object``.
Types might be: ``join`` or ``attribute``.
The ``join`` issues are:
* ``no_table`` - there is no table for join
* ``duplicity`` - either table or alias is specified more than once
The ``attribute`` ... | 625941ccbe8e80087fb20d2b |
def reply_contact( self, phone_number: str = None, first_name: str = None, last_name: str = None, disable_notification: DVInput[bool] = DEFAULT_NONE, reply_to_message_id: int = None, reply_markup: ReplyMarkup = None, timeout: ODVInput[float] = DEFAULT_NONE, contact: Contact = None, vcard: str = None, api_kwargs: JSONDi... | Shortcut for::
bot.send_contact(update.effective_message.chat_id, *args, **kwargs)
For the documentation of the arguments, please see :meth:`telegram.Bot.send_contact`.
Args:
quote (:obj:`bool`, optional): If set to :obj:`True`, the contact is sent as an actual
reply to this message. If ``reply_to_me... | 625941cc4527f215b584c53f |
def retrieve_elections_by_election_date(self, election_day_text='', include_test_election=False, read_only=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if positive_value_exists(read_only): <NEW_LINE> <INDENT> election_list_query = Election.objects.using('readonly').all() <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND... | Retrieve elections using election_day_text
:param election_day_text:
:param include_test_election:
:param read_only:
:return: | 625941cc3c8af77a43ae3888 |
def loss(self, X, y=None): <NEW_LINE> <INDENT> W1, b1 = self.params['W1'], self.params['b1'] <NEW_LINE> W2, b2 = self.params['W2'], self.params['b2'] <NEW_LINE> W3, b3 = self.params['W3'], self.params['b3'] <NEW_LINE> filter_size = W1.shape[2] <NEW_LINE> conv_param = {'stride': 1, 'pad': (filter_size - 1) / 2} <NEW_LIN... | Evaluate loss and gradient for the three-layer convolutional network.
Input / output: Same API as TwoLayerNet in fc_net.py. | 625941ccfff4ab517eb2f524 |
@app.route('/') <NEW_LINE> @app.route('/index') <NEW_LINE> def home(): <NEW_LINE> <INDENT> return render_template('index.html', title='DB Viewer', year=datetime.now().year,) | Renders the home page. | 625941cc236d856c2ad448c2 |
def to_distances(self, x): <NEW_LINE> <INDENT> if len(x.shape) != 2: <NEW_LINE> <INDENT> raise ValueError('observation data must be a 2-dimensional array') <NEW_LINE> <DEDENT> m, n = x.shape <NEW_LINE> if n != self.landmarks.shape[1]: <NEW_LINE> <INDENT> raise ValueError('training data had %s features but you provided ... | x: a set of (original) features to convert to similarity features
return value: the converted feature values of x ready to use for
cost or prediction functions | 625941ccde87d2750b85fe7b |
def __init__(self, is_training, first_stage_features_stride=16, batch_norm_trainable=False, weight_decay=0.0): <NEW_LINE> <INDENT> super(FasterRCNNResnet152KerasFeatureExtractor, self).__init__( is_training=is_training, resnet_v1_base_model=resnet_v1.resnet_v1_152, resnet_v1_base_model_name='resnet_v1_152', first_stage... | Constructor.
Args:
is_training: See base class.
first_stage_features_stride: See base class.
batch_norm_trainable: See base class.
weight_decay: See base class. | 625941cc187af65679ca5207 |
def __parse_scenario(self, line): <NEW_LINE> <INDENT> if REGEX_TAGS.match(line): <NEW_LINE> <INDENT> self.__state = STATE_SCENARIO_TAGS <NEW_LINE> self.__tags = [line, ] <NEW_LINE> return <NEW_LINE> <DEDENT> if REGEX_SCENARIO_START.match(line): <NEW_LINE> <INDENT> self.scenarios.append([]) <NEW_LINE> <DEDENT> if REGEX_... | Add the body of the current scenario up till the next scenario starts.
We take care to notice multiline texts since those might have Feature/Scenario sections
in them that might confuse the parser. | 625941cccad5886f8bd270c1 |
def __init__(self): <NEW_LINE> <INDENT> self._version = 'use-outside-compilation' <NEW_LINE> self._device_type = None <NEW_LINE> TensorTracer.validate_flag_names() <NEW_LINE> found, self._trace_mode = TensorTracer.get_flag_value(_FLAG_NAME_TRACE_MODE) <NEW_LINE> if not found or not self._trace_mode: <NEW_LINE> <INDENT>... | Initializes a TensorTracer.
Sets the various member fields from the flags (if given) or the defaults. | 625941cc3eb6a72ae02ec5c5 |
def compute_distances_no_loops(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> M = np.dot(X,self.X_train.T) <NEW_LINE> nrow = M.shape[0] <NEW_LINE> ncol = M.shape[1] <NEW_LINE> tr = np.diag(np.dot(self.X_train... | Compute the distance between each test point in X and each training point
in self.X_train using no explicit loops.
Input / Output: Same as compute_distances_two_loops | 625941cc796e427e537b06ae |
def find_col_from_list(self, label_list, case_sensitive=False): <NEW_LINE> <INDENT> if not case_sensitive: <NEW_LINE> <INDENT> search_list = [item.lower() for item in label_list] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> search_list = label_list <NEW_LINE> <DEDENT> for key, col_ind in self.col_attr_dict.iteritems()... | search through self.col_attr_dict to find a key in
label_list. When a key is found that is in label_list, return
the corresponding column index. If case_sensitive is False,
use .lower() on the keys and the labels. | 625941cc091ae35668667046 |
def connect( self, **connectargs ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for key in connectargs: <NEW_LINE> <INDENT> vars( self )[ key ] = connectargs[ key ] <NEW_LINE> <DEDENT> self.home = self.options[ 'home' ] if 'home' in self.options.keys() else "~/mininet" <NEW_LINE> self.name = self.options[ 'name' ] <NE... | Here the main is the TestON instance after creating
all the log handles. | 625941cc4e4d5625662d44c0 |
def show_observatories(args, out): <NEW_LINE> <INDENT> sitelist = ui.find_observatories(host=args.server, match=args.match) <NEW_LINE> print("\n".join(sitelist), file=out) | Worker for the --show-observatories option
Parameters
----------
args : `argparse.Namespace`
the parsed command-line options.
out : `file`
the open file object to write to.
Returns
-------
exitcode : `int` or `None`
the return value of the action or `None` to indicate success. | 625941cc0a50d4780f666f7a |
def create_test_execution_result( test_cycle_key: str, test_case_key: str, execution_status: str, *, test_script_results: List[Dict[str, str]] = None, actual_end_date: str = None, environment_name: str = None, execution_time: int = None, executed_by_id: str = None, assigned_to_id: str = None, comment: str = None, ) -> ... | Creates test result for particular test case in test run
:param test_cycle_key: Key of TM4J test cycle to put test execution to
:type test_cycle_key: str
:param test_case_key: Key of test case the execution applies to
:type test_case_key: str
:param execution_status: Name of the Test Execution Status
:type execution... | 625941cc1d351010ab855c04 |
def escape_entities(text): <NEW_LINE> <INDENT> return escape(text, {'"': '"'}) if text else text | Convert all XML entities
@param text: a string containing entities possibly
@type text: str
@return: converted version of text
@rtype: str | 625941cc851cf427c661a5f7 |
def test_configure_quotas(self, os_api_conn): <NEW_LINE> <INDENT> expect_quotas = {'instances': 12, 'cores': 10, 'ram': 128} <NEW_LINE> os_api_conn.set_compute_quotas(tenant, **expect_quotas) <NEW_LINE> actual_quotas = os_api_conn.get_compute_quotas(tenant) <NEW_LINE> for expect_quota in expect_quotas: <NEW_LINE> <INDE... | Configure tenant quotas and verify it works properly.
Args:
os_api_conn (openstack.connection.Connection): An authorized API
connection to the 'default' cloud on the OpenStack
infrastructure. | 625941cc7cff6e4e81117a6e |
def set_option(self, key, value=True): <NEW_LINE> <INDENT> if key not in Instrumentation.KNOWN_OPTIONS: <NEW_LINE> <INDENT> raise Exception('Unknown option `%s`' % key) <NEW_LINE> <DEDENT> self.options[key] = value | Sets one of the options used later one by the instrumentation. The available
options are listed in `KNOWN_OPTIONS`.
:param key: The name of the option to set.
:param value: The value of the option. Defaults to ``True``. | 625941cccad5886f8bd270c2 |
def log_info(message): <NEW_LINE> <INDENT> _INSTANCE.metadata.log("info", message) | Log a message. | 625941cc2c8b7c6e89b358a9 |
def addEdge(self, fromMe, to): <NEW_LINE> <INDENT> self.graph[fromMe].append(to) | add a directed edge to self | 625941cc8e71fb1e9831d891 |
def get_referred(self): <NEW_LINE> <INDENT> pass | Derivation for ProtocolTransition::/referred
.. ocl::
result = (trigger->collect(event)->select(oclIsKindOf(CallEvent))->collect(oclAsType(CallEvent).operation)->asSet()) | 625941cc5fdd1c0f98dc031b |
def fahrenheit_to_kelvin(temperature): <NEW_LINE> <INDENT> return (5.0 / 9.0) * (temperature - 32) + 273.15 | Convert from Fahrenheit to Kelvin
:param temperature: degree understood to be in Fahrenheit
NOTE:
Fahrenheit to Kelvin formula: K = 5/9(°F - 32) + 273.15
Subtract by 32, multiply by 5/9, then add 273.15. | 625941cc50485f2cf553ce82 |
def save_to_storage(self, image, filename, req): <NEW_LINE> <INDENT> storage.upload_fileobj(BytesIO(image), filename) | Send binary file to storage. | 625941cc3617ad0b5ed67fe0 |
def get_partner(self): <NEW_LINE> <INDENT> return self.partner | Overrides Voucher.get_partner | 625941cc55399d3f0558879c |
def test_basic(self): <NEW_LINE> <INDENT> field = data_form.Field(var='test') <NEW_LINE> self.assertEqual('text-single', field.fieldType) <NEW_LINE> self.assertEqual('test', field.var) | Test basic field initialization. | 625941cc3cc13d1c6d3c7463 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.