code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def ignore(prefix=None, head=None, suffix=None): <NEW_LINE> <INDENT> assert head <NEW_LINE> pref = _join(prefix) <NEW_LINE> rest = _join(suffix) <NEW_LINE> return "ignore sub{0} {1}'{2};".format(pref, head, rest) | don't substitute `head` if it's surrounded by `prefix` and `suffix` | 625941c3d486a94d0b98e10d |
def delete_bp(self, bp_id): <NEW_LINE> <INDENT> self.__nbsock.delete_bp(bp_id) | Delete a breakpoint.
The breakpoint must have been already set in a Vim buffer with
'add_bp'.
Method parameter:
bp_id: object
The debugger breakpoint id. | 625941c3460517430c394151 |
def hpd(x, mass_frac): <NEW_LINE> <INDENT> d = np.sort(np.copy(x)) <NEW_LINE> n = len(x) <NEW_LINE> n_samples = np.floor(mass_frac * n).astype(int) <NEW_LINE> int_width = d[n_samples:] - d[: n - n_samples] <NEW_LINE> min_int = np.argmin(int_width) <NEW_LINE> return np.array([d[min_int], d[min_int + n_samples]]) | Returns highest probability density region given by
a set of samples.
Parameters
----------
x : array
1D array of MCMC samples for a single variable
mass_frac : float with 0 < mass_frac <= 1
The fraction of the probability to be included in
the HPD. For example, `massfrac` = 0.95 gives a
95% HPD.
Ret... | 625941c3283ffb24f3c558cb |
def get_hovered_color(self): <NEW_LINE> <INDENT> return self._hoveredcolor | Return the Buttons's color overlay when hovered over
parameters: -
return values: tuple of format pygame.Color representing the Buttons's color overlay when hovered over | 625941c356ac1b37e626419a |
def create_new_record(self, model, values, context=None): <NEW_LINE> <INDENT> values = dict(values) <NEW_LINE> res = self.client.create(model, values, context=context) <NEW_LINE> return res | Create a new record for ``model`` with ``values``. | 625941c3baa26c4b54cb10e9 |
def rectangular_shape(a,b): <NEW_LINE> <INDENT> a=int(a) <NEW_LINE> b=int(b) <NEW_LINE> side=max([a,b]) <NEW_LINE> I = np.zeros([side+2,side+2]) <NEW_LINE> I[(side-a)//2+1:(side+a)//2+1,(side-b)//2+1:(side+b)//2+1]=1 <NEW_LINE> return I | Parameters
----------
Returns
-------
References
----------
Examples
-------- | 625941c37b25080760e39422 |
def switch_log(self, callback): <NEW_LINE> <INDENT> if self.t is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> model = callback.get_model() <NEW_LINE> index = callback.get_active() <NEW_LINE> filename = model[index][0] <NEW_LINE> if filename != self.choice: <NEW_LINE> <INDENT> self.choice = filename <NEW_L... | Switch to another file. | 625941c3d6c5a10208144011 |
def is_executable(fpath: str): <NEW_LINE> <INDENT> return os.path.isfile(fpath) and os.access(fpath, os.X_OK) | Checks if a given path corresponds to an executable file | 625941c3f9cc0f698b1405c5 |
def eraseOverlapIntervals(self, intervals): <NEW_LINE> <INDENT> if intervals: <NEW_LINE> <INDENT> intervals.sort(key=lambda interval: interval.end) <NEW_LINE> lastInterval = intervals[0] <NEW_LINE> count = 0 <NEW_LINE> for idx in range(1,len(intervals)): <NEW_LINE> <INDENT> if intervals[idx].start < lastInterval.end: <... | :type intervals: List[Interval]
:rtype: int | 625941c34f6381625f114a04 |
def __init__(self, obs_status=None): <NEW_LINE> <INDENT> self.obs_status = obs_status | Constructor | 625941c33346ee7daa2b2d33 |
def from_multilabel_to_single(self, y_true, y_prob_dict, y_pred_matrix, clas): <NEW_LINE> <INDENT> y_prob_dict_class = dict() <NEW_LINE> y_pred_matrix_class = pd.DataFrame() <NEW_LINE> for model in y_prob_dict: <NEW_LINE> <INDENT> y_prob_dict_class[model] = pd.DataFrame(y_prob_dict[model][clas]) <NEW_LINE> y_prob_dict_... | when preforming multi_class prediction and the prediction are in a dictionary instead of a pandas matrix
this function transform the dictionary into a pandas matrix that can be used in the score_models
it selects only one class, so it has to be repeated as many times as the number of classes
:param y_true: matrix with ... | 625941c3a4f1c619b28b0005 |
def node_to_elem(root): <NEW_LINE> <INDENT> def generate_elem(append, node, level): <NEW_LINE> <INDENT> var = "e" + str(level) <NEW_LINE> arg = repr(node.tag) <NEW_LINE> if node.attrib: <NEW_LINE> <INDENT> arg += ", **%r" % node.attrib <NEW_LINE> <DEDENT> if level == 1: <NEW_LINE> <INDENT> append("e1 = Element(%s)" % a... | Convert (recursively) a Node object into an ElementTree object. | 625941c355399d3f0558867b |
def exists(self, key, callback=None): <NEW_LINE> <INDENT> args = ["EXISTS"] <NEW_LINE> args.append(key) <NEW_LINE> self.send_message(args, callback) | Determine if a key exists
:param key:
Complexity
----------
O(1) | 625941c38e71fb1e9831d772 |
def stream(self, activity_name=values.unset, activity_sid=values.unset, available=values.unset, friendly_name=values.unset, target_workers_expression=values.unset, task_queue_name=values.unset, task_queue_sid=values.unset, limit=None, page_size=None): <NEW_LINE> <INDENT> limits = self._version.read_limits(limit, page_s... | Streams WorkerInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param unicode activity_name: Filter by workers that are in a particular Activity... | 625941c3b7558d58953c4edf |
def select_items(predicate, source_dict): <NEW_LINE> <INDENT> return {k: v for k, v in source_dict.items() if predicate(k, v)} | Creates a new dict from the source dict where the items match the given predicate
:param predicate: predicate function that must accept a two arguments (key & value)
:param source_dict: input dictionary to select from
:return: filtered dict | 625941c373bcbd0ca4b2c03e |
def parseEntrez(fname): <NEW_LINE> <INDENT> entrez2Sym = dict() <NEW_LINE> entrez2RefseqProts = dict() <NEW_LINE> entrez2RefseqCodingSeqs = dict() <NEW_LINE> for row in maxCommon.iterTsvRows(fname): <NEW_LINE> <INDENT> entrez2Sym[int(row.entrezId)] = row.sym <NEW_LINE> if row.refseqProtIds == "": <NEW_LINE> <INDENT> re... | parse a tab-sep table with headers and return one dict with entrez to refprots
and another dict with entrez to symbol | 625941c3f7d966606f6a9fcb |
def test_write_missing_unique_identifiers(self): <NEW_LINE> <INDENT> payload = payloads.DeriveKeyRequestPayload( object_type=enums.ObjectType.SYMMETRIC_KEY ) <NEW_LINE> args = (utils.BytearrayStream(), ) <NEW_LINE> self.assertRaisesRegex( exceptions.InvalidField, "The DeriveKey request payload is missing the unique ide... | Test that an InvalidField error gets raised when encoding a DeriveKey
request payload missing the unique identifiers. | 625941c3507cdc57c6306c9f |
@dsc.command() <NEW_LINE> def handle_le(precommand, args): <NEW_LINE> <INDENT> series_key = extract_series_key(args) <NEW_LINE> value = extract_value(args) <NEW_LINE> nearest = find_less_than_or_equal(series_key, value) <NEW_LINE> nearest_text = present_value(args, nearest) <NEW_LINE> print(nearest_text) <NEW_LINE> ret... | usage: {program} le <e-series> <value> [--symbol]
The largest value less-than or equal-to the given value.
Options:
-s --symbol Use the SI magnitude prefix symbol. | 625941c3090684286d50ecac |
def dot(self, other): <NEW_LINE> <INDENT> return self.__x * other.__x + self.__y * other.__y | Opertaion of the dot product two vectors.
Args:
(Vecotr): Other vector.
Returns:
(float): dot product of self with other vector | 625941c363b5f9789fde70ad |
def LAP_two_clusters(cluster_A, cluster_B, alpha=0.5, max_iter1=100, max_iter2=100, parallel=True): <NEW_LINE> <INDENT> if len(cluster_A) <= len(cluster_B): <NEW_LINE> <INDENT> corresponding_streamlines = LAP(cluster_A, cluster_B, verbose=False, parallel=parallel) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> correspon... | Wrapper of LAP() between the streamlines of two clusters. This code
is able two handle clusters of different sizes and to invert the
result of corresponding_streamlines, if necessary. | 625941c38e7ae83300e4af94 |
def _makeSameLength(self): <NEW_LINE> <INDENT> for pitch_index in self.schedule.columns: <NEW_LINE> <INDENT> pocet_zapasu = self.schedule[pitch_index].count() <NEW_LINE> if pocet_zapasu < len(self.schedule): <NEW_LINE> <INDENT> self.schedule[pitch_index] = self.schedule[pitch_index].dropna().reset_index(drop=True) <NEW... | natahne vlozi mezery mezi zapasy tak, vsechny zapasy koncily stejne | 625941c32eb69b55b151c875 |
@task <NEW_LINE> def build_unix_unikernel(build_dir=None): <NEW_LINE> <INDENT> if build_dir is None: <NEW_LINE> <INDENT> sys.exit('Build directory is required') <NEW_LINE> <DEDENT> with cd(build_dir): <NEW_LINE> <INDENT> with prefix('eval `opam config env`'): <NEW_LINE> <INDENT> run('env NET=socket FS=crunch mirage con... | Produce a Unix unikernel.
Args:
build_dir: directory containing the config.ml configuration. | 625941c3cc40096d61595919 |
def getprotocolmod(request): <NEW_LINE> <INDENT> ldict = json.loads(request.POST['jpargs']) <NEW_LINE> return HttpResponse(returnQueryJson(*commonQuery(FeeMod.objects.all(), ldict))) | 协议模式查询 | 625941c3236d856c2ad447a0 |
def color15(color32): <NEW_LINE> <INDENT> r = int((color32[0]/256.0)*32) <NEW_LINE> g = int((color32[1]/256.0)*32) <NEW_LINE> b = int((color32[2]/256.0)*32) <NEW_LINE> return (r, g, b) | Convert 32-bit colors 0-255 to gba 15-bit colors 0-31 | 625941c37b180e01f3dc47c9 |
def handle(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> name = request.packageName <NEW_LINE> cfgMgr = BaseHandler.configMgr <NEW_LINE> infos = cfgMgr.getInstalledPackages().get(name, None) <NEW_LINE> if not infos: <NEW_LINE> <INDENT> request.put('无法找到模块:‘%s’ 的安装信息' % name, msgType='nerror') <NEW_LINE> ... | 检查相关的信息
:param request:
:return: | 625941c3a934411ee375165c |
def greaterthan(value, reference_value): <NEW_LINE> <INDENT> return value > reference_value | Return true if value > reference_value. | 625941c30fa83653e4656f84 |
def generateMatrix(n): <NEW_LINE> <INDENT> file_a = open("matrix.txt", 'w+') <NEW_LINE> matrix = [[0 for i in range(int(n))] for j in range(int(n))] <NEW_LINE> a = 1 <NEW_LINE> for m in range(0,int(n)): <NEW_LINE> <INDENT> for o in range(0,int(n)): <NEW_LINE> <INDENT> matrix[m][o] = int(a) <NEW_LINE> a+=1 <NEW_LINE> <D... | This function generates an N * N
matrix and writes the results to two
files matrixA.txt and matrixB.txt as row col values | 625941c3379a373c97cfab0c |
def download_dataset(download_dir: str, dataset_name: str = "midv500"): <NEW_LINE> <INDENT> if dataset_name == "midv500": <NEW_LINE> <INDENT> links_set = { "midv500": midv500_links, } <NEW_LINE> <DEDENT> elif dataset_name == "midv2019": <NEW_LINE> <INDENT> links_set = { "midv2019": midv2019_links, } <NEW_LINE> <DEDENT>... | This script downloads the MIDV-500 dataset with extra files and unzips the folders.
dataset_name: str
"midv500": https://doi.org/10.18287/2412-6179-2019-43-5-818-824
"midv2019": https://doi.org/10.1117/12.2558438
"all": midv500 + midv2019 | 625941c3796e427e537b058d |
def test_h2(self): <NEW_LINE> <INDENT> self.assertEqual( run_markdown('##Test'), '<p><h2>Test</h2></p>') | Lines starting with ## should be wrapped in 'h2' tags. | 625941c3e64d504609d74808 |
def d0(m,Lambda): <NEW_LINE> <INDENT> D0 = (3.67 + m)/Lambda <NEW_LINE> return D0 | Compute the median volume diameter (D0) using the method of moments as in
Tokay and Short (JAM 1996) - which assumes a gamma DSD model so that
the xth moment is expressed:
Gamma(m + x + 1)
Mx = N0 * -----------------
Lambda^(m + x + 1)
INPUT::
m = Shape parameter of... | 625941c326068e7796caeca4 |
def __repr__(self): <NEW_LINE> <INDENT> enzyme_rep = self.enzyme.__repr__() <NEW_LINE> substrate_rep = self.substrate.__repr__() <NEW_LINE> mod_target = self.target.__repr__() <NEW_LINE> res = "LigandModification(" + "enzyme={}, substrate={}, target={}, value={}".format( enzyme_rep, substrate_rep, mod_target... | Representation of a LigandModification object. | 625941c3fbf16365ca6f6189 |
def _usage_endpoint(self, endpoint, year=None, month=None): <NEW_LINE> <INDENT> err = False <NEW_LINE> if year is None and month is None: <NEW_LINE> <INDENT> resp = self.r_session.get(endpoint) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if int(year) > 0 and int(month) in range(1, 13): <NEW_L... | Common helper for getting usage and billing reports with
optional year and month URL elements.
:param str endpoint: Cloudant usage endpoint.
:param int year: Year to query against. Optional parameter.
Defaults to None. If used, it must be accompanied by ``month``.
:param int month: Month to query against that mu... | 625941c3566aa707497f4534 |
def slotActionTriggered(self): <NEW_LINE> <INDENT> pass | void KActionCollection.slotActionTriggered() | 625941c38c3a873295158381 |
def get_training_ops(self, should_enqueue): <NEW_LINE> <INDENT> ops = [self.training_op] <NEW_LINE> if should_enqueue: <NEW_LINE> <INDENT> ops += [self.requeue_op] <NEW_LINE> <DEDENT> return [ops], self.loss | Gets the training operations | 625941c330dc7b7665901931 |
def execute(*command): <NEW_LINE> <INDENT> devnull = open(os.devnull, 'w') <NEW_LINE> command = map(str, command) <NEW_LINE> subprocess.call(command, close_fds=True, stdout=devnull, stderr=devnull) <NEW_LINE> devnull.close() | Execute without returning stdout. | 625941c3d6c5a10208144012 |
def get_transactions_dates(self): <NEW_LINE> <INDENT> dates = [] <NEW_LINE> for wallet in self.wallets: <NEW_LINE> <INDENT> dates += wallet.dates() <NEW_LINE> <DEDENT> return sorted(dates) | :return: [] of datetime
List of all dates of all transactions of all wallets | 625941c3097d151d1a222e24 |
def text_msg_handler(self,message): <NEW_LINE> <INDENT> if not self.current_chat_contact: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> from_user_display_name = self.get_user_display_name(message) <NEW_LINE> format_msg = self.msg_timestamp(from_user_display_name,message["CreateTime"]) <NEW_LINE> from_user_name = message... | #:把文本消息加入到聊天記錄裏 | 625941c3cad5886f8bd26fa2 |
def lat_long_upper_left(tileX, tileY, zoom): <NEW_LINE> <INDENT> pixelX = tileX * 256 <NEW_LINE> pixelY = tileY * 256 <NEW_LINE> mapSize = 256*math.pow(2,zoom) <NEW_LINE> x = (pixelX / mapSize) - 0.5 <NEW_LINE> y = 0.5 - (pixelY / mapSize) <NEW_LINE> lonleft = 360 * x <NEW_LINE> lattop = (90-360 * math.atan(math.exp(-y... | A lat-long coordinate point for the upper left corner of a tile | 625941c37c178a314d6ef425 |
@boolean_fail <NEW_LINE> def is_multi_line_string(anything): <NEW_LINE> <INDENT> return ( isinstance(anything, dict) and anything.get("type") == "MultiLineString" and is_multi_line_string_coordinates(anything.get("coordinates")) and has_crs(anything) and has_bbox(anything) ) | Validate a GeoJSON MultiLineString. | 625941c382261d6c526ab465 |
def remove_groups(self, *group_names): <NEW_LINE> <INDENT> d = self._groups_systems <NEW_LINE> for group_name in group_names: <NEW_LINE> <INDENT> grp = d[group_name] <NEW_LINE> self._used_groups.remove(group_name) <NEW_LINE> grp._used_by.remove(self.name) <NEW_LINE> <DEDENT> self.invalidate_members() | Remove groups from group.
:type group_names: str | 625941c3656771135c3eb835 |
def get_oem_uuid_string(): <NEW_LINE> <INDENT> oem_uuid = "".join(["Q_SENTINEL_{", str(uuid.uuid4()).upper(), "}", datetime.datetime.now().strftime("_%Y%m%d_%H%M")]) <NEW_LINE> return oem_uuid | -------------------------------------------------------------------------
Get OEM uuid string
utility function to get OEM uuid string from multiple sources, used from
multiple functions
------------------------------------------------------------------------- | 625941c33c8af77a43ae3767 |
@app.route('/'.join(['', API_ROOT, API_VERSION, 'test-preparations', '<test_plan_uuid>', 'change']), methods=['POST']) <NEW_LINE> def test_in_execution(test_plan_uuid): <NEW_LINE> <INDENT> _LOG.debug(f'Callback received {request.path}, contains {request.get_data()}, ' f'Content-type: {request.headers["Content-type"]}')... | Executor->Curator
Test in execution: executor responses with the Test ID that can be used in a future test cancellation
{ "test-id": <test_id> }(?)
:param test_plan_uuid:
:return: | 625941c3a79ad161976cc10e |
def lockForWrite(self): <NEW_LINE> <INDENT> pass | lockForWrite(self) | 625941c371ff763f4b549651 |
def extract(ds, var_id): <NEW_LINE> <INDENT> nm = merra.get_varname(var_id) <NEW_LINE> uvar_nm = 'U*' + nm <NEW_LINE> vvar_nm = 'V*' + nm <NEW_LINE> ds_out = ds[nm].to_dataset() <NEW_LINE> ds_out[uvar_nm] = ds[uvar_nm] <NEW_LINE> ds_out[vvar_nm] = ds[vvar_nm] <NEW_LINE> return ds_out | Return variable plus its fluxes from dataset | 625941c3cad5886f8bd26fa3 |
def __init__(self, message): <NEW_LINE> <INDENT> super(CorruptXML, self).__init__("Corrupt XML: %s" % message) | initialization | 625941c36aa9bd52df036d6c |
def set_alpha(self, alpha): <NEW_LINE> <INDENT> tmp_color = Color(self) <NEW_LINE> tmp_color.has_alpha = True <NEW_LINE> tmp_color.alpha = alpha <NEW_LINE> return tmp_color | Sets the `alpha` (or alpha value) attribute
This will also enable this Color's tracking of its alpha value. | 625941c316aa5153ce362442 |
def mnist_download( filename, expected_bytes ): <NEW_LINE> <INDENT> filename = filename + ".gz" <NEW_LINE> filepath = mnist_download_folder + filename <NEW_LINE> if not os.path.exists( mnist_download_folder ): <NEW_LINE> <INDENT> os.makedirs( mnist_download_folder ) <NEW_LINE> <DEDENT> if not os.path.exists( filepath )... | Download a file if not present, and make sure it's the right size.
Files are stored in mnist_download | 625941c3596a897236089a8c |
def get(self): <NEW_LINE> <INDENT> if not self.is_logged_in(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> cookie_val = self.read_secure_cookie('user') <NEW_LINE> user_id = int(cookie_val) <NEW_LINE> user = user_id and models.Blogger.by_id(user_id) <NEW_LINE> if not user: <NEW_LINE> <INDENT> self.redirect('/signup')... | Render WelcomePage once new blogger signs up.
Redirects to signup page if user cookie is invalid. | 625941c3f8510a7c17cf96c4 |
def make_array(histos): <NEW_LINE> <INDENT> histo_shape = histos.x.shape <NEW_LINE> distortion = np.zeros(histo_shape, dtype=[('dx', np.float), ('dy', np.float), ('dz', np.float)]) <NEW_LINE> distortion[:, :, :]['dx'] = histos.x <NEW_LINE> distortion[:, :, :]['dy'] = histos.y <NEW_LINE> distortion[:, :, :]['dz'] = hist... | Convert the histos from FieldCalib input to a nice numpy array | 625941c3627d3e7fe0d68e18 |
def set_selected_obj(self): <NEW_LINE> <INDENT> self.obj_to_inst_txt = QtWidgets.QLabel("Object to Instance") <NEW_LINE> self.obj_to_inst_le = QtWidgets.QLineEdit() <NEW_LINE> self.obj_to_inst_le.setReadOnly(True) <NEW_LINE> self.obj_to_inst_le.setText("Object") <NEW_LINE> self.obj_to_inst_le.setFixedWidth(95) | set object to instance lineEdit | 625941c3a8370b7717052869 |
def fatorial(num: int) -> int: <NEW_LINE> <INDENT> if num <= 1: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> return num*(fatorial(num-1)) | num E Naturais ( Números *Inteiros* e *positivos* )
:param num: int
:return: int | 625941c38a43f66fc4b54030 |
def _build_lstm(self, inputs): <NEW_LINE> <INDENT> keep_prob = self.params.keep_prob <NEW_LINE> hidden_units = self.params.hidden_units <NEW_LINE> is_training = self._is_training <NEW_LINE> num_layers = self.params.num_layers <NEW_LINE> batch_size = self.params.batch_size <NEW_LINE> ts = self.params.time_steps <NEW_LIN... | Build LSTM Layers | 625941c31f037a2d8b9461c7 |
def UseSeaborn(palette='deep'): <NEW_LINE> <INDENT> import seaborn as sns <NEW_LINE> sns.set(style='whitegrid', font_scale=1.5, rc={'legend.frameon': True}) <NEW_LINE> sns.set_style('ticks') <NEW_LINE> sns.set_style({"xtick.direction": "in","ytick.direction": "in"}) <NEW_LINE> if palette == 'xkcd': <NEW_LINE> <INDENT> ... | Call to use seaborn plotting package
| 625941c3090684286d50ecad |
def check_invariance(self, value): <NEW_LINE> <INDENT> if not (isinstance(value, int) or isinstance(value, float)): <NEW_LINE> <INDENT> raise ValueError('Point: All values must be type int or float') | Raises exception if value is not int or float | 625941c34428ac0f6e5ba7ba |
def test_valid_base_class(self): <NEW_LINE> <INDENT> class_ = import_class("rapidsms.utils.test_modules.ChildOfA", ParentA) <NEW_LINE> self.assertTrue(issubclass(class_, ParentA)) <NEW_LINE> self.assertEqual(class_, ChildOfA) | Class should match base_class if supplied. | 625941c3de87d2750b85fd5a |
def get_tag_feed(tag, API,type_ = 'items'): <NEW_LINE> <INDENT> API.tagFeed(tag) <NEW_LINE> posts = API.LastJson <NEW_LINE> if type_ == 'story': <NEW_LINE> <INDENT> if "story" in posts.keys(): <NEW_LINE> <INDENT> return posts['story']['items'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> ... | Returns the posts for ranked items, items or stories given a tag, type_ and keys
InstagramAPI library | 625941c3aad79263cf390a08 |
def phi(self, i): <NEW_LINE> <INDENT> return self.parent()._phi(self.value).phi(i) | Return `\varphi_i` of ``self``.
EXAMPLES::
sage: D = crystals.Tableaux(['A',3], shapes=PartitionsInBox(4,3))
sage: G = GelfandTsetlinPatterns(4, 3)
sage: phi = lambda x: D(x.to_tableau())
sage: phi_inv = lambda x: G(x.to_tableau())
sage: I = crystals.Induced(G, phi, phi_inv)
sage: elt = I([[1,... | 625941c3a05bb46b383ec7ec |
def clean_all_reviews(self, remove_stopwords=False, stemmerize=False, remove_small_words=False): <NEW_LINE> <INDENT> for val in self.inputs: <NEW_LINE> <INDENT> cleaned = Imdb.clean_text(val) <NEW_LINE> if remove_stopwords: <NEW_LINE> <INDENT> cleaned = Imdb.remove_stop_words(cleaned) <NEW_LINE> <DEDENT> if stemmerize:... | Cleans the review data
:return: cleaned input values | 625941c3cc0a2c11143dce59 |
def weibull_pmf(t, a, b): <NEW_LINE> <INDENT> t = np.double(t) + 1e-35 <NEW_LINE> return weibull_cdf(t + 1.0, a, b) - weibull_cdf(t, a, b) | Probability mass function.
:param t: Value
:param a: Alpha
:param b: Beta
:return: `cdf(t + 1.0, a, b) - cdf(t, a, b)` | 625941c35f7d997b87174a5f |
def profile(self, duration_ns): <NEW_LINE> <INDENT> traces = self._profile(duration_ns) <NEW_LINE> return self._build_profile(duration_ns, traces) | Profiles the CPU time usage for the given duration.
Args:
duration_ns: An integer specifying the duration to profile in nanoseconds.
Returns:
A bytes object containing gzip-compressed profile proto. | 625941c37b25080760e39423 |
def diagonal_morphism(self,rename_vertices=True): <NEW_LINE> <INDENT> mutable = self._codomain.is_mutable() <NEW_LINE> X = self._domain.product(self._domain,rename_vertices=rename_vertices, is_mutable=mutable) <NEW_LINE> if self._codomain != X: <NEW_LINE> <INDENT> raise TypeError("diagonal morphism is only defined for ... | Return the diagonal morphism in `Hom(S, S \times S)`.
EXAMPLES::
sage: S = simplicial_complexes.Sphere(2)
sage: H = Hom(S,S.product(S, is_mutable=False))
sage: d = H.diagonal_morphism()
sage: d
Simplicial complex morphism:
From: Minimal triangulation of the 2-sphere
To: Simplicial co... | 625941c3a17c0f6771cbe01b |
def maxProfit(self, prices): <NEW_LINE> <INDENT> if len(prices) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> minpoint = prices[0] <NEW_LINE> maxpoint = prices[0] <NEW_LINE> tempmin = prices[0] <NEW_LINE> tempmax = prices[0] <NEW_LINE> maxprofit = maxpoint - minpoint <NEW_LINE> for i in range(len(prices)): <NE... | :type prices: List[int]
:rtype: int | 625941c3e1aae11d1e749c7f |
def test_func(self): <NEW_LINE> <INDENT> return self.request.user.is_authenticated and self.request.user.is_staff | called by the UserPassesTestMixin to verify the user has permissions to use this view | 625941c3cc0a2c11143dce5a |
def remove_implied_spec_nodes(tree, added_nodes, recon=None, events=None): <NEW_LINE> <INDENT> for node in added_nodes: <NEW_LINE> <INDENT> remove_spec_node(node, tree, recon, events) | removes speciation nodes from tree | 625941c3bd1bec0571d905f8 |
def solve_quadratic(a: float, b: float, c: float) -> Tuple[float, float]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> solution_1 = (-b + math.sqrt(math.pow(b, 2) - (4 * a * c))) / (2 * a) <NEW_LINE> solution_2 = (-b - math.sqrt(math.pow(b, 2) - (4 * a * c))) / (2 * a) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> ... | Solve a quadratic using the quadratic formula | 625941c3cb5e8a47e48b7a76 |
def set_value(self, value): <NEW_LINE> <INDENT> self.iface_value.SetValue(value) <NEW_LINE> return self | An interface to the SetValue method of the Value control pattern | 625941c30c0af96317bb81b1 |
def save_document_from_provn(self, content=None): <NEW_LINE> <INDENT> prov_document = form_string(content=content) <NEW_LINE> return self.save_document(content=prov_document) | Saves a prov document in the database based on the provn string or buffer
:param content: provn object
:type content: str or buffer
:return: Document_id
:rtype: str | 625941c344b2445a33932060 |
def integrate(self, location, step): <NEW_LINE> <INDENT> new_location = self.step_size*step + location <NEW_LINE> return new_location | Takes a step of step_size from location | 625941c399fddb7c1c9de35b |
def setrestart(self, database, restart_policy ): <NEW_LINE> <INDENT> key = "Database:%s" % database <NEW_LINE> self.configdict.set(key, "restartpolicy", restart_policy) | set the restart policy for a given database | 625941c3a79ad161976cc10f |
def _get_dialog_parent(self): <NEW_LINE> <INDENT> return self._dialog_parent.get_dialog_parent() | Get Alias dialog parent | 625941c3d7e4931a7ee9dee7 |
def close_bold_code(): <NEW_LINE> <INDENT> result = HtmlRequests.close_bold() + HtmlRequests.close_code() <NEW_LINE> log.debug(result) <NEW_LINE> return result | Returns '</b></code>' | 625941c37cff6e4e8111794f |
def query(request, obj): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> form = QueryForm(request.POST, {"typeobj_id":obj}) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> return HttpResponseRedirect('/thanks/') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> form = QueryForm(typeobj_id=o... | Форма запроса на выбранный объект учёта `obj` | 625941c33617ad0b5ed67ec2 |
def is_fully_expanded(self): <NEW_LINE> <INDENT> return len(self.untried_actions) == 0 | 判断这个的子节点是否全被遍历过了
:return: | 625941c391af0d3eaac9b9e1 |
def slugify(value): <NEW_LINE> <INDENT> value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') <NEW_LINE> value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) <NEW_LINE> return re.sub('[-\s]+', '-', value) | Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
From Django's "django/template/defaultfilters.py". | 625941c3ac7a0e7691ed4099 |
def symmetrize(W, method='average'): <NEW_LINE> <INDENT> if W.shape[0] != W.shape[1]: <NEW_LINE> <INDENT> raise ValueError('Matrix must be square.') <NEW_LINE> <DEDENT> if method == 'average': <NEW_LINE> <INDENT> return (W + W.T) / 2 <NEW_LINE> <DEDENT> elif method == 'maximum': <NEW_LINE> <INDENT> if sparse.issparse(W... | Symmetrize a square matrix.
Parameters
----------
W : array_like
Square matrix to be symmetrized
method : string
* 'average' : symmetrize by averaging with the transpose. Most useful
when transforming a directed graph to an undirected one.
* 'maximum' : symmetrize by taking the maximum with the trans... | 625941c329b78933be1e5678 |
def class_variance_b_squared(im, k, maxCount=255): <NEW_LINE> <INDENT> print("======= {} ======".format(k)) <NEW_LINE> print("w0", w0(im,k)) <NEW_LINE> print("w1", w1(im,k)) <NEW_LINE> print("u", u(im, k)) <NEW_LINE> print("u0", u0(im,k)) <NEW_LINE> print("u1", u1(im,k)) <NEW_LINE> return w0(im, k) * w1(im, k) * ( (u1(... | Function to get the class variance b squared, as described in otsu's paper
Args:
im (array): image to convert to histogram and evaluate
i (int): pixel level to evaluating class variance
maxCount (option[int]): total number of pixel levels possible
shortcut for total class variance squared
Returns:... | 625941c3e8904600ed9f1ef4 |
def extract_attraction_info(rel_url): <NEW_LINE> <INDENT> name = "DUMMY_NAME" <NEW_LINE> description = "DUMMY_DESCRIPTION" <NEW_LINE> address = "DUMMY_ADDRESS" <NEW_LINE> return name, description, address | Extract attraction name, description (overview) and address for
attraction at f"{base_url}{rel_url}" | 625941c35f7d997b87174a60 |
def get(self): <NEW_LINE> <INDENT> self.delayed_call = self.dask_obj <NEW_LINE> return self.delayed_call.compute() | Return the object wrapped by this one to the original format.
Note: This is the opposite of the classmethod `put`.
E.g. if you assign `x = BaseRemotePartition.put(1)`, `x.get()` should
always return 1.
Returns:
The object that was `put`. | 625941c3d10714528d5ffcab |
def intersection_plan(self, r): <NEW_LINE> <INDENT> if r.direction.scalaire(self.vnorm) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> oa = self.a - r.origine <NEW_LINE> lv = self.vnorm.scalaire(oa) / self.vnorm.scalaire(r.direction) <NEW_LINE> p = r.origine + r.direction * lv <NEW_LINE> return p | retourne le point d'intersection entre le plan et le rayon r | 625941c3460517430c394153 |
def _get_soup(url, backend='selenium'): <NEW_LINE> <INDENT> if backend == 'requests': <NEW_LINE> <INDENT> req = requests.get(url, headers={'User-Agent': UA}) <NEW_LINE> html_doc = req.text <NEW_LINE> soup = BeautifulSoup(html_doc) <NEW_LINE> if soup.find('div', attrs={'id': 'gs_ab_md'}) is None: <NEW_LINE> <INDENT> pri... | Get BeautifulSoup object from url.
Parameters
----------
url : str
The url to fetch.
backend : 'selenium' | 'requests'
Use selenium by default because google can ask for captcha. For
'selenium' backend Firefox must be installed.
Returns
-------
soup : instance of BeautifulSoup
The soup page from the u... | 625941c3d6c5a10208144013 |
def loglikelihood(self, a, prob): <NEW_LINE> <INDENT> return tf.log(self.likelihood(a, prob)) | Log-likehood of observation, given distribution. | 625941c356b00c62f0f14622 |
def create(self, obj): <NEW_LINE> <INDENT> obj.create(self.session) <NEW_LINE> return obj | Create an object.
:param obj: A resource object.
:type resource: :class:`~openstack.resource.Resource` | 625941c330c21e258bdfa466 |
def _count_c_tests(self, progabs, progdir, progbase): <NEW_LINE> <INDENT> cmdline = [ progabs, '--list' ] <NEW_LINE> with Popen(cmdline, stdout=subprocess.PIPE, cwd=progdir) as prog: <NEW_LINE> <INDENT> lines = prog.stdout.readlines() <NEW_LINE> self.result.append(TestHarness.Job(len(lines) - 2, False, progabs, progdir... | Run a c test, escaping parameters as required. | 625941c3711fe17d82542339 |
def test_filterInstalled(self): <NEW_LINE> <INDENT> filter = self.store.findUnique(spam.Filter) <NEW_LINE> self.failIf( (filter.messageSource is None or filter.tiSource is None), 'spam.Filter was not installed properly') | Test that the L{xquotient.spam.Filter} looks like it was properly
installed, by looking at its dependencies | 625941c344b2445a33932061 |
def serialize(self): <NEW_LINE> <INDENT> return yaml.dump( {'comm': self._config_dictionary() }, default_flow_style=False) | @brief Get yaml dump of object data
@retval yaml string of object data | 625941c330dc7b7665901932 |
def prepareSubgraphWithData(self, data): <NEW_LINE> <INDENT> scene = QtWidgets.QGraphicsScene() <NEW_LINE> scene.addText(str(data)) <NEW_LINE> subgraph = QtWidgets.QGraphicsView() <NEW_LINE> subgraph.setScene(scene) <NEW_LINE> return subgraph | Create graphics view containing scene with string | 625941c321a7993f00bc7cb7 |
def to_csv(self) -> str: <NEW_LINE> <INDENT> return "{},{},\"{}\",{},{}".format( self.get_season(), self.get_episode(), self.get_name(), self.get_runtime(), self.is_watched()) | Returns the CSV representation of this Episode | 625941c34e696a04525c9416 |
def _all_media(self): <NEW_LINE> <INDENT> self.set_text(_("Writing media")) <NEW_LINE> sorted_list = sort_handles_by_id(self.dbase.get_media_handles(), self.dbase.get_media_from_handle) <NEW_LINE> for media_handle in [hndl[1] for hndl in sorted_list]: <NEW_LINE> <INDENT> self.update() <NEW_LINE> self._media(self.dbase.... | Write out the list of media, sorting by Gramps ID. | 625941c38e71fb1e9831d774 |
def __getitem__(self, name): <NEW_LINE> <INDENT> return self.results[str(name).upper()] | Get a specific header, as from a dictionary. | 625941c373bcbd0ca4b2c040 |
def get_sum(self,lst): <NEW_LINE> <INDENT> sum = 0 <NEW_LINE> for product in lst : <NEW_LINE> <INDENT> sum+=product.get_quantity()*product.get_price() <NEW_LINE> <DEDENT> return sum | computes the sum of the list (cart or purchased list of items)
:param lst: list of products to be parsed and to be added to the sum their cost(each product's cost)
:return: | 625941c35fc7496912cc3948 |
def __init__(self): <NEW_LINE> <INDENT> self._header = self._Node(None, None, None) <NEW_LINE> self._trailer = self._Node(None, None, None) <NEW_LINE> self._header._next = self._trailer <NEW_LINE> self._trailer._prev = self._header <NEW_LINE> self._size = 0 | Create a structure with two empty nodes, headers and tailer | 625941c3b830903b967e98d7 |
def cli_build(args: argparse.Namespace) -> None: <NEW_LINE> <INDENT> build(**{k: v for k, v in vars(args).items() if v is not None}) | Run a build using arguments parsed from the command line.
:param args: A namespace of parsed arguments. | 625941c38a349b6b435e813d |
def format(_pattern, *args, stepout=1, _quote_all=False, **kwargs): <NEW_LINE> <INDENT> frame = inspect.currentframe().f_back <NEW_LINE> while stepout > 1: <NEW_LINE> <INDENT> if not frame.f_back: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> frame = frame.f_back <NEW_LINE> stepout -= 1 <NEW_LINE> <DEDENT> variables = ... | Format a pattern in Snakemake style.
This means that keywords embedded in braces are replaced by any variable
values that are available in the current namespace. | 625941c3d164cc6175782d18 |
def _handle_ff(self, data): <NEW_LINE> <INDENT> self._reset_recv() <NEW_LINE> size = ((data[0] & 0xF) << 8) + data[1] <NEW_LINE> if not size: <NEW_LINE> <INDENT> size = struct.unpack_from('>L', data, 2) <NEW_LINE> frame_payload = data[6:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> frame_payload = data[2:] <NEW_LINE>... | Handle first frame. | 625941c356ac1b37e626419d |
def acceleration(self): <NEW_LINE> <INDENT> radian = self.deg_to_rad() <NEW_LINE> new_speed_x = self.__pos_vel_x[1] + cos(radian) <NEW_LINE> new_speed_y = self.__pos_vel_y[1] + sin(radian) <NEW_LINE> self.__pos_vel_x = (self.__pos_vel_x[0], new_speed_x) <NEW_LINE> self.__pos_vel_y = (self.__pos_vel_y[0], new_speed_y) | Sets ship's horizontal and vertical velocity according to an
acceleration formula. | 625941c33d592f4c4ed1d03c |
def __shuffleArrays(self, *arrs): <NEW_LINE> <INDENT> arrs = list(arrs) <NEW_LINE> for i, arr in enumerate(arrs): <NEW_LINE> <INDENT> assert len(arrs[0]) == len(arrs[i]) <NEW_LINE> arrs[i] = np.array(arr) <NEW_LINE> <DEDENT> p = np.random.permutation(len(arrs[0])) <NEW_LINE> return tuple(arr[p] for arr in arrs) | shuffle.
Shuffle given arrays at unison, along first axis.
Arguments:
*arrs: Each array to shuffle at unison as a parameter.
Returns:
Tuple of shuffled arrays. | 625941c34a966d76dd550fd8 |
def getAction(self, gameState): <NEW_LINE> <INDENT> def terminalTest(gameState,cnt=0): <NEW_LINE> <INDENT> return gameState.isWin() or gameState.isLose() or self.depth == cnt <NEW_LINE> <DEDENT> def maxValue(gameState,cnt=0): <NEW_LINE> <INDENT> if terminalTest(gameState,cnt): <NEW_LINE> <INDENT> return self.evaluation... | Returns the minimax action from the current gameState using self.depth
and self.evaluationFunction.
Here are some method calls that might be useful when implementing minimax.
gameState.getLegalActions(agentIndex):
Returns a list of legal actions for an agent
agentIndex=0 means Pacman, ghosts are >= 1
gameState.g... | 625941c3e76e3b2f99f3a7d8 |
def crawl_basic(begin_date=None, end_date=None): <NEW_LINE> <INDENT> if begin_date is None: <NEW_LINE> <INDENT> begin_date = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d') <NEW_LINE> <DEDENT> if end_date is None: <NEW_LINE> <INDENT> end_date = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d') <NEW_LI... | 抓取指定时间范围内的股票基础信息
:param begin_date: 开始日期
:param end_date: 结束日期 | 625941c32eb69b55b151c877 |
def noticia_detalle(request,slug): <NEW_LINE> <INDENT> noticia = get_object_or_404(Noticia, slug=slug) <NEW_LINE> noticia_rel = Noticia.objects.filter(categoria=noticia.categoria).exclude(id = noticia.id).order_by('-fecha','-id')[:4] <NEW_LINE> dicc = {'noticia': noticia, 'noticia_rel':noticia_rel, } <NEW_LINE> return ... | Muestra el detalle de la noticia | 625941c3f548e778e58cd547 |
def __init__(self): <NEW_LINE> <INDENT> wx.Frame.__init__(self, None, -1, 'Apodization Viewer') <NEW_LINE> self.SetBackgroundColour(wx.NamedColor("WHITE")) <NEW_LINE> self.figure = Figure() <NEW_LINE> self.axes = self.figure.add_subplot(111) <NEW_LINE> self.canvas = FigureCanvas(self, -1, self.figure) <NEW_LINE> self.t... | Initializate the frame | 625941c323e79379d52ee530 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.