code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def myPow(self, x, n): <NEW_LINE> <INDENT> print(x **(n)) | :type x: float
:type n: int
:rtype: float | 625941d12eb69b55b151ca3a |
@testing.requires_testing_data <NEW_LINE> def test_spatial_inter_hemi_adjacency(): <NEW_LINE> <INDENT> conn = spatial_inter_hemi_adjacency(fname_src_3, 5e-6) <NEW_LINE> assert_equal(conn.data.size, 0) <NEW_LINE> conn = spatial_inter_hemi_adjacency(fname_src_3, 5e6) <NEW_LINE> assert_equal(conn.data.size, np.prod(conn.s... | Test spatial adjacency between hemispheres. | 625941d1379a373c97cfaccf |
def get_user_from_data(self, post_data): <NEW_LINE> <INDENT> form = RegistrationForm(post_data) <NEW_LINE> self.assertTrue(form.is_valid(), msg=(post_data, form.errors)) <NEW_LINE> user = form.save(commit=True) <NEW_LINE> self.assertIsNotNone(user) <NEW_LINE> return user | Checks if form is correct and returns
user instance by calling form.save() | 625941d1a8ecb033257d3257 |
def test_get_scientific_names_ex2(self): <NEW_LINE> <INDENT> result = phylotastic_services.get_scientific_names(["domestic cattle","blue whale"], source="ITIS") <NEW_LINE> result_list = json.loads(result)['result'] <NEW_LINE> for result in result_list: <NEW_LINE> <INDENT> if result['searched_name'] == "domestic cattle"... | Testing Example 2 (ITIS): Getting scientific names of a list of species from their common names (vernacular names) | 625941d1ff9c53063f47c37e |
def plotData(data): <NEW_LINE> <INDENT> plt.figure() <NEW_LINE> plt.plot(data[:, 0], data[:, 1], 'rx', markersize=5, label='Тренировочные данные') <NEW_LINE> plt.legend(loc='upper right', shadow=True, fontsize=12, numpoints=1) <NEW_LINE> plt.xlabel('Численность населения в 10,000') <NEW_LINE> plt.ylabel('Прибыль в $100... | Функция позволяет выполнить визуализацию данных в декартовой
системе координат с подписанным осями (численность населения
и прибыль) | 625941d1379a373c97cfacd0 |
def toggle_password_visibility(self) -> None: <NEW_LINE> <INDENT> if self.show_password_button["text"] == "Show": <NEW_LINE> <INDENT> self.show_password_button.config(text="Hide") <NEW_LINE> self.password_entry.config(show="") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.show_password_button.config(text="Show") <... | Toggle whether to show or hide the password depending on the button's text.
:return: None. | 625941d132920d7e50b2835b |
def __init__(self, bid_price=None, offer_price=None, spread=None, top_bid=None, top_offer=None, trade_count=None): <NEW_LINE> <INDENT> self.swagger_types = { 'bid_price': 'float', 'offer_price': 'float', 'spread': 'float', 'top_bid': 'BookOrder', 'top_offer': 'BookOrder', 'trade_count': 'int' } <NEW_LINE> self.attribut... | Statistics - 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. | 625941d1711fe17d825424f5 |
def getSampledVersion(self, samplingFold= 1.0): <NEW_LINE> <INDENT> sampled_seqL= None if isinstance(self.pairsDf_seqL, type(None)) else self._sample_oneDf(self.pairsDf_seqL, samplingFold) <NEW_LINE> sampled_seqR= None if isinstance(self.pairsDf_seqR, type(None)) else self._sample_oneDf(self.pairsDf_seqR, samplingFold)... | return a sampled version of self. Thus, sampled version will have just n= num_posPairs*(1+ samplingFold)
pairs: all the positive pairs and num_posPairs*(samplingFold) randomly selected negative pairs.
:param samplingFold: Float. Number of times the number of negative sampled pairs is bigger than positive pairs.
... | 625941d131939e2706e4cff4 |
def less(self, data): <NEW_LINE> <INDENT> if not self.sumCorrect: <NEW_LINE> <INDENT> self.partialSum() <NEW_LINE> <DEDENT> curr = self.head <NEW_LINE> for i in xrange(self.maxLevel-1, -1, -1): <NEW_LINE> <INDENT> while curr.forward[i].data < data: <NEW_LINE> <INDENT> curr = curr.forward[i] <NEW_LINE> <DEDENT> <DEDENT>... | return the count of elements that is less than data
based on search() | 625941d1956e5f7376d70ff7 |
def setup_loss(self): <NEW_LINE> <INDENT> with vs.variable_scope("loss"): <NEW_LINE> <INDENT> l1 = tf.nn.softmax_cross_entropy_with_logits(self.a_s, self.start_answer) <NEW_LINE> l2 = tf.nn.softmax_cross_entropy_with_logits(self.a_e, self.end_answer) <NEW_LINE> self.loss = tf.reduce_mean(l1+l2) | Set up your loss computation here
:return: | 625941d14d74a7450ccd434e |
def dispose(self, isEnd=1): <NEW_LINE> <INDENT> if isEnd == 1: <NEW_LINE> <INDENT> self.end('commit') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.end('rollback') <NEW_LINE> <DEDENT> self._cursor.close() <NEW_LINE> self._conn.close() | @summary: 释放连接池资源 | 625941d1c432627299f04dd1 |
def MessageString(message): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return message.split(DELIMITER)[1] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return message | Will return the message without the message type and the delimiter | 625941d130bbd722463cbf51 |
def t_ASSIGN_MULT(t): <NEW_LINE> <INDENT> return t | \*\= | 625941d17d43ff24873a2e2b |
def _get_tree_root(self): <NEW_LINE> <INDENT> d = _cal_freq(self.long_str) <NEW_LINE> return _build_tree( [Node(ch=ch, fq=int(fq)) for ch, fq in d.items()]) | Set and get root node of the nodes | 625941d192d797404e304315 |
def remover_tudo_clicado(self, widget): <NEW_LINE> <INDENT> if self._confirmacao.run() == -5: <NEW_LINE> <INDENT> self._liststore.clear() <NEW_LINE> self._selecao = self._treeview.get_selection() <NEW_LINE> delete_all_dados() <NEW_LINE> <DEDENT> self._confirmacao.hide() | Método que limpa todos os dados do banco de dados quando remover_tudo
for precionado. | 625941d138b623060ff0af78 |
def remove(self, *args): <NEW_LINE> <INDENT> return _fife.MapList_remove(self, *args) | remove(MapList self, Map x) | 625941d14c3428357757c4b2 |
def fibo(n): <NEW_LINE> <INDENT> while len(f) < n + 1: <NEW_LINE> <INDENT> f.append(tailsum(f)) <NEW_LINE> <DEDENT> return f[n] | Calculates the n-th Fibonacci number without recursion. | 625941d19b70327d1c4e0f60 |
def create_space(self, name): <NEW_LINE> <INDENT> return self._maas(self.profile, 'spaces', 'create', 'name=' + name) | Create a new space with given name. | 625941d173bcbd0ca4b2c201 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, SmbSettingsGlobalSettings): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941d1498bea3a759b9c3a |
def reorderList(self, head): <NEW_LINE> <INDENT> self.reorder(head) | :type head: ListNode
:rtype: void Do not return anything, modify head in-place instead. | 625941d1cad5886f8bd27164 |
def __init__(self, finished): <NEW_LINE> <INDENT> self.finished = finished <NEW_LINE> self._data = [] <NEW_LINE> self.logger = logging.getLogger() | @param finished: deferred fired when protocol is finishing
@type finished: Deferred | 625941d13539df3088e2e4d6 |
def build_t_dataset(corpus_file, mincount): <NEW_LINE> <INDENT> with open(corpus_file) as f: <NEW_LINE> <INDENT> words = f.read().split() <NEW_LINE> <DEDENT> count = Counter(words) <NEW_LINE> unique_size = len(count) <NEW_LINE> word_id = {} <NEW_LINE> freq = {} <NEW_LINE> for word in count: <NEW_LINE> <INDENT> if count... | Process raw text into a dataset.
The universal embedding: [entities, words].
So the start index of words is ent_eize. | 625941d130c21e258bdfa629 |
def do_SCN(self) -> None: <NEW_LINE> <INDENT> if self.scs: <NEW_LINE> <INDENT> n = self.scs.ncomponents <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if settings.STRICT: <NEW_LINE> <INDENT> raise PDFInterpreterError("No colorspace specified!") <NEW_LINE> <DEDENT> n = 1 <NEW_LINE> <DEDENT> self.graphicstate.scolor = cas... | Set color for stroking operations. | 625941d163d6d428bbe4467a |
def test_sign_up_password_confirmation(self): <NEW_LINE> <INDENT> sign_up_credentials = { 'username': 'vince2', "email": "vincenthokiee@gmail.com", "password": "123", "password2": "1233"} <NEW_LINE> with app.test_client() as client: <NEW_LINE> <INDENT> res = self.sign_up(client, sign_up_credentials) <NEW_LINE> self.ass... | Test API can notice incorrect password
confirmation (POST request) | 625941d18e71fb1e9831d934 |
def __init__(self, temperature=5.0, **kwargs): <NEW_LINE> <INDENT> super(DiscreteVAE, self).__init__(**kwargs) <NEW_LINE> self.posterior = DiscretePosterior( state_size=kwargs['posterior_state_size']*self.history_size, action_size=kwargs['posterior_action_size'], latent_size=kwargs['posterior_latent_size']+kwargs['post... | state_size: State size
latent_size: Size of 'c' variable
goal_size: Number of goals.
output_size: | 625941d1377c676e91272334 |
def add_key(self, key): <NEW_LINE> <INDENT> if self.keys: <NEW_LINE> <INDENT> self.keys += ',' + key <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.keys = key <NEW_LINE> <DEDENT> self.save() | Add a new public key of this user. | 625941d1cc40096d61595adb |
def get_X(self): <NEW_LINE> <INDENT> return super(ICoordinateDialog, self).get_X() | Method ICoordinateDialog.get_X
OUTPUT
val : double* | 625941d1956e5f7376d70ff8 |
def _on_mousewheel(self, event): <NEW_LINE> <INDENT> if self.frame.winfo_height() > 800: <NEW_LINE> <INDENT> self.canvas.yview_scroll(-1*(event.delta/120), "units") | mouse wheel event | 625941d123e79379d52ee6ee |
def write_es(self, timestamp): <NEW_LINE> <INDENT> if timestamp is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> ts = self.context.datetime_to_secs(self.pmfg_ts(), PM_TIME_MSEC) <NEW_LINE> try: <NEW_LINE> <INDENT> body = {'ignore': 400, 'mappings': {'pcp-metric': {'properties':{'@timestamp':{'type':'epoch_milli'... | Write (send) metrics to Elasticsearch host | 625941d17b25080760e395e4 |
def on_serial_changed(self, event): <NEW_LINE> <INDENT> serial = self.serial.GetValue() <NEW_LINE> if len(serial) in [16, 40]: <NEW_LINE> <INDENT> self.button.Enable() <NEW_LINE> self.config.set("General", "Serial", self.serial.GetValue()) <NEW_LINE> self.config.write(open(CONFIG, "w")) <NEW_LINE> <DEDENT> else: <NEW_L... | The serial number has changed. If it is the correct number of
characters then enable the decrypt button, otherwise disable it
until a valid serial is entered. | 625941d18e7ae83300e4b158 |
def testLbSelectPoolAction(self): <NEW_LINE> <INDENT> pass | Test LbSelectPoolAction | 625941d11f5feb6acb0c4cdb |
def _install_app(self, device_name: str): <NEW_LINE> <INDENT> _app: AppDevice = self.device_services.get_device_app(device_name) <NEW_LINE> _apks = self.para['android_apk'].split(',') <NEW_LINE> for _apk in _apks: <NEW_LINE> <INDENT> if _apk == '': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> _path = os.path.abspat... | 安装APP
@param {str} device_name - 要安装到的设备号 | 625941d1e64d504609d749cb |
def bft(self): <NEW_LINE> <INDENT> self.nodelist = [] <NEW_LINE> if self.root is not None: <NEW_LINE> <INDENT> queue = [self.root] <NEW_LINE> while queue: <NEW_LINE> <INDENT> node = queue.pop(0) <NEW_LINE> if node.lnode is not None: <NEW_LINE> <INDENT> queue.append(node.lnode) <NEW_LINE> <DEDENT> if node.rnode is not N... | Breadth-first traversal on the tree (starting
from root note!) | 625941d1097d151d1a222fe4 |
def _getverifymask(self): <NEW_LINE> <INDENT> return numpy.full(self.shape, True, dtype=bool) | A numpy array with all entries being `True` of the same
shape as the values handled by the respective parameter. All entries
beeing `True` indicates that the method :func:`~MultiParameter.verify`
checks all entries of the numpy array storing the parameter values.
Overwrite :func:`~MultiParameter.verify` for :class:`Mu... | 625941d1bd1bec0571d907bb |
def hessian_scale3d(x, sigma): <NEW_LINE> <INDENT> hessian = np.empty((x.ndim, x.ndim) + x.shape, dtype=x.dtype) <NEW_LINE> for i in np.arange(x.ndim): <NEW_LINE> <INDENT> for j in np.arange(x.ndim-1, i-1, -1): <NEW_LINE> <INDENT> z_order = int(i==0) + int(j==0) <NEW_LINE> y_order = int(i==1) + int(j==1) <NEW_LINE> x_o... | Calculate the hessian matrix with derivative of Gaussian kernel convolutions
Parameters:
- x : ndarray
- sigma : scale, standard deviation of Gaussian kernel
Returns:
an array of shape (x.ndim, x.ndim) + x.shape
where the array[i, j, ...] corresponds to the second derivative x_ij | 625941d1cdde0d52a9e531bf |
def heap_sort(array): <NEW_LINE> <INDENT> def max_heap(array): <NEW_LINE> <INDENT> n = len(array) <NEW_LINE> for i in range(int(n/2)-1,-1,-1): <NEW_LINE> <INDENT> array[:] = heapify(array, i) <NEW_LINE> <DEDENT> return array <NEW_LINE> <DEDENT> def heapify(array, index): <NEW_LINE> <INDENT> n = len(array) <NEW_LINE> ri... | Input : list of values
Note:
Builds a max heap of given array. Then swaps first element (which is largest) of the array with the last, and heapifys
w.r.t new first element (array excluding the last element). It reapeats this procedure till array is sorted.
Returns : sorted list of values | 625941d1a17c0f6771cbe1db |
def test_mklost_and_found(vm, params): <NEW_LINE> <INDENT> add_ref = params.get("gf_add_ref", "disk") <NEW_LINE> readonly = "yes" == params.get("gf_add_readonly") <NEW_LINE> gf = utils_test.libguestfs.GuestfishTools(params) <NEW_LINE> if add_ref == "disk": <NEW_LINE> <INDENT> image_path = params.get("image_path") <NEW_... | Test command mklost_and_found | 625941d171ff763f4b549818 |
def attempt_sequence_sorting(seq): <NEW_LINE> <INDENT> end_sort = len(seq) - 2 <NEW_LINE> i = 0 <NEW_LINE> while i < end_sort: <NEW_LINE> <INDENT> if seq[i] > seq[i + 1]: <NEW_LINE> <INDENT> tmp = seq[i] <NEW_LINE> seq[i] = seq[i + 1] <NEW_LINE> seq[i + 1] = seq[i + 2] <NEW_LINE> seq[i + 2] = tmp <NEW_LINE> if i > 0: <... | Return True if the sequence can be sorted, False otherwise
It also sorts seq, but if this is not possible, the last two elements
may remain unsorted | 625941d144b2445a33932220 |
def testTrendingTrendingEntrySupportArticle(self): <NEW_LINE> <INDENT> pass | Test TrendingTrendingEntrySupportArticle | 625941d107f4c71912b1160e |
def dowload_invoice_with_http_info(self, invoice_number, **kwargs): <NEW_LINE> <INDENT> all_params = ['invoice_number'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_... | Download invoice # noqa: E501
Download invoice # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.dowload_invoice_with_http_info(invoice_number, async_req=True)
>>> result = thread.get()
:param async_req bool
:param... | 625941d167a9b606de4a8045 |
def test_get_collections_invalid_limit(client): <NEW_LINE> <INDENT> response = client.simulate_get("/collections", query_string="limit=101") <NEW_LINE> assert response.status_code == 400 | Test requesting 100 collections with an invalid limit parameter. | 625941d1097d151d1a222fe5 |
def step(self, grad_scale = 1, lr_scale = 1): <NEW_LINE> <INDENT> if 'global_step' not in self.state: <NEW_LINE> <INDENT> self.state['global_step'] = 0 <NEW_LINE> <DEDENT> for group in self.param_groups: <NEW_LINE> <INDENT> lr_sch = self.get_group_lr_sch(group, self.state['global_step']) <NEW_LINE> if group['rank'] == ... | Performs a single optimization step.
Arguments:
grad_scale: divid grad by grad_scale
lr_scale: scale learning rate by bs_scale | 625941d1435de62698dfddd9 |
def delete_workspace(repo_folder_1, repo_folder_2): <NEW_LINE> <INDENT> time.sleep(5) <NEW_LINE> if os.path.exists(repo_folder_1): <NEW_LINE> <INDENT> shutil.rmtree(repo_folder_1, onerror=rmtree_onerror) <NEW_LINE> <DEDENT> if os.path.exists(repo_folder_2): <NEW_LINE> <INDENT> shutil.rmtree(repo_folder_2, onerror=rmtre... | Deletes folders used to clone repositories | 625941d18c3a873295158547 |
def test_user_CRUD(self): <NEW_LINE> <INDENT> user_name = 'test2user' <NEW_LINE> user_password = 'test-user-password' <NEW_LINE> user_email = 'test@test-email.com' <NEW_LINE> user_email2 = 'changed@test-user-email.com' <NEW_LINE> self.auth_tool.manage_addUser(name=user_name, password=user_password, confirm=user_passwor... | Create, Read, Update and Delete a User | 625941d19c8ee82313fbb901 |
def run(self, iterations): <NEW_LINE> <INDENT> for i in range(iterations): <NEW_LINE> <INDENT> self.step() | Run several iterations of the morphological snakes method. | 625941d1d486a94d0b98e2d1 |
def create_global_frame(): <NEW_LINE> <INDENT> env = Frame(None) <NEW_LINE> env.define('eval', PrimitiveProcedure(scheme_eval, True, 'eval')) <NEW_LINE> env.define('apply', PrimitiveProcedure(scheme_apply, True, 'apply')) <NEW_LINE> env.define('load', PrimitiveProcedure(scheme_load, True, 'load')) <NEW_LINE> env.define... | Initialize and return a single-frame environment with built-in names. | 625941d138b623060ff0af79 |
def test_team_can_speak(self): <NEW_LINE> <INDENT> t = Team.objects.get(name="ucla") <NEW_LINE> u = Team.objects.get(name="Anaheim") <NEW_LINE> v = Team.objects.get(name="Irvine") <NEW_LINE> w = Team.objects.get(name="LB") <NEW_LINE> x = Team.objects.get(name="BFA") <NEW_LINE> self.assertEqual("CAMPUS", t.type) <NEW_LI... | Team objects that can speak are correctly identified | 625941d1236d856c2ad44967 |
def initSecret(): <NEW_LINE> <INDENT> secret = os.environ['APP_SECRET'] <NEW_LINE> if getattr(sys, 'frozen', False): <NEW_LINE> <INDENT> secret = os.path.join(sys._MEIPASS, 'secret.py') <NEW_LINE> <DEDENT> if not os.path.exists(secret): <NEW_LINE> <INDENT> import uuid <NEW_LINE> with open(secret, 'w') as f: <NEW_LINE> ... | initializes the database secret file and creates a secret token used to encrypt database information
Returns: None | 625941d1287bf620b61d3bee |
def set_up_matching_url(self, url, expected_message='A message'): <NEW_LINE> <INDENT> blacklist = Mock() <NEW_LINE> if expected_message != self.DEFAULT_MESSAGE: <NEW_LINE> <INDENT> self.tested_instance._msg_map[blacklist] = expected_message <NEW_LINE> <DEDENT> first = Mock() <NEW_LINE> first.address = url <NEW_LINE> fi... | Prepare a URL to be recognized as spam during tests.
:param url: a URL value expected to be recognized by
tested instance
:param expected_message: a message to be associated with
the result of validating the URL | 625941d1d4950a0f3b08c4da |
def absdiff(self, old, new): <NEW_LINE> <INDENT> return cv2.absdiff(old, new) | Returns an absolute difference tbween two frames. | 625941d1d18da76e23532662 |
def g_numeric(self, **kwargs): <NEW_LINE> <INDENT> pass | Custom gcall functions. Modify equations directly. | 625941d1a934411ee375181f |
def casefold(self, in_str): <NEW_LINE> <INDENT> folded = in_str.translate(self._lower_trans) <NEW_LINE> return folded | Casefold the given string, with the current server's casemapping. | 625941d182261d6c526ab62c |
def supported_types(self): <NEW_LINE> <INDENT> return [int,float] | Supported types for this access class | 625941d18e05c05ec3eea501 |
def tree_to_tfexample( root, example = None): <NEW_LINE> <INDENT> if example is None: <NEW_LINE> <INDENT> example = tf.train.Example() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for field_name in get_all_attrs(N_FIELDS): <NEW_LINE> <INDENT> example_utils.del_feat(example, getattr(N_FIELDS, field_name)) <NEW_LINE> <D... | Convert a tree of AnyNodes to a tf.Example.
Args:
root: AnyNode that represents the root of the tree.
example: tf.Example to which to add the view hierarchy information.
Returns:
The tf.Example created. | 625941d15f7d997b87174c24 |
def __init__(self): <NEW_LINE> <INDENT> self.BestFrameBase64 = None <NEW_LINE> self.Sim = None <NEW_LINE> self.Result = None <NEW_LINE> self.Description = None <NEW_LINE> self.BestFrameList = None <NEW_LINE> self.RequestId = None | :param BestFrameBase64: 验证通过后的视频最佳截图照片,照片为BASE64编码后的值,jpg格式。
注意:此字段可能返回 null,表示取不到有效值。
:type BestFrameBase64: str
:param Sim: 相似度,取值范围 [0.00, 100.00]。推荐相似度大于等于70时可判断为同一人,可根据具体场景自行调整阈值(阈值70的误通过率为千分之一,阈值80的误通过率是万分之一)。
:type Sim: float
:param Result: 业务错误码,成功情况返回Success, 错误情况请参考下方错误... | 625941d1cdde0d52a9e531c0 |
def _retlast(self, data): <NEW_LINE> <INDENT> return max(data, key = lambda a: a[0])[1] | rief return value (index 1) of maximum element by index 0
\param data | 625941d126238365f5f0effa |
def pad_to_longest_in_one_batch(batch): <NEW_LINE> <INDENT> noisy_mag_list = [] <NEW_LINE> mask_mag_list = [] <NEW_LINE> clean_mag_list = [] <NEW_LINE> n_frames_list = [] <NEW_LINE> for noisy_mag, mask, clean_mag, n_frames in batch: <NEW_LINE> <INDENT> noisy_mag_list.append(torch.t(torch.tensor(noisy_mag))) <NEW_LINE> ... | According to the longest item to pad dataset in one batch.
Notes:
usage of pad_sequence:
seq_list = [(L_1, dims), (L_2, dims), ...]
item.size() must be (L, dims)
return (longest_len, len(seq_list), dims)
Args:
batch: [
(noisy_mag_1, noise_mag_1, clean_mag_1, n_frames_1),
... | 625941d1d7e4931a7ee9e0aa |
def test_get_hard_cache_hit(self): <NEW_LINE> <INDENT> self.mock.get = Mock(return_value="bar") <NEW_LINE> value = self.cache.get("foo") <NEW_LINE> self.assertEquals("bar", value) <NEW_LINE> self.assertEquals(1, self.mock.get.call_count) <NEW_LINE> self.mock.get.assert_called_with("foo", version=None) <NEW_LINE> self.a... | Test getting a non-anti-dogpiled value from the cache which has not
timed out. The cached value should just be returned without any futher
ado. | 625941d194891a1f4081bc35 |
def user_edit(request, nid): <NEW_LINE> <INDENT> obj = models.UserInfo.objects.filter(id=nid).first() <NEW_LINE> if request.method == "GET": <NEW_LINE> <INDENT> form = UserInfoModelForm(instance=obj) <NEW_LINE> return render(request, 'user_edit.html', {"form": form}) <NEW_LINE> <DEDENT> form = UserInfoModelForm(data=re... | 编辑部门
:param request:
:param nid:
:return: | 625941d13d592f4c4ed1d1f8 |
def get_short_tables(tables): <NEW_LINE> <INDENT> return [_get_short_table(i, j) for i, j in tables] | Returns a set of short table wrappers.
:param tables: 2 member tuple: name, dict.
:returns: A specialization wrapper.
:rtype: tuple | 625941d123e79379d52ee6ef |
def normalize_mean0std1(data,data_mean=None,data_std=None): <NEW_LINE> <INDENT> if data_mean is None: <NEW_LINE> <INDENT> data_mean=np.mean(data,axis=0) <NEW_LINE> <DEDENT> data_mean.reshape((1,data_mean.shape[0])) <NEW_LINE> if data_std is None: <NEW_LINE> <INDENT> data_std=np.std(data,axis=0) <NEW_LINE> <DEDENT> data... | Normalize each feature to have mean 0 and std 1.
INPUTS:
data: numpy 2d array or matrix, each row should be a sample.
data_mean: numpy 1d array or vector, the given means of samples, useful for normalize test data.
data_std: numpy 1d array or vector, the given standard deviation of samples, useful for normalize test... | 625941d14e4d5625662d4562 |
def __str__(self, tail=None): <NEW_LINE> <INDENT> name = self.__class__.__name__ <NEW_LINE> if tail is None: <NEW_LINE> <INDENT> tail = "{}/{}".format(self.width, self.height) <NEW_LINE> <DEDENT> return ("[{}] ({}) {}/{} - {}".format (name, self.id, self.x, self.y, tail)) | print a str format | 625941d18da39b475bd65101 |
def close(self): <NEW_LINE> <INDENT> self.closed = True <NEW_LINE> self._wakeup_all() | Close the queue.
Future calls to ``WorkQueue.get`` will raise ``WorkQueueClosed`` | 625941d1d18da76e23532663 |
def save_account(user): <NEW_LINE> <INDENT> User.save_user(user) | Function to save a new user account on sign-up | 625941d14527f215b584c5e2 |
@click.group() <NEW_LINE> def cli(): <NEW_LINE> <INDENT> pass | Command Line Interface to Thomas' RESTful API and webinterface. | 625941d1c432627299f04dd2 |
def __init__(self, sys, basis, coeffs=[], flaglen=[]): <NEW_LINE> <INDENT> self.nstates = sys.nstates <NEW_LINE> self.ninputs = sys.ninputs <NEW_LINE> self.system = sys <NEW_LINE> self.basis = basis <NEW_LINE> self.coeffs = list(coeffs) <NEW_LINE> self.flaglen = list(flaglen) | Initilize a system trajectory object.
Parameters
----------
sys : FlatSystem
Flat system object associated with this trajectory.
basis : BasisFamily
Family of basis vectors to use to represent the trajectory.
coeffs : list of 1D arrays, optional
For each flat output, define the coefficients of the basis
... | 625941d10a366e3fb873e9a7 |
def __init__(self, max_width=80): <NEW_LINE> <INDENT> self.set_max_width(max_width) <NEW_LINE> self._precision = 3 <NEW_LINE> self._deco = Texttable.VLINES | Texttable.HLINES | Texttable.BORDER | Texttable.HEADER <NEW_LINE> self.set_chars(['-', '|', '+', '=']) <NEW_LINE> self.reset() | Constructor
- max_width is an integer, specifying the maximum width of the table
- if set to 0, size is unlimited, therefore cells won't be wrapped | 625941d130dc7b7665901af2 |
def generateFilenameFromUrl(url): <NEW_LINE> <INDENT> reverse = url[::-1] <NEW_LINE> filename = reverse[:reverse.find('/')][::-1] <NEW_LINE> reverse = reverse[reverse.find('/')+1:] <NEW_LINE> setname = reverse[:reverse.find('/')][::-1] <NEW_LINE> return 'imageCache/'+ setname + '_' + filename | Transforms a card URL into a local filename in the format
imageCache/setname_cardnumber.jpg. | 625941d192d797404e304316 |
def invalidate_tags(self, *tags, **kwargs): <NEW_LINE> <INDENT> if len(tags) == 1 and isinstance(tags[0], interfaces.IDependency): <NEW_LINE> <INDENT> dependency = tags[0] <NEW_LINE> <DEDENT> elif len(tags) == 1 and isinstance(tags[0], (list, tuple, set, frozenset)): <NEW_LINE> <INDENT> dependency = dependencies.TagsDe... | Invalidate specified tags | 625941d1004d5f362079a4be |
def saveComment(self): <NEW_LINE> <INDENT> frm = json.loads(self.request.body) <NEW_LINE> if "commentId" in frm: <NEW_LINE> <INDENT> c = CommentDto.get_by_id(long(frm["commentId"])) <NEW_LINE> if c: <NEW_LINE> <INDENT> if c.owner != self.get_current_user_key(): <NEW_LINE> <INDENT> raise ValueError("Cannot save comment ... | :return: | 625941d1462c4b4f79d1d85d |
def get_dict_s1(): <NEW_LINE> <INDENT> highways = tags.apply(lambda d: d.get("highway", "unclassified")) <NEW_LINE> types = np.sort(highways.unique()) <NEW_LINE> type_id = {} <NEW_LINE> for i in range(len(types)): <NEW_LINE> <INDENT> type_id[types[i]] = i <NEW_LINE> <DEDENT> df = pd.concat([roads.gid, highways.apply(la... | s1: highway | 625941d1be7bc26dc91cd78a |
def parseString(inString, silence=False, print_warnings=True): <NEW_LINE> <INDENT> parser = None <NEW_LINE> rootNode= parsexmlstring_(inString, parser) <NEW_LINE> gds_collector = GdsCollector_() <NEW_LINE> rootTag, rootClass = get_root_tag(rootNode) <NEW_LINE> if rootClass is None: <NEW_LINE> <INDENT> rootTag = 'distDF... | Parse a string, create the object tree, and export it.
Arguments:
- inString -- A string. This XML fragment should not start
with an XML declaration containing an encoding.
- silence -- A boolean. If False, export the object.
Returns -- The root object in the tree. | 625941d1004d5f362079a4bf |
def test_timestamp_translation_datetime(self): <NEW_LINE> <INDENT> expected = "2017-02-22 16:05:26" <NEW_LINE> actual = datetime.fromtimestamp(1487750726.0) <NEW_LINE> self.assertEqual(expected, str(actual)) | 将timestamp转化成datetime格式 | 625941d110dbd63aa1bd2d30 |
def list_instance_uuids(self): <NEW_LINE> <INDENT> uuids = self._vmops.list_instances() <NEW_LINE> return [uuid for uuid in uuids if uuidutils.is_uuid_like(uuid)] | List VM instance UUIDs. | 625941d1099cdd3c635f0de7 |
def check_group_members(ldap_entries) -> Iterable[str]: <NEW_LINE> <INDENT> for dn, attributes in _iterate_groups(ldap_entries): <NEW_LINE> <INDENT> members = attributes.get('member', []) <NEW_LINE> for member_dn in members: <NEW_LINE> <INDENT> if member_dn.lower() not in ldap_entries: <NEW_LINE> <INDENT> yield 'Unknow... | Check if all group members have a corresponding person entry. | 625941d17cff6e4e81117b12 |
def dists(): <NEW_LINE> <INDENT> for os_, arch in itertools.product(OS, ARCH): <NEW_LINE> <INDENT> if (os_, arch) in SKIP_BUILDS: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> yield (os_, arch) | Generator for tuples of distributions in form of (os, arch) | 625941d16e29344779a6279d |
def pytest_collection_modifyitems(session, config, items): <NEW_LINE> <INDENT> for item in items: <NEW_LINE> <INDENT> if isinstance(item, pytest.Function): <NEW_LINE> <INDENT> if isinstance(item, TestCaseFunction): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> function = item.obj <NEW_LINE> if USE_DOCSTRING_AS_DESCR... | Add description to the test node id if item is a function and function
has a description attribute or __doc__ attribute. | 625941d1460517430c39430f |
def get_avg_fragments_length(mates, genome_length): <NEW_LINE> <INDENT> avg_fragments_length = [0] * genome_length <NEW_LINE> physical_coverage = get_physical_coverage(mates, genome_length) <NEW_LINE> fragments_length = get_framents_length(mates, genome_length) <NEW_LINE> current_phisical_coverage = 0 <NEW_LINE> curren... | Return an array where every genomic position represents the average
length of fragments at that position. | 625941d156ac1b37e6264359 |
def TestConnection(self, pProps): <NEW_LINE> <INDENT> return super(IRoleStore, self).TestConnection(pProps) | Method IRoleStore.TestConnection
INPUT
pProps : IPropertySet* | 625941d1a4f1c619b28b01c3 |
def invoke_map_commands(command_function, file, prefix): <NEW_LINE> <INDENT> service = get_file_name(file) <NEW_LINE> lines = read_lines(file) <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> if check_prefix(prefix, line): <NEW_LINE> <INDENT> line = remove_line_feed(line) <NEW_LINE> args = parse_map(line) <NEW_LINE> c... | Invokes cli's map command for conf files | 625941d13539df3088e2e4d7 |
def worker(file: object, *args): <NEW_LINE> <INDENT> thread_name = current_thread().name <NEW_LINE> lock.acquire() <NEW_LINE> file.write(thread_name + ': ' + 'started.\n') <NEW_LINE> time.sleep(random.random() * 5) <NEW_LINE> file.write(thread_name + ': ' + 'done.\n') <NEW_LINE> lock.release() | worker function writes two strings with random pause to
shared file using synchronization primitive
:param file: file-object
:return: | 625941d19f2886367277aa19 |
def confusion_matrix(feature_vectors, labels, interference_fn=cosine_similarity): <NEW_LINE> <INDENT> unique_labels = torch.unique(labels, sorted=True) <NEW_LINE> mean_matrix = torch.zeros((len(unique_labels),)*2) <NEW_LINE> std_matrix = torch.zeros((len(unique_labels),)*2) <NEW_LINE> for i, label_i in enumerate(unique... | Computes a mean cosine similarity matrix
from a set of feature vectors and corresponding class labels
Parameters
----------
feature_vectors: torch.tensor
set of all corresponding class feature vectors
labels: torch.tensor
set of all class labels
interference_fn: visualize.fn
computes an interference score ... | 625941d166673b3332b9221d |
def test_email(self): <NEW_LINE> <INDENT> to = 'dest@address.com' <NEW_LINE> subject = 'msg subject' <NEW_LINE> body = 'msg body' <NEW_LINE> attachments = [] <NEW_LINE> with mock.patch('smtplib.SMTP.sendmail', autospec=True) as mocked: <NEW_LINE> <INDENT> monitor.util.sendemail.email(self.status, to, subject, body, att... | Test Sending Email. | 625941d11f5feb6acb0c4cdc |
def __getitem__(self, item): <NEW_LINE> <INDENT> if self.exists(item): <NEW_LINE> <INDENT> return self._nodes.get(item) <NEW_LINE> <DEDENT> raise KeyError("Vertex with given key doesn't exist in graph") | Method for getting instance in dictionary style ( graph [item] )
Args:
item - key which will be passed to get_node method
Raises:
KeyError - if doesn't exist Vertex with given key in graph | 625941d17d847024c06be449 |
def info(self, **kwargs): <NEW_LINE> <INDENT> path = self._get_id_path('info') <NEW_LINE> response = self._GET(path, kwargs) <NEW_LINE> self._set_attrs_to_values(response) <NEW_LINE> return response | Get the full details of a review by ID.
Returns:
A dict respresentation of the JSON returned from the API. | 625941d1236d856c2ad44968 |
def np_chunk(tree): <NEW_LINE> <INDENT> chunks = [] <NEW_LINE> for s in tree.subtrees(lambda t: t.label()=='CN'): <NEW_LINE> <INDENT> chunks.append(s) <NEW_LINE> <DEDENT> return chunks | Return a list of all noun phrase chunks in the sentence tree.
A noun phrase chunk is defined as any subtree of the sentence
whose label is "NP" that does not itself contain any other
noun phrases as subtrees. | 625941d1d164cc6175782eda |
def timestamp(): <NEW_LINE> <INDENT> now = datetime.datetime.now() <NEW_LINE> return now.strftime(TIMESTAMP_FORMAT) | Get a string indicating the current time.
| 625941d1d10714528d5ffe71 |
def add_track(tracked_objects, observation): <NEW_LINE> <INDENT> x, y = observation <NEW_LINE> state_vec = [x, 0, y, 0] <NEW_LINE> tp = TrackedPoint(state_vec, sigma_proc, sigma_meas) <NEW_LINE> xmin, ymin, xmax, ymax = bounds <NEW_LINE> tp.boundary.xmin, tp.boundary.ymin = xmin, ymin <NEW_LINE> tp.boundary.xmax, tp.bo... | Append a new TrackedPoint object to the `tracked_objects` list.
This is used as a callback in match_tracks_to_observations and the
signature should not change.
Parameters
----------
tracked_objects : list(TrackedPoint)
Append a new TrackedPoint to this list
observation : sequence of floats
(x, y) | 625941d163f4b57ef00012a4 |
def gMove(self): <NEW_LINE> <INDENT> a=float(self.jogStep.value()) <NEW_LINE> a=float(a*self.unitChangeLat) <NEW_LINE> b=self.MOT[0].position() <NEW_LINE> if b-a<self.buteNeg[0] : <NEW_LINE> <INDENT> print( "STOP : Butée Positive") <NEW_LINE> self.MOT[0].stopMotor() <NEW_LINE> <DEDENT> elif b-a>self.butePos[0] : <NEW_L... | action bouton left | 625941d1a05bb46b383ec9ad |
def get_dai_client(daiaddress, daipassword) -> 'driverlessai._core.Client': <NEW_LINE> <INDENT> print('----- start server connection : get_dai_client -----') <NEW_LINE> dai = driverlessai.Client(address=daiaddress, username=dai_user, password=daipassword) <NEW_LINE> return dai | DAIサーバへの接続
----------
daiaddress : str
daipassword : str | 625941d16fece00bbac2d8cb |
def createAttribute(self, QString): <NEW_LINE> <INDENT> return QDomAttr | QDomDocument.createAttribute(QString) -> QDomAttr | 625941d1379a373c97cfacd1 |
def __len__(self): <NEW_LINE> <INDENT> return len(self.__data) | Returns the size of the list of movies
(Overriding the len() built-in function) | 625941d1a79ad161976cc2d2 |
def elided(self, text, font_metrics, width): <NEW_LINE> <INDENT> html_stripped = strip_html(text) <NEW_LINE> if text.startswith(self.mark_str): <NEW_LINE> <INDENT> mark_stripped = strip_html(self.mark_str) <NEW_LINE> elided = font_metrics.elidedText(html_stripped, Qt.ElideMiddle, width) <NEW_LINE> return elided.replace... | Return an elided text preserving html tags.
If the text is wider than width, it is elided by replacing characters from the
middle by …. Surrounding html tags are not included in the calculation and left
untouched.
Args:
text: The text to elide.
font_metrics: QFontMetrics to create elided text based on width.
... | 625941d1bf627c535bc1335b |
def predict(self, xX, xG0, xG1=None, prob=True): <NEW_LINE> <INDENT> self._updateConstants() <NEW_LINE> if len(xX.shape)==1: <NEW_LINE> <INDENT> assert xX.shape[0]==self._D <NEW_LINE> assert xG0.shape[0]==self._G0.shape[1] <NEW_LINE> if xG1 is not None: <NEW_LINE> <INDENT> assert xG1.shape[0]==self._G1.shape[1] <NEW_LI... | Compute the probability of y=1.0, for each provided latent variable.
It can instead return only the most probable class by setting prob=False.
--------------------------------------------------------------------------
Input:
xX : [D] array of fixed effects or
[n*D] array of fixed effects ... | 625941d10a50d4780f66701f |
def with_page_token(self, page_token): <NEW_LINE> <INDENT> self.set_page_token(page_token) <NEW_LINE> return self | データの取得を開始する位置を指定するトークンを設定
:param page_token: データの取得を開始する位置を指定するトークン
:type page_token: unicode
:return: this
:rtype: DescribeShowcaseRequest | 625941d1596a897236089c4c |
def test_categories_dict(self): <NEW_LINE> <INDENT> cat_dict = self.definitions.categories_dict <NEW_LINE> self.assertEqual(len(cat_dict.keys()), 4) <NEW_LINE> self.assertIn('Covalent Modification', cat_dict.keys()) <NEW_LINE> self.assertIn('p+', cat_dict['Covalent Modification']) <NEW_LINE> self.assertIn('ppi', cat_di... | Tests correct creation of categories_dict
from the default_definition.py
(default_definition.py is used when quick input is used).
dict looks like {'Covalent Modification': 'p+', 'p-', ...'} | 625941d1fbf16365ca6f6353 |
def with_lightness(self, lightness): <NEW_LINE> <INDENT> h, s, l = self.__hsl <NEW_LINE> return Color((h, s, lightness), 'hsl', self.__a, self.__wref) | Create a new instance based on this one with a new lightness value.
Parameters:
:lightness:
The lightness of the new color [0...1].
Returns:
A grapefruit.Color instance.
>>> Color.from_hsl(30, 1, 0.5).with_lightness(0.25)
Color(0.5, 0.25, 0.0, 1.0)
>>> Color.from_hsl(30, 1, 0.5).with_lightness(0.25).hsl
(30.... | 625941d123849d37ff7b321c |
def last_failed_test(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> f = open("test_results.txt") <NEW_LINE> try: <NEW_LINE> <INDENT> return f.read().strip() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> f.close() <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> return None | Returns the name of the last failed test or None. | 625941d176d4e153a657ecbe |
def path_to_uri(path): <NEW_LINE> <INDENT> return urllib.parse.urljoin("file:", urllib.request.pathname2url(path)) | Convert the given path string to a valid URI.
It produces URI that are recognized by the windows
shell API on windows, e.g. 'C:\foo.txt' will be
'file:///C:/foo.txt' | 625941d1046cf37aa974ced4 |
def test_survey_view_update(self): <NEW_LINE> <INDENT> response = self.client.get('/survey/1/') <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertTemplateUsed(response, 'frontend/survey/survey_change.html') <NEW_LINE> request = self.factory.post('/survey/1/', {'name': 'test_survey'}, follow=T... | Test Function survey view update | 625941d14428ac0f6e5ba97f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.