code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def ones2(basis): <NEW_LINE> <INDENT> results=[] <NEW_LINE> for i in range(len(basis)): <NEW_LINE> <INDENT> zeroes=[0]*len(basis) <NEW_LINE> if basis[i]==1: <NEW_LINE> <INDENT> zeroes[i]=1 <NEW_LINE> results.append(zeroes) <NEW_LINE> <DEDENT> <DEDENT> return results | Input:
basis: List of Integers (0 or 1)
Output:
List of lists of Integers (each list has one 1 on a place like in basis) | 625941e1dc8b845886cb58d8 |
def map_to_generic(self, generic): <NEW_LINE> <INDENT> return [] | In this case *this* is the generic bus, there is no mapping that
needs to be done. Simply return ourself and all is good.
:return: | 625941e1a8ecb033257d346d |
def __init__(self,addr=DEFAULT_LISTEN_ADDRESS, outdir = config['OUTPUT_DIRECTORY'] ): <NEW_LINE> <INDENT> self.outdir = outdir <NEW_LINE> self.addr = addr <NEW_LINE> self.logger = logging.getLogger(__name__) | Set up the coordinator object | 625941e126238365f5f0f214 |
def table_disperssion(data, axs, f=2): <NEW_LINE> <INDENT> v_bessel_sd = round(data.std(), f) <NEW_LINE> v_var = round(data.var(), f) <NEW_LINE> v_range = round((data.max()-data.min()), f) <NEW_LINE> v_iqr = round((data.quantile(0.75)-data.quantile(0.25)), f) <NEW_LINE> v_mad = round(data.mad(), f) <NEW_LINE> sample_st... | Returns a plotted table on an axs.
Based on statistics for disperssion, can
take one column or more.
Requires an matplot lib `axs` as input to be used.
Parameters
----------
data : DataFrame object
Pandas DataFrame containing columns to be used
for statistics.
axs : matplotlib axs object
axs (e.g. subplo... | 625941e1d486a94d0b98e4e8 |
def initialize_or_restore(self, session=None): <NEW_LINE> <INDENT> self._load_status.initialize_or_restore(session) <NEW_LINE> return self._load_status | Initialize or restore graph (based on checkpoint if exists). | 625941e130bbd722463cc169 |
@pytest.mark.flaky(min_passes=1, max_runs=3) <NEW_LINE> @pytest.mark.skipif(no_casa or no_astropy, reason="Neither python-casacore or astropy installed") <NEW_LINE> @pytest.mark.parametrize('obs_and_tol', [ ((2018, 1, 1, 4), "10s"), ((2018, 2, 20, 8), "10s"), ((2018, 11, 2, 4), "10s")]) <NEW_LINE> def test_compare_astr... | Compare astropy and python-casacore parallactic angle implementations.
More work needs to be done here to get things lined up closer,
but the tolerances above suggest nothing > 10 arcseconds. | 625941e1bf627c535bc13571 |
def setup_app(command, conf, vars): <NEW_LINE> <INDENT> load_environment(conf.global_conf, conf.local_conf) | Place any commands to setup demo here | 625941e17d43ff24873a3044 |
def assertIsInstance(self, obj, klass, msg=None, strict=False): <NEW_LINE> <INDENT> if strict: <NEW_LINE> <INDENT> warnings.warn('[API] Non-standard. Strict parameter has vanished', DeprecationWarning, stacklevel=2) <NEW_LINE> <DEDENT> if msg is None: <NEW_LINE> <INDENT> if strict: <NEW_LINE> <INDENT> msg = '%r is not ... | check if an object is an instance of a class
:param obj: the Python Object to be checked
:param klass: the target class
:param msg: a String for a custom message
:param strict: if True, check that the class of <obj> is <klass>;
else check with 'isinstance' | 625941e15fcc89381b1e1a62 |
def validate(self): <NEW_LINE> <INDENT> return | Validate message parameters during initialization
Raises:
ValidationError | 625941e1d4950a0f3b08c6eb |
def create_policy(policyName=None, policyDocument=None, tags=None): <NEW_LINE> <INDENT> pass | Creates an AWS IoT policy.
The created policy is the default version for the policy. This operation creates a policy version with a version identifier of 1 and sets 1 as the policy's default version.
See also: AWS API Documentation
Exceptions
:example: response = client.create_policy(
... | 625941e1925a0f43d254a21c |
def pc_work_time_var(self): <NEW_LINE> <INDENT> return _atsc_swig.atsc_fpll_sptr_pc_work_time_var(self) | pc_work_time_var(atsc_fpll_sptr self) -> float | 625941e1e76e3b2f99f3aba8 |
def onDeleted(self): <NEW_LINE> <INDENT> self.scene.pieces.pop(self.piece) | Called by scene.ChessPieceFeedback | 625941e157b8e32f5248383f |
def Get_sequence_info(self): <NEW_LINE> <INDENT> masked = [] <NEW_LINE> GC = [] <NEW_LINE> gaps = [] <NEW_LINE> lengths = [] <NEW_LINE> gc_chars = ["G", "C", "g", "c"] <NEW_LINE> for value in self.seqs.values(): <NEW_LINE> <INDENT> seq_length = len(value) <NEW_LINE> lengths.append(seq_length) <NEW_LINE> masked_count = ... | I only want to loop through the file once ideally, so lets get as much information here as I can | 625941e130dc7b7665901d04 |
def min(self, axis=None): <NEW_LINE> <INDENT> mask = self.asi8 == tslib.iNaT <NEW_LINE> masked = self[~mask] <NEW_LINE> if len(masked) == 0: <NEW_LINE> <INDENT> return tslib.NaT <NEW_LINE> <DEDENT> elif self.is_monotonic: <NEW_LINE> <INDENT> return masked[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> min_stamp = mas... | Overridden ndarray.min to return a Timestamp | 625941e13617ad0b5ed68298 |
def step(self): <NEW_LINE> <INDENT> self.step_num += 1 <NEW_LINE> lr = self.d_model**(-0.5) * min(self.step_num**(-0.5), self.step_num*self.warmup_steps**(-.5)) <NEW_LINE> for p in self.optimizer.param_groups: <NEW_LINE> <INDENT> p['lr'] = lr <NEW_LINE> <DEDENT> self.current_lr = lr <NEW_LINE> self.optimizer.step() | Runs at every step and updates the learning rate
:return: | 625941e1eab8aa0e5d26defb |
def isPalindrome(self, s): <NEW_LINE> <INDENT> s2=re.sub("[^a-z0-9]","",s.lower()) <NEW_LINE> if s2==[]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if s2==s2[::-1]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | :type s: str
:rtype: bool | 625941e144b2445a33932435 |
def _fixed_shutter_control(self): <NEW_LINE> <INDENT> if self.fixed_shutter == 0: <NEW_LINE> <INDENT> self.fixed_shutter = 1 <NEW_LINE> self.fixed_shutter_button.label = '1040 nm Shutter Open' <NEW_LINE> self.fixed_shutter_button._form.setStyleSheet(self._button_on) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.fi... | Opens the shutter for the fundamental output. | 625941e17d847024c06be661 |
def uniquePaths(self, m, n): <NEW_LINE> <INDENT> dp = [[0 for _ in xrange(n)] for _ in xrange(m)] <NEW_LINE> for i in xrange(n): <NEW_LINE> <INDENT> dp[0][i] = 1 <NEW_LINE> <DEDENT> for i in xrange(m): <NEW_LINE> <INDENT> dp[i][0] = 1 <NEW_LINE> <DEDENT> for i in xrange(1, m): <NEW_LINE> <INDENT> for j in xrange(1, n):... | :type m: int
:type n: int
:rtype: int | 625941e14e4d5625662d4775 |
def download_page(url, browser): <NEW_LINE> <INDENT> page_down_count = 0 <NEW_LINE> def get_artile(artcle_url): <NEW_LINE> <INDENT> nonlocal count <NEW_LINE> browser.get(artile_real_url) <NEW_LINE> selector_article = Selector(text=browser.page_source) <NEW_LINE> os.path.exists('title') or os.mkdir('title') <NEW_LINE> t... | 文章列表,最多尝试5次 | 625941e1187af65679ca54c2 |
def __init__(self, endpoint): <NEW_LINE> <INDENT> super(DefaultChannel, self).__init__() <NEW_LINE> self._endpoint = endpoint <NEW_LINE> self._context = get_Zcontext() <NEW_LINE> self._poller = zmq.Poller() <NEW_LINE> self._socket = None | Constructor. | 625941e11f5feb6acb0c4eeb |
def fit(self, x: np.ndarray) -> np.ndarray: <NEW_LINE> <INDENT> if x.shape[0] == 1: <NEW_LINE> <INDENT> raise OneSamplePassedException('Cannot perform KPCA for 1 sample.') <NEW_LINE> <DEDENT> self._x_fit = x <NEW_LINE> kernel_matrix = self.kernel.calc_matrix(self._x_fit) <NEW_LINE> kernel_matrix = KPCA._center_symmetri... | Creates eigenvalues and eigenvectors.
:param x: the array to be fitted.
:return: n_components number of eigenvalues and eigenvectors. | 625941e1956e5f7376d7120d |
def evaluate_test(model, data_loader, output_dir = "./preds/"): <NEW_LINE> <INDENT> model.eval() <NEW_LINE> preds = [] <NEW_LINE> with torch.no_grad(): <NEW_LINE> <INDENT> cnt = 0 <NEW_LINE> for _, imgs in enumerate(data_loader): <NEW_LINE> <INDENT> imgs = imgs.cuda() <NEW_LINE> pred = model(imgs) <NEW_LINE> rgb_mask =... | set model to evaluate mode | 625941e1b7558d58953c52af |
def is_ref(expr): <NEW_LINE> <INDENT> return _fn({"is_ref": expr}) | See the `docs <https://docs.fauna.com/fauna/current/api/fql/functions/isref>`__. | 625941e1462c4b4f79d1da71 |
def loss(self, features, captions): <NEW_LINE> <INDENT> captions_in = captions[:, :-1] <NEW_LINE> captions_out = captions[:, 1:] <NEW_LINE> mask = (captions_out != self._null) <NEW_LINE> W_proj, b_proj = self.params['W_proj'], self.params['b_proj'] <NEW_LINE> W_embed = self.params['W_embed'] <NEW_LINE> Wx, Wh, b = self... | Compute training-time loss for the RNN. We input image features and
ground-truth captions for those images, and use an RNN (or LSTM) to compute
loss and gradients on all parameters.
Inputs:
- features: Input image features, of shape (N, D)
- captions: Ground-truth captions; an integer array of shape (N, T) where
eac... | 625941e1aad79263cf390de8 |
def close(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> asyncio.ensure_future(self.es.close()) <NEW_LINE> logger.debug("Closed ES connection pool") <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.error(e) | :return: | 625941e1046cf37aa974d0e6 |
def _set_item_at_location(self, location, item): <NEW_LINE> <INDENT> self._room[location.getX()][location.getY()] = item | sets an item at a specific location | 625941e17047854f462a17a7 |
def solve_t_before(self, t, *args, **kwargs): <NEW_LINE> <INDENT> self.xr[t] = self.xr_bar[t] <NEW_LINE> self.submodels['North'].p_g[t] = self.p_g_bar[t] / self.xr[t] <NEW_LINE> self.submodels['South'].p_g[t] = self.p_g_bar[t] * self.xr[t] | Evaluate equations that only need to solve once per period, prior to iterative solution. | 625941e1d4950a0f3b08c6ec |
def train_gpr_model(TRAIN): <NEW_LINE> <INDENT> train_dat=TRAIN.iloc[:,:-1] <NEW_LINE> train_gs=TRAIN.iloc[:,-1] <NEW_LINE> kernel = DotProduct() + WhiteKernel() <NEW_LINE> gpr = GaussianProcessRegressor(kernel=kernel, random_state=0).fit(train_dat, train_gs) <NEW_LINE> return gpr | Train Gaussian Process Regression model
Params:
-------
TRAIN: Pandas dataframe
training set; last column is label
Yields:
-------
gpr: Gaussian Process Regression model | 625941e1956e5f7376d7120e |
def leave_building(self): <NEW_LINE> <INDENT> if self.player.building_local is not None: <NEW_LINE> <INDENT> print(f"Leaving {self.player.building_local.name}") <NEW_LINE> self.player.building_local = None | Exit the building the player is inside | 625941e1cdde0d52a9e533d7 |
def get_time_spents_for_year(year=None, person_id=None): <NEW_LINE> <INDENT> query = TimeSpent.query <NEW_LINE> if person_id is not None: <NEW_LINE> <INDENT> query = query.filter(TimeSpent.person_id == person_id) <NEW_LINE> <DEDENT> if year is not None: <NEW_LINE> <INDENT> query = query.filter( TimeSpent.date.between("... | Return all time spents for given year. | 625941e1009cb60464c63751 |
def set_s3_config(access_key_id=None, secret_access_key=None, bucket=None, region=None): <NEW_LINE> <INDENT> if access_key_id and not secret_access_key: <NEW_LINE> <INDENT> secret_access_key = getpass.getpass(prompt="Enter AWS Secret Access Key: ") <NEW_LINE> <DEDENT> data = {} <NEW_LINE> if access_key_id: <NEW_LINE> <... | Set AWS S3 configuration for pushing and pulling databases to and from
S3.
See http://qrok.it/h/dbs3 to learn more.
Credentials are encrypted at rest and never leave your deployment.
Parameters
----------
access_key_id : str, optional
AWS access key ID
secret_access_key : str, optional
AWS secret access key... | 625941e13c8af77a43ae3b46 |
def add(self, book, quantity=1, update_quantity=False): <NEW_LINE> <INDENT> book_id = str(book.id) <NEW_LINE> if book_id not in self.cart.keys(): <NEW_LINE> <INDENT> self.cart[book_id] = { 'quantity': 0, 'price': book.price } <NEW_LINE> <DEDENT> if update_quantity: <NEW_LINE> <INDENT> self.cart[book_id]['quantity'] = q... | add a book to cart or update its quantity. | 625941e12ae34c7f2600d4d3 |
def deserialize(self, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> end = 0 <NEW_LINE> start = end <NEW_LINE> end += 4 <NEW_LINE> (length,) = _struct_I.unpack(str[start:end]) <NEW_LINE> start = end <NEW_LINE> end += length <NEW_LINE> if python3: <NEW_LINE> <INDENT> self.error = str[start:end].decode('utf-8') <NEW_... | unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str`` | 625941e124f1403a92600f05 |
def get_gmap_config_file(): <NEW_LINE> <INDENT> gmap_config_file = '{0}/{1}-config.txt'.format(xlib.get_config_dir(), xlib.get_gmap_code()) <NEW_LINE> return gmap_config_file | Get the GMAP config file path. | 625941e1be7bc26dc91cd99b |
def setState(self, state): <NEW_LINE> <INDENT> super(EnumFieldWidget, self).setState(state) <NEW_LINE> editable = state.get('editable') <NEW_LINE> if editable is not None: <NEW_LINE> <INDENT> self.widget().setEditable(editable) | Set the current state with support for editable.
:type state: dict | 625941e160cbc95b062c68e5 |
def fitTUV(xdata,ydata): <NEW_LINE> <INDENT> import numpy as np <NEW_LINE> import collections <NEW_LINE> from scipy.optimize import leastsq <NEW_LINE> from datfcn import order <NEW_LINE> Param=collections.namedtuple('Param','l m n') <NEW_LINE> p_guess=Param(l=ydata[0]*np.exp(-0.8),m=0.8,n=0.25) <NEW_LINE> p,cov,infodic... | Function fitTUV
===============
Purpose:
Curve of TUV data to parameterisation for photolysis in MCM.
j = l*(cos(x))^m*exp(-n*sec(x))
Variables:
I/O:
xdata,ydata: x-,y-data for curve fit (sza and j values)
p: optimised parameters from least square fit
cov: covari... | 625941e176d4e153a657eed4 |
def test_list_scopes(self): <NEW_LINE> <INDENT> for scope in self.scopes: <NEW_LINE> <INDENT> add_scope(scope=scope, account='jdoe') <NEW_LINE> <DEDENT> scopes = get_scopes(account='jdoe') <NEW_LINE> for s in scopes: <NEW_LINE> <INDENT> assert_in(s, scopes) | SCOPE (CORE): List scopes | 625941e1596a897236089e5e |
def partition_spanning_tree( G, minimum=True, weight="weight", partition="partition", ignore_nan=False ): <NEW_LINE> <INDENT> edges = kruskal_mst_edges( G, minimum, weight, keys=True, data=True, ignore_nan=ignore_nan, partition=partition, ) <NEW_LINE> T = G.__class__() <NEW_LINE> T.graph.update(G.graph) <NEW_LINE> T.ad... | Find a spanning tree while respecting a partition of edges.
Edges can be flagged as either `INLCUDED` which are required to be in the
returned tree, `EXCLUDED`, which cannot be in the returned tree and `OPEN`.
This is used in the SpanningTreeIterator to create new partitions following
the algorithm of Sörensen and Ja... | 625941e123e79379d52ee901 |
def Clean_Maze(maze): <NEW_LINE> <INDENT> n = len( maze[0,:] ) <NEW_LINE> for i in np.arange(n): <NEW_LINE> <INDENT> for j in np.arange(n): <NEW_LINE> <INDENT> maze[i,j] = int( maze[i,j] - 20 ) | 625941e121a7993f00bc8098 | |
def get_next_token(self): <NEW_LINE> <INDENT> while self.current_char is not None: <NEW_LINE> <INDENT> if self.current_char.isspace(): <NEW_LINE> <INDENT> self.skip_whitespace() <NEW_LINE> continue <NEW_LINE> <DEDENT> if self.current_char.isdigit(): <NEW_LINE> <INDENT> return Token(INTEGER, self.integer()) <NEW_LINE> <... | Lexical analyzer (also known as scanner or tokenizer)
This method is responsible for breaking a sentence
apart into tokens. One token at a time. | 625941e13eb6a72ae02ec888 |
def accuracy(output, target, topk=(1,)): <NEW_LINE> <INDENT> with torch.no_grad(): <NEW_LINE> <INDENT> maxk = max(topk) <NEW_LINE> batchSize = target.size(0) <NEW_LINE> _, pred = output.topk(maxk, 1, True, True) <NEW_LINE> pred = pred.t() <NEW_LINE> correct = pred.eq(target.view(1, -1).expand_as(pred)) <NEW_LINE> res =... | Computes the accuracy over the k top predictions for the specified values of k | 625941e1aad79263cf390de9 |
def rot13(string: str) -> Union[str, None]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return "".join( [ chr(ord(n) + (13 if "Z" < n < "n" or n < "N" else -13)) if ("a" <= n <= "z" or "A" <= n <= "Z") else n for n in string ] ) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return None | Rot13 for only A-Z and a-z characters | 625941e126068e7796caf086 |
def arcTo(self, point1, point2, radius): <NEW_LINE> <INDENT> self._path.appendBezierPathWithArcFromPoint_toPoint_radius_(point1, point2, radius) | Arc defined by a circle inscribed inside the angle specified by three points:
the current point, `point1`, and `point2`. The arc is drawn between the two points of the circle that are tangent to the two legs of the angle. | 625941e1ec188e330fd5ab3a |
def sonar_calibrate(self, sonar_v=None): <NEW_LINE> <INDENT> max_invalid_rate = 0.9 <NEW_LINE> if sonar_v: <NEW_LINE> <INDENT> logging.warning("Hard code sonar reading!") <NEW_LINE> sonar_distance = sonar_v <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> time.sleep(0.1) <NEW_LINE> try: <NEW_LINE> <INDENT> sonar_distance ... | Return True when sucessful, False otherwise | 625941e1d53ae8145f87a60c |
def test_load_corpus_from_file(): <NEW_LINE> <INDENT> file_dict1 = corpus.get_files_in_train_and_test_sets() <NEW_LINE> fName = '{}/corpus.json'.format(data_dir) <NEW_LINE> corpus.save(fName) <NEW_LINE> corpus2 = CPTCorpus.load(fName, topicLines=[0], opinionLines=[1]) <NEW_LINE> file_dict2 = corpus2.get_files_in_train_... | Test load corpus from json file | 625941e1d7e4931a7ee9e2c1 |
def get_additional_fields(self): <NEW_LINE> <INDENT> additional_fields = {} <NEW_LINE> stored_fields = self.get_stored_fields().keys() <NEW_LINE> for key, value in self.object.get_additional_fields().items(): <NEW_LINE> <INDENT> if key not in stored_fields: <NEW_LINE> <INDENT> additional_fields[key] = value <NEW_LINE> ... | Find all fields in the Haystack SearchResult which have not already
appeared in the stored fields.
:return: dictionary of field names and values. | 625941e1bd1bec0571d909d1 |
def Reset(self): <NEW_LINE> <INDENT> pass | Reset(self: ConnectorSetIterator)
Bring the iterator back to the start of the set. | 625941e1ec188e330fd5ab3b |
def begin_create_or_update( self, resource_group_name, dscp_configuration_name, parameters, **kwargs ): <NEW_LINE> <INDENT> polling = kwargs.pop('polling', True) <NEW_LINE> cls = kwargs.pop('cls', None) <NEW_LINE> lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) <NEW_LINE> cont_token = kwargs... | Creates or updates a DSCP Configuration.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param dscp_configuration_name: The name of the resource.
:type dscp_configuration_name: str
:param parameters: Parameters supplied to the create or update dscp configuration operation.
:... | 625941e150485f2cf553d13e |
def discovered(self): <NEW_LINE> <INDENT> return time() - self.last_discovery < self.discovery_timeout | Returns boolean indicating if device was discovered lately. | 625941e1e5267d203edce03b |
def storeTree(inputTree,fileName): <NEW_LINE> <INDENT> with open(fileName,'wb') as fw: <NEW_LINE> <INDENT> pickle.dump(inputTree,fw) | 保存决策树
:param inputTree: 已经生成的决策树
:param fileName:存储文件名
:return: | 625941e1c432627299f04feb |
def get_image_hist(self, img_id): <NEW_LINE> <INDENT> img_ind = self.id_ind_map[img_id] <NEW_LINE> color_hist = self.hists_reduced[img_ind, :] <NEW_LINE> return color_hist | Return the smoothed image histogram of the image with the given id.
Parameters
----------
img_id : string
Returns
-------
color_hist : ndarray | 625941e18da39b475bd6531a |
def _node_betweenness(G,source,cutoff=False,normalized=True,weight=None): <NEW_LINE> <INDENT> if weight is None: <NEW_LINE> <INDENT> (pred,length)=nx.predecessor(G,source,cutoff=cutoff,return_seen=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if weight is True: weight='weight' <NEW_LINE> (pred,length)=nx.dijkstra... | Node betweenness helper:
see betweenness_centrality for what you probably want.
This actually computes "load" and not betweenness.
See https://networkx.lanl.gov/ticket/103
This calculates the load of each node for paths from a single source.
(The fraction of number of shortests paths from source that go
through each ... | 625941e18a349b6b435e8515 |
def build_page4(self): <NEW_LINE> <INDENT> label = Gtk.Label(_("Please check that the information is correct, " "do not worry if you don't understand the detail " "of the error information. Just make sure that it " "does not contain anything that you do not want " "to be sent to the developers.")) <NEW_LINE> label.set_... | Build the bug report summary page. | 625941e176e4537e8c351a18 |
def get_first_commit_id(): <NEW_LINE> <INDENT> cmd = ['git', 'log', '--pretty=format:%H', '--reverse'] <NEW_LINE> out = subprocess.check_output(cmd).decode('unicode_escape') <NEW_LINE> return out.strip().split()[0] | Return the first commit hash.
| 625941e1b57a9660fec33c2c |
@aggregations.command('process') <NEW_LINE> @aggr_arg <NEW_LINE> @click.option('--start-date', callback=_verify_date) <NEW_LINE> @click.option('--end-date', callback=_verify_date) <NEW_LINE> @click.option('--update-bookmark', '-b', is_flag=True) <NEW_LINE> @click.option('--eager', '-e', is_flag=True) <NEW_LINE> @with_a... | Process stats aggregations. | 625941e1091ae356686672fb |
def run(self): <NEW_LINE> <INDENT> literal = super(AllowCaptionMixin, self).run()[0] <NEW_LINE> linespec = self.options.get('emphasize-lines') <NEW_LINE> if linespec: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> nlines = len(self.content) <NEW_LINE> hl_lines = [x + 1 for x in parselinenos(linespec, nlines)] <NEW_LINE> ... | Call the original directive run, then add in caption, if applicable. | 625941e16e29344779a629b3 |
def getStream(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ds = DownloadStream(file(self._sourceFile, 'rb'), self.getMIMEType(), self.getFilename()) <NEW_LINE> length = str( getsize(self._sourceFile) ) <NEW_LINE> ds.setParameter('Content-Length', length) <NEW_LINE> ds.setCacheTime(self._cacheTime) <NEW_LINE> ret... | Gets the resource as stream.
@see: L{IApplicationResource.getStream} | 625941e18a43f66fc4b54404 |
def get_robust_fluxes(data_dict: dict, rxn_order: list = None) -> pd.DataFrame: <NEW_LINE> <INDENT> fluxes_df = pd.DataFrame() <NEW_LINE> stoic_balanced, rxn_list = _get_balanced_s_matrix(data_dict) <NEW_LINE> meas_rates_mean, meas_rates_std = _get_meas_rates(data_dict, rxn_list) <NEW_LINE> v_mean, v_std = _compute_rob... | Given a dictionary representing a GRASP input file, it calculates the robust fluxes (almost) as in GRASP,
unless the system is not fully determined.
Args:
data_dict: path to the GRASP input file
rxn_order: a list with the reactions order (optional)
Returns:
fluxes_df: dataframe with flux mean and std valu... | 625941e131939e2706e4d207 |
def _getModifiedProfileNameMarkup(self, name): <NEW_LINE> <INDENT> return "* " + name | Convert the given name into a markup representing that the
corresponding profile has been modified since downloaded.
This implementation puts an asterisk in front of the name. | 625941e1a8ecb033257d346e |
@contextlib.contextmanager <NEW_LINE> def mock_p4(): <NEW_LINE> <INDENT> with nimp.tests.utils.mock_filesystem(): <NEW_LINE> <INDENT> p4_mock = P4Mock() <NEW_LINE> with nimp.tests.utils.mock_capture_process_output(p4_mock): <NEW_LINE> <INDENT> yield p4_mock | Returns a p4 mock | 625941e1bf627c535bc13572 |
def show_contextual_menu(event): <NEW_LINE> <INDENT> if tree.focus(): <NEW_LINE> <INDENT> menu.post(event.x + 65, event.y) | Handle popping of contextual menu. | 625941e126068e7796caf087 |
def registration_function_for_global_scope(self): <NEW_LINE> <INDENT> return self.registration_function_for_scope(GLOBAL_SCOPE) | Returns a function for registering argparse args on the global scope. | 625941e116aa5153ce36281a |
def test_crawl_data(): <NEW_LINE> <INDENT> assert t.sub("crawl_data") | 测试正式发布结果
:return: | 625941e1f7d966606f6aa3ac |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'trial_blog.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you s... | Run administrative tasks. | 625941e1fff4ab517eb2f7e1 |
def Convert(imgname1,imgname2,cleanafter=False): <NEW_LINE> <INDENT> os.system('convert %s %s' % (imgname1,imgname2)) <NEW_LINE> if cleanafter : os.system('rm %s' % imgname1) <NEW_LINE> return None | Converts formats of images | 625941e1d164cc61757830f2 |
def compute(self): <NEW_LINE> <INDENT> ip_recs = self._ip_recs <NEW_LINE> for cur_ip_rec in ip_recs: <NEW_LINE> <INDENT> total_size = 0 <NEW_LINE> for payload in ip_recs[cur_ip_rec]: <NEW_LINE> <INDENT> total_size += int(payload.get_payload_size()) <NEW_LINE> <DEDENT> self.append_feature(cur_ip_rec, (total_size > 0) an... | retrieve the ip dictionary and compute the average for each
ip to determine the change rate of UA per IP. | 625941e1796e427e537b096b |
def load(self, occupant): <NEW_LINE> <INDENT> self.__occupant = occupant <NEW_LINE> self.__max_speed = occupant.get_speed() | Loads the script with an occupant. This must always be called before a script can be run
Args:
occupant: the occupant that is taking over the script | 625941e1d10714528d60008a |
def extra_condition(): <NEW_LINE> <INDENT> b = python_input.default_buffer <NEW_LINE> return ( python_input.show_meta_enter_message and (not b.document.is_cursor_at_the_end or python_input.accept_input_on_enter is None) and '\n' in b.text) | Only show when... | 625941e10a50d4780f667238 |
def getBottomFlangeMidPlaneContourPoints(self, org, extrusionVDir, weakAxisVDir): <NEW_LINE> <INDENT> halfB= self.getFlangeWidth()/2.0 <NEW_LINE> halfH= (self.h()-self.getFlangeThickness())/2.0 <NEW_LINE> bottom= -halfH <NEW_LINE> strongAxisVDir= extrusionVDir.cross(weakAxisVDir).normalized() <NEW_LINE> v= bottom*weakA... | Return the bottom flange contour points at its mid plane.
:param org: origin point.
:param extrusionVDir: extrusion direction vector.
:param weakAxisVDir: direction of the weak axis. | 625941e16aa9bd52df037148 |
def p_statement_rule9(p): <NEW_LINE> <INDENT> print("scanf(\"%c\",&"+str(p[3])+");") | statement : SCAN CHARACTER VAR | 625941e1cc40096d61595cf2 |
def test_str_method(self): <NEW_LINE> <INDENT> self.assertEqual(str(self.bucketlist), "BucketList : {}".format(self.name)) | Test string representation of a bucketlist | 625941e1097d151d1a2231fa |
def onFaceDetected(self, *_args): <NEW_LINE> <INDENT> memory.unsubscribeToEvent("FaceDetected", "HumanGreeter") <NEW_LINE> self.tts.setLanguage("Chinese") <NEW_LINE> self.tts.say("你好,我是NAO,我来自山东大学工程训练中心") <NEW_LINE> memory.subscribeToEvent("FaceDetected", "HumanGreeter", "onFaceDetected") | This will be called each time a face is
detected. | 625941e121bff66bcd684cf2 |
def acquire(self): <NEW_LINE> <INDENT> if VERBOSE: <NEW_LINE> <INDENT> util.SMlog("rbdsr_lock.Lock.acquire") <NEW_LINE> <DEDENT> if not self._trylock(): <NEW_LINE> <INDENT> _locker = self._get_srlocker() <NEW_LINE> if VERBOSE: <NEW_LINE> <INDENT> util.SMlog("rbdsr_lock: Failed to lock on first attempt, blocked by %s...... | Blocking lock aquisition, with warnings. | 625941e176d4e153a657eed5 |
def __setattr__(self, label, value): <NEW_LINE> <INDENT> raise AttributeError('Direct setting of attributes not allowed. To change an element e, try e.updateWith() instead.') | Raises exception when trying to set attributes directly.Elements are to be changed using "updateWith()". | 625941e15fdd1c0f98dc05d8 |
def testMaxScore_Bits(self): <NEW_LINE> <INDENT> mockOpener = mock_open(read_data=( dumps(PARAMS) + '\n' + dumps(RECORD0) + '\n' + dumps(RECORD1) + '\n' + dumps(RECORD2) + '\n' + dumps(RECORD3) + '\n')) <NEW_LINE> with patch.object(builtins, 'open', mockOpener): <NEW_LINE> <INDENT> reads = Reads() <NEW_LINE> reads.add(... | Sorting on max score must work when scores are bit scores, including a
secondary sort on title. | 625941e138b623060ff0b190 |
def exists(self, identifier): <NEW_LINE> <INDENT> matches = list( filter( lambda x: getattr(x, self.key_field) == identifier, self.session_values)) <NEW_LINE> return len(matches) > 0 | Check if exists a document with the identifier provided
Args:
identifier (any type): identifier value
Returns:
bool: True if document exists False if not | 625941e182261d6c526ab848 |
def create_links(self, links, ports): <NEW_LINE> <INDENT> first_pass = {} <NEW_LINE> for (src_port_flat, dst_port_flat) in links: <NEW_LINE> <INDENT> src_dpid = src_port_flat / self.SWITCH_ID_MULTIPLIER <NEW_LINE> dst_dpid = dst_port_flat / self.SWITCH_ID_MULTIPLIER <NEW_LINE> src_port = src_port_flat % self.PORT_TYPE_... | Generate dummy switches
For example, interface A1 connects to B1 and C1 at the same time. Since
Mininet uses veth, which supports point to point communication only,
we need to manually create dummy switches
@param links link info from the file
@param ports port info from the file | 625941e1236d856c2ad44b82 |
def _tasks_from_config(self, cfg): <NEW_LINE> <INDENT> tasks = ("bbox",) <NEW_LINE> if cfg.MODEL.MASK_ON: <NEW_LINE> <INDENT> tasks = tasks + ("segm",) <NEW_LINE> <DEDENT> return tasks | Returns:
tuple[str]: tasks that can be evaluated under the given configuration. | 625941e1925a0f43d254a21d |
def test_queued_restart_multiple_queue(self): <NEW_LINE> <INDENT> qname = ['workq1', 'workq2'] <NEW_LINE> for que in qname: <NEW_LINE> <INDENT> a = { 'queue_type': 'Execution', 'enabled': 'True', 'started': 'True'} <NEW_LINE> self.server.manager(MGR_CMD_CREATE, QUEUE, a, que, expect=True) <NEW_LINE> <DEDENT> q1_attr = ... | The test case verifies that the queued_count reported in the output
of qstat -Bf is equal to total_jobs - running jobs, even after the
server is restart.
(each job uses ncpus=1) | 625941e1c432627299f04fec |
def __init__(self, qdb, *args, include_flows=None, quell_locations=False): <NEW_LINE> <INDENT> print('!!NOTE: _far_headings must be set') <NEW_LINE> self._qdb = qdb <NEW_LINE> if include_flows is not None: <NEW_LINE> <INDENT> include_fbs = set([qdb.f_index(qdb.parse_flow(x)[0]) for x in include_flows]) <NEW_LINE> def c... | :param qdb: Mandatory Qdb for resolving flowables and compartments
:param args: supply process ref (exchanges), quantity ref (cfs), or lcia result (flows)
:param include_flows: either None (include all flows) or an iterable of flowables to include
:param quell_locations: for characterizations, suppress reporting of lo... | 625941e18e71fb1e9831db4b |
def check_cluster_version_operator_health(self): <NEW_LINE> <INDENT> logger.info("Check health of ClusterVersion operator") <NEW_LINE> is_cluster_version_operator_healthy = True <NEW_LINE> cluster_version_response = self.ocp_cluster_version.get_cluster_version() <NEW_LINE> if cluster_version_response["metadata"]["name"... | Check ClusterVersion operator health
:return: (boolean) Return | 625941e18da39b475bd6531b |
def lxc_list(): <NEW_LINE> <INDENT> out, _, _ = call(['sudo', 'lxc-ls']) <NEW_LINE> return out.strip().split() | Return the list of LXC containers | 625941e17d847024c06be662 |
def get_final_aggregation(thing_list, operation): <NEW_LINE> <INDENT> if operation != "COUNT" and len(thing_list) == 0: <NEW_LINE> <INDENT> return {"operation": operation, "result": "unknown"} <NEW_LINE> <DEDENT> result = {"operation": operation} <NEW_LINE> if operation == "COUNT": <NEW_LINE> <INDENT> result["result"] ... | Generate the HTTP response content according to the operation and the result thing list
Args:
thing_list(list): the list of thing description
operation(str): one of the five aggregation operations
Returns:
dict: formatted result containing the aggregation data | 625941e10a366e3fb873ebc0 |
def __init__(self, name, execObj, modules=[], pythonExec='python'): <NEW_LINE> <INDENT> self.name=name <NEW_LINE> self.execObj=execObj <NEW_LINE> self.submitted=False <NEW_LINE> self.pythonExec=pythonExec <NEW_LINE> self.modules=modules | name must be unique, execObj must be pickle_able and have a run method
pythonExec is the python command to use e.g. phenix.python | 625941e12ae34c7f2600d4d4 |
@add_arg_scope <NEW_LINE> def dense_sum_conv_blocks(inputs, n, ch_dim, k_size, mode: str = '2d', layer_norm: bool = True, outputs_collections=None, scope=None): <NEW_LINE> <INDENT> with tf.variable_scope( scope, default_name='densesum_conv{}_blks'.format(mode)) as sc: <NEW_LINE> <INDENT> embed = inputs <NEW_LINE> pre_e... | Dense-sum blocks with 1D or 2D convolutional layers.
Args:
inputs:
n: Number of blocks. Each blocks has exactly one fully connected layer.
ch_dim: output channel dim.
k_size: int or tuple, kernel size
mode: str, '1d' or '2d'
layer_norm: Whether to use layer norm
outputs_collections:
scope:
Returns:
... | 625941e163b5f9789fde7489 |
def fastcat_creation_SQL(self, engine="MEMORY"): <NEW_LINE> <INDENT> tbname = "fastcat" <NEW_LINE> if engine=="MYISAM": <NEW_LINE> <INDENT> tbname = "fastcat_" <NEW_LINE> <DEDENT> fastFieldsCreateList = [ "bookid MEDIUMINT UNSIGNED NOT NULL, PRIMARY KEY (bookid)", "nwords MEDIUMINT UNSIGNED NOT NULL" ] <NEW_LINE> fastF... | Generate SQL to create the fastcat (memory) and fastcat_ (on-disk) tables. | 625941e1099cdd3c635f0ffd |
def inPhaseUse(iophs): <NEW_LINE> <INDENT> return ((~iophs[:, :, 0].mask).sum()/iophs[:, :, 0].size) | Number of fraction of rays that were dropped | 625941e1dd821e528d63b549 |
def show_toolbar(request): <NEW_LINE> <INDENT> return bool(DEBUG) | Determine whether to show the toolbar on a given page. | 625941e1a79ad161976cc4e8 |
def getRecentProjectsFolder(defAct): <NEW_LINE> <INDENT> recentProjectTuple = defAct.recentProjectsData.getMostRecent() <NEW_LINE> if recentProjectTuple is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> [_, mostRecentProjectPath] = recentProjectTuple <NEW_LINE> return os.path.dirname(mos... | Get the folder containing (!) the most recent project.
defAct: DefaultActions to use
returns: folder path or None | 625941e126238365f5f0f216 |
def __init__(self, module, name, file, lineno, signature='', separator=',', modifierType=General, annotation=""): <NEW_LINE> <INDENT> ClbrBase.__init__(self, module, name, file, lineno) <NEW_LINE> self.parameters = [e.strip() for e in signature.split(separator)] <NEW_LINE> self.modifier = modifierType <NEW_LINE> self.a... | Constructor
@param module name of the module containing this function
@param name name of this function
@param file filename containing this class
@param lineno linenumber of the class definition
@param signature parameterlist of the method
@param separator string separating the parameters
@param modifierType type of ... | 625941e1a4f1c619b28b03d4 |
def containsNearbyDuplicate(self, nums, k): <NEW_LINE> <INDENT> if not nums: return False <NEW_LINE> dic = {} <NEW_LINE> for i,n in enumerate(nums): <NEW_LINE> <INDENT> if n not in dic: dic[n] = [i] <NEW_LINE> else: dic[n].append(i) <NEW_LINE> <DEDENT> for key in dic: <NEW_LINE> <INDENT> if len(dic[key]) != 1: <NEW_LIN... | :type nums: List[int]
:type k: int
:rtype: bool | 625941e19b70327d1c4e117a |
def generate_robust_pifs_pixel_list(candidate_data, reference_data, parameters=DEFAULT_ROBUST_OPTIONS): <NEW_LINE> <INDENT> logging.info('PIF: Pseudo invariant feature generation is using: ' 'Filtering using a robust fit.') <NEW_LINE> gain, offset = robust.fit(candidate_data, reference_data) <NEW_LINE> return filtering... | Performs a robust fit to the valid pixels and filters according
to the distance from the fit line.
:param list candidate_band: A list of valid candidate data
:param list reference_band: A list of coincident valid reference data
:param robust_options parameters: Method specific parameters. Currently:
threshold (flo... | 625941e1097d151d1a2231fb |
def incr(self,key): <NEW_LINE> <INDENT> self._redis.incr(key) | 给键对应的值增加1,不存在会自动创建,并且值为1 | 625941e1baa26c4b54cb14bf |
def get_lift(data_file, n_groups, output_file, y_name='y', score_name='score'): <NEW_LINE> <INDENT> data = pd.read_table(data_file, sep='\t', na_values=na_values) <NEW_LINE> data_sorted = data.sort_values(by=score_name, axis=0, ascending=False) <NEW_LINE> n_rcds = data_sorted.shape[0] <NEW_LINE> n_rcd_p_group = int(flo... | data_file: 要带表头, 分割 | 625941e1b5575c28eb68e3a7 |
def __init__(self, game_pk=None, link=None, game_type=None, season=None, game_date=None, status=None, teams=None, venue=None, content=None): <NEW_LINE> <INDENT> self._game_pk = None <NEW_LINE> self._link = None <NEW_LINE> self._game_type = None <NEW_LINE> self._season = None <NEW_LINE> self._game_date = None <NEW_LINE>... | TeamNextGameScheduleGames - a model defined in OpenAPI | 625941e157b8e32f52483841 |
def init_gui(self): <NEW_LINE> <INDENT> vbox = QtGui.QVBoxLayout() <NEW_LINE> hbox = QtGui.QHBoxLayout() <NEW_LINE> self.txt_file_path = pg.QtGui.QLineEdit() <NEW_LINE> self.txt_file_path.textChanged[str].connect(self.set_file_path) <NEW_LINE> self.setup_time_series_charts() <NEW_LINE> self.setup_histogram_chart() <NEW... | General GUI setup, if it was more complex we might want to use a
ui file built in Qt Creator. | 625941e1d268445f265b5212 |
def run_preprocessing_pipeline(order_hist): <NEW_LINE> <INDENT> customer = User(id=1, first_name="John", meal_plan="Balanced", postcode="SW18") <NEW_LINE> suggestions = [ Recipe( recipe_id="1", food_group="Pork", calories="150", carbs="23", fat="50", protein="400", cooking_time="25", title="Meal 1", description="descri... | this function wrapper should only used for testing purposes. Instead of running only functions required for delta12 calculation as in get_delta12(order_hist),
it runs entire preprocessing pipeline generating input for the recipe recommender. For simplicity, I removed all unnecesary stuff and made a wrapper around
propr... | 625941e17b180e01f3dc4b9a |
def create_neighbor(): <NEW_LINE> <INDENT> copy = np.copy(puzzle) <NEW_LINE> pair1, pair2 = same_box_pair() <NEW_LINE> temp = copy[pair1[0], pair1[1]] <NEW_LINE> copy[pair1[0], pair1[1]] = copy[pair2[0], pair2[1]] <NEW_LINE> copy[pair2[0], pair2[1]] = temp <NEW_LINE> return copy | Randomly changes cells within the same box in puzzle if cells were initially blank. | 625941e1a05bb46b383ecbc2 |
def sanitize_raster(base_raster_path, target_raster_path): <NEW_LINE> <INDENT> raster_info = geoprocessing.get_raster_info( base_raster_path) <NEW_LINE> fill_value = raster_info['nodata'][0] <NEW_LINE> if fill_value is None: <NEW_LINE> <INDENT> fill_value = 0 <NEW_LINE> <DEDENT> geoprocessing.raster_calculator( [(base_... | Scrub base raster of any non-finite values to nodata.
If noodata is None then scrub to 0.
Args:
base_raster_path (str): path to base raster
target_raster_path (str): path to target raster
Return:
None. | 625941e1187af65679ca54c4 |
def do_project(self, line): <NEW_LINE> <INDENT> if line == "": <NEW_LINE> <INDENT> jprint(self.project) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.project = line <NEW_LINE> self.project_dirs = self._has_project() <NEW_LINE> jprint(self.project_dirs) | Project can be the whole loc_data name or a pattern
eg. J0230 - GHD_Apache Phoenix South_1
or j0230* | 625941e1ac7a0e7691ed4469 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.