code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def solve_nos1(fvind, mo_energy, mo_occ, h1, max_cycle=20, tol=1e-9, hermi=False, verbose=logger.WARN): <NEW_LINE> <INDENT> log = logger.new_logger(verbose=verbose) <NEW_LINE> t0 = (time.clock(), time.time()) <NEW_LINE> occidxa = mo_occ[0] > 0 <NEW_LINE> occidxb = mo_occ[1] > 0 <NEW_LINE> viridxa = ~occidxa <NEW_LINE> ...
For field independent basis. First order overlap matrix is zero
625941f5046cf37aa974d375
def get_nas_volume_instance_detail_with_http_info(self, get_nas_volume_instance_detail_request, **kwargs): <NEW_LINE> <INDENT> all_params = ['get_nas_volume_instance_detail_request'] <NEW_LINE> all_params.append('async') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_conte...
get_nas_volume_instance_detail # noqa: E501 NAS볼륨인스턴스상세조회 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_nas_volume_instance_detail_with_http_info(get_nas_volume_instance_detail_request, async=True) >>> result = ...
625941f50fa83653e46575eb
def clusterize(self, error_rt=10.0, corr_shape_dist=DEFAULT_SHAPE_CORR, corr_int_dist=DEFAULT_INT_CORR): <NEW_LINE> <INDENT> rt_clusters = self.clusterize_by_rt(error_rt) <NEW_LINE> logging.info("Rt clustering done, nb clusters: {0}".format(len(rt_clusters))) <NEW_LINE> if rt_clusters is None: <NEW_LINE> <INDENT> loggi...
:param corr_shape_dist: :param corr_int_dist: :param error_rt:
625941f5e8904600ed9f256c
def get_trailer_id(movie_name): <NEW_LINE> <INDENT> youtube_search_name = movie_name.replace(" ", "+") + "+Trailer" <NEW_LINE> url = 'http://www.youtube.com/results?search_query=' + youtube_search_name <NEW_LINE> conn = urlopen(url) <NEW_LINE> content = conn.read() <NEW_LINE> conn.close() <NEW_LINE> soup_content = B.Be...
It finds the YouTube movie trailer ID from the given name. This function with do a YouTube query search based on the name of the movie plus the word "Trailer". Then I'll it assumes that the first thumbnail is best option, so it'll uses regular expression tp get the YouTube video ID. :param movie_name: (str) name of t...
625941f521bff66bcd684f81
def byteStringToHexifiedBitString(string): <NEW_LINE> <INDENT> return "'%s'H" % six.ensure_binary(string).hex()
Takes a string of bytes and returns a hex string representing those bytes for use with pyasn1.type.univ.BitString. It must be of the form "'<hex bytes>'H", where the trailing 'H' indicates to pyasn1 that the input is a hex string.
625941f57c178a314d6efa9f
def get(self): <NEW_LINE> <INDENT> def _set_criteria(): <NEW_LINE> <INDENT> for param in { _PARAM_DOCUMENT_ID, _PARAM_DOCUMENT_VERSION, _PARAM_ENCODING }: <NEW_LINE> <INDENT> setattr(self, param, self.get_argument(param).lower()) <NEW_LINE> <DEDENT> <DEDENT> def _set_data(): <NEW_LINE> <INDENT> self.doc = pyesdoc.archi...
HTTP GET handler.
625941f5e5267d203edce2c9
def login_verify(fn): <NEW_LINE> <INDENT> def inner(*args,**kwargs): <NEW_LINE> <INDENT> while 1: <NEW_LINE> <INDENT> if flag: <NEW_LINE> <INDENT> ret=fn(*args,**kwargs) <NEW_LINE> return ret <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> login() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return inner
这里是登录验证的装饰器 :param fn: 被装饰的函数 :return: inner
625941f55fc7496912cc3fb1
def save_model(self, request, obj: User, form, change): <NEW_LINE> <INDENT> if not change: <NEW_LINE> <INDENT> password = User.objects.make_random_password() <NEW_LINE> obj.set_password(password) <NEW_LINE> html_message = render_to_string("email/register.html", {"username": obj.get_full_name(), "password": password, "p...
Zapisuje użytkonika. Wysyłane jest jednocześnie zaproszenie do platformy Slack, email powitalny z hasłem oraz dodawany jest użytkownik do bazy radius. :param request: :param obj: :param form: :param change: True w wypadku, gdy użytkownik został zmodyfikowany, False, gdy jest tworzony. :return: :model:`usersystem.User`
625941f5cc0a2c11143dd4c6
def copy_to_output_destination(logfil, svg_out_filnam, out_dest): <NEW_LINE> <INDENT> logfil.write(lib_util.TimeStamp() + " Output without conversion: %s\n" % svg_out_filnam) <NEW_LINE> infil = open(svg_out_filnam, 'rb') <NEW_LINE> str_in_read = infil.read() <NEW_LINE> try: <NEW_LINE> <INDENT> nb_out = out_dest.write(s...
Copies a file to standard output.
625941f5a79ad161976cc77a
def item(self, index): <NEW_LINE> <INDENT> return Attribute()
Returns the specified attribute using an index into the collection. index : The index of the attribute within the collection to return. The first item in the collection has an index of 0. Returns the specified attribute or null if an invalid index was specified.
625941f55fc7496912cc3fb2
def to_native(self, data): <NEW_LINE> <INDENT> raise NotImplementedError( '{cls}.to_internal_value() must be implemented.'.format( cls=self.__class__.__name__ ) )
Transform the *incoming* primitive data into a native value.
625941f566656f66f7cbc7e1
def futures_recent_trades(self, **params): <NEW_LINE> <INDENT> return self._request_futures_api('get', 'trades', data=params)
Get recent trades (up to last 500). https://binance-docs.github.io/apidocs/futures/en/#recent-trades-list-market_data
625941f507d97122c4178ecf
def to_rectified(self, x, y): <NEW_LINE> <INDENT> return self._reproject(self.wcs_original, self.wcs_rectified, x, y)
Convert the input (x, y) positions from the original (unrectified) image to the rectified image. Parameters ---------- x, y: float or array-like of float The zero-index pixel coordinates in the original (unrectified) image. Returns ------- x, y: float or array-like The zero-index pixel coordinates in th...
625941f5b830903b967e9f38
def add_noise(x,n,snr=None): <NEW_LINE> <INDENT> xlen,nlen = len(x),len(n) <NEW_LINE> if xlen > nlen: <NEW_LINE> <INDENT> nn = np.tile(n,xlen/nlen+1) <NEW_LINE> nlen = len(nn) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nn = n <NEW_LINE> <DEDENT> if xlen < nlen: <NEW_LINE> <INDENT> nn = sample(nn,xlen,1)[0] <NEW_LINE...
Add user provided noise n with SNR=snr to signal x. SNR = 10log10(Signal Energy/Noise Energy) NE = SE/10**(SNR/10)
625941f523849d37ff7b36be
def upgrade_fw(self,file): <NEW_LINE> <INDENT> print('upgrade fw') <NEW_LINE> max_data_len = 240 <NEW_LINE> write_len = 0 <NEW_LINE> fw = open(file, 'rb').read() <NEW_LINE> fs_len = len(fw) <NEW_LINE> if not self.start_bootloader(): <NEW_LINE> <INDENT> print('Bootloader Start Failed') <NEW_LINE> return False <NEW_LINE>...
Upgrades firmware of connected 380 device to file provided in argument
625941f576d4e153a657f167
def __init__(self, code, parent, active=True, combined=False, on_exception=True): <NEW_LINE> <INDENT> self.code = code <NEW_LINE> self.active = active <NEW_LINE> self.combined = combined <NEW_LINE> self.on_exception = on_exception <NEW_LINE> self._parent = parent
Creates a new filter. :param str code: List of lines of code in the filter function. :param bool active: Is the filter active? :param bool combined : When True, the filter gets a list of items and returns a filtered list. Otherwise, the filter gets a single item and returns ``True`` or ``False``. :param bool o...
625941f53346ee7daa2b33a7
def zscore(series): <NEW_LINE> <INDENT> zs = (series-series.mean())/series.std(ddof=0) <NEW_LINE> return(zs)
Return the Z-score of a series
625941f5009cb60464c639e1
def parsehelper_395(self, node): <NEW_LINE> <INDENT> oldpos = self.pos <NEW_LINE> if not self.tok_test(tokenizer.T_NAME): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> tok = self.tok_peek() <NEW_LINE> self.pos = self.pos + 1 <NEW_LINE> return [astnode('NAME', tok)]
## subexpr ## 'NAME'
625941f5d18da76e23532b13
def nodes_iter(self, data=False): <NEW_LINE> <INDENT> if data: <NEW_LINE> <INDENT> return iter(self.node.items()) <NEW_LINE> <DEDENT> return iter(self.node)
Return an iterator over the nodes. Parameters ---------- data : boolean, optional (default=False) If False the iterator returns nodes. If True return a two-tuple of node and node data dictionary Returns ------- niter : iterator An iterator over nodes. If data=True the iterator gives two-tuples c...
625941f550812a4eaa59c94f
def test_new_user_with_spaces(testapp): <NEW_LINE> <INDENT> user = { 'username': 'dude mclovin', 'password': 'password', 'first_name': 'dude', 'last_name': 'asdasd', 'email': 'goyour@skdgmsk2', } <NEW_LINE> html = testapp.post('/registration', user, status=302).follow().html <NEW_LINE> assert 'goyour@skdgmsk2' in html....
Test that adding a new user via registration page.
625941f5287bf620b61d4094
def translate_cinder_exception(method): <NEW_LINE> <INDENT> @functools.wraps(method) <NEW_LINE> def wrapper(self, ctx, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> res = method(self, ctx, *args, **kwargs) <NEW_LINE> <DEDENT> except (cinder_exception.ConnectionError, keystone_exception.ConnectionError)...
Transforms a cinder exception but keeps its traceback intact.
625941f576e4537e8c351cad
def listen(self): <NEW_LINE> <INDENT> threading.Thread(target=self._prepare_driver).start() <NEW_LINE> self._prepare_logger()
Prepare components, initialize the application
625941f55f7d997b871750d2
def set_font_sizes(legend_font_size=None, tick_font_size=None, title_font_size=None, label_font_size=None): <NEW_LINE> <INDENT> if legend_font_size is not None: <NEW_LINE> <INDENT> global _LEGEND_FONT_SIZE <NEW_LINE> _LEGEND_FONT_SIZE = legend_font_size <NEW_LINE> <DEDENT> if tick_font_size is not None: <NEW_LINE> <IND...
Sets font sizes for legend, tick, title, or label. Any value that isn't given (or is given as None) remains the same.
625941f5aad79263cf39107f
def known_celestial(data): <NEW_LINE> <INDENT> for system in data['systems']: <NEW_LINE> <INDENT> celestials = {c['name'] for c in system['celestials']} <NEW_LINE> for location in system['locations']: <NEW_LINE> <INDENT> if location['celestial'] not in celestials: <NEW_LINE> <INDENT> raise v.error.Invalid('locations mu...
Ensures that any celestial mentioned in a location is present in the stellar system
625941f58e71fb1e9831dddb
def get_first_player(self) -> str: <NEW_LINE> <INDENT> return self._fp_choice
Returns the first player inputted
625941f53539df3088e2e980
def _get_tids_from_tags(self, tags, which='all'): <NEW_LINE> <INDENT> if tags in (None, ..., all): <NEW_LINE> <INDENT> return set(self.tensor_map) <NEW_LINE> <DEDENT> elif isinstance(tags, (Integral, slice)): <NEW_LINE> <INDENT> tags = self.sites2tags(tags) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tags = tags2set(...
Return the set of tensor ids that match ``tags``. Parameters ---------- tags : seq or str, str, None, ..., int, slice Tag specifier(s). which : {'all', 'any', '!all', '!any'} How to select based on the tags, if: - 'all': get ids of tensors matching all tags - 'any': get ids of tensors matching any tag...
625941f5956e5f7376d714a0
def __update_in_db(self, item): <NEW_LINE> <INDENT> item = self.__locate(item) <NEW_LINE> if not item: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not item.is_dir: <NEW_LINE> <INDENT> item = item.parent <NEW_LINE> if not item.is_dir: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> n_uuid, n_fi...
Push updating commit to Database for changes. Does not affect nonexistent nodes in Database. Otherwise please use __insert_in_db(). Operation would not be redirected to insertion because of recursive risks that could potentially damage and overflow the process.
625941f57b25080760e39a8a
@templatefunc("rstdoc(text, style)") <NEW_LINE> def rstdoc(context, mapping, args): <NEW_LINE> <INDENT> if len(args) != 2: <NEW_LINE> <INDENT> raise error.ParseError(_("rstdoc expects two arguments")) <NEW_LINE> <DEDENT> text = evalstring(context, mapping, args[0]) <NEW_LINE> style = evalstring(context, mapping, args[1...
Format reStructuredText.
625941f5d4950a0f3b08c97b
def fib_of_n(n): <NEW_LINE> <INDENT> if n<=1: <NEW_LINE> <INDENT> return n <NEW_LINE> <DEDENT> return fib_of_n(n-1) + fib_of_n(n-2)
return the fibonaci sequence
625941f526238365f5f0f4ab
def normangpos(ang): <NEW_LINE> <INDENT> return ang % (2 * np.pi)
ang is in radians returns in [0, 2pi]
625941f566673b3332b926c6
def message_handler(self, widget): <NEW_LINE> <INDENT> self.generate_message() <NEW_LINE> self.preview_message("clicked")
Generate Message then show it
625941f524f1403a92601195
def evaluationFunction(self, currentGameState, action): <NEW_LINE> <INDENT> successorGameState = currentGameState.generatePacmanSuccessor(action) <NEW_LINE> newPos = successorGameState.getPacmanPosition() <NEW_LINE> newFood = successorGameState.getFood() <NEW_LINE> newGhostStates = successorGameState.getGhostStates() <...
Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving...
625941f5d58c6744b4258292
def save_feature(self, df_feat, prefix, is_train=2): <NEW_LINE> <INDENT> utils.save_feature(df_feat=df_feat, is_train=is_train, target=self.target, ignore_list=self.ignore_list, prefix=prefix)
is_train: 0->train only, 1->test only, 2->train & test
625941f55510c4643540fa08
def CalcOptNEchoes(s): <NEW_LINE> <INDENT> s_sum = np.zeros(len(s)) <NEW_LINE> s_sum[0] = s[0] <NEW_LINE> TestFn = np.zeros(len(s)) <NEW_LINE> SNR_averaged = np.zeros(len(s)) <NEW_LINE> count = 1 <NEW_LINE> for n in range(2, len(s)+1): <NEW_LINE> <INDENT> SNR_averaged = np.sum(s[0:n] / np.sqrt(n)) <NEW_LINE> s_sum[n-1]...
Find out how many echoes in an echo train [s] have to be included into an averaging operation, such that the signal to noise (SNR) of the resulting averaged signal is maximized. Based on the formula shown in the supporting information of the [Doepfert et al. ChemPhysChem, 15(2), 261-264, 2014]
625941f5adb09d7d5db6cdc1
def save_config(config): <NEW_LINE> <INDENT> home_dir = os.path.expanduser("~") <NEW_LINE> config_fn = os.path.join(home_dir, '.smartthings_cli.json') <NEW_LINE> with open(config_fn, 'w') as json_file: <NEW_LINE> <INDENT> json.dump(config, json_file, indent=4)
Save script's configuration to a JSON file
625941f5d164cc6175783384
def execute_iud(self, sql, args=()): <NEW_LINE> <INDENT> conn = self.__pool.connection() <NEW_LINE> cur = conn.cursor() <NEW_LINE> count = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> result = cur.execute(sql, args) <NEW_LINE> conn.commit() <NEW_LINE> count = result <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDEN...
执行增删改语句 :param sql:sql语句,注意防注入 :param args:传入参数 :return:影响行数,mysql和sqlite有返回值
625941f5462c4b4f79d1dd04
def get_jids(): <NEW_LINE> <INDENT> ret = {} <NEW_LINE> client, path = _get_conn(__opts__) <NEW_LINE> items = client.get('/'.join((path, 'jobs'))) <NEW_LINE> for item in items.children: <NEW_LINE> <INDENT> if item.dir is True: <NEW_LINE> <INDENT> jid = six.text_type(item.key).split('/')[-1] <NEW_LINE> load = client.get...
Return a list of all job ids
625941f57c178a314d6efaa0
def get_embeddings(frame, detections, face_reid, landmarks_predictor): <NEW_LINE> <INDENT> rois = [] <NEW_LINE> embeddings = [] <NEW_LINE> for rect, _ in detections: <NEW_LINE> <INDENT> left, top, right, bottom = rect <NEW_LINE> rois.append(frame[top:bottom, left:right]) <NEW_LINE> <DEDENT> if rois: <NEW_LINE> <INDENT>...
Get embeddings for all detected faces on the frame
625941f556ac1b37e62647f7
def runTest(self): <NEW_LINE> <INDENT> db_con = database_utils.connect_database(self, utils.SERVER_GROUP, self.server_id, self.db_id) <NEW_LINE> if not db_con["info"] == "Database connected.": <NEW_LINE> <INDENT> raise Exception("Could not connect to database.") <NEW_LINE> <DEDENT> fdw_response = fdw_utils.verify_fdw(s...
This function will fetch foreign data wrapper present under test database.
625941f50a366e3fb873ee55
def view_stats(request): <NEW_LINE> <INDENT> countries = Country.all().filter("total >", 0).order("-total").fetch(250) <NEW_LINE> stats = DeveloperStats.all().order("-timestamp").get() <NEW_LINE> tags = TagStats.all().filter("developer_stats =", stats) <NEW_LINE> tags = tags.order("-total").fetch(20) <NEW_LINE> return ...
Show AppEngine general stats
625941f557b8e32f52483ad5
def get(self, term, location): <NEW_LINE> <INDENT> response = self.search(term, location=location) <NEW_LINE> businesses = response.get('businesses') <NEW_LINE> return businesses
Queries the API by the input values from the user and only return the top result. Args: term (str): The search term to query. location (str): The location of the business to query.
625941f53317a56b8693a27d
def show_data_complex(self): <NEW_LINE> <INDENT> if len(self.file_list) == 0: <NEW_LINE> <INDENT> popup.err_no_file() <NEW_LINE> return 1 <NEW_LINE> <DEDENT> my_app = structure.DataComplex(master=self.master, icon=self.octadist_icon) <NEW_LINE> for i in range(len(self.file_list)): <NEW_LINE> <INDENT> atom = self.atom_c...
Show info of input complex. See Also -------- octadist.src.structure.DataComplex : Show data summary of complex.
625941f5a219f33f34628f95
def MCOptionPrices(S0, K, T, rateCurve, sigma, t, checkpoints, samples, integrator): <NEW_LINE> <INDENT> S0 = float(S0) <NEW_LINE> K = float(K) <NEW_LINE> T = float(T) <NEW_LINE> sigma = float(sigma) <NEW_LINE> stock_path = MCStockPrices(S0, sigma, rateCurve, t, samples, integrator)[-1, :] <NEW_LINE> running_std = [] <...
:param S0: is the stock prices at time t0. :param K: is the strike price. :param T: is the expiration date of the European option. :param rateCurve: is an InterestRateCurve stored as a numpy array. :param sigma: is the constant volatility. :param t: is an array of xing times ti; i = 1 : : :N to...
625941f5f8510a7c17cf9d37
def _accessible_libraries_iter(user): <NEW_LINE> <INDENT> return (lib for lib in modulestore().get_libraries() if has_studio_read_access(user, lib.location.library_key))
List all libraries available to the logged in user by iterating through all libraries
625941f5e8904600ed9f256d
def cleanup_output_to_csv(infile, genelist_path, accession_pattern='(?P<accession>[A-Z _\d]*\.\d*)', logger=None): <NEW_LINE> <INDENT> import pandas as pd <NEW_LINE> print("cleaning up the csv output") <NEW_LINE> colnames = ["query_id", "subject_id", "identity_perc", "alignment_length", "mismatches", "gap_opens", "q_st...
given .tab from merge_blast_tab_outfiles, assign pretty column names,
625941f50a366e3fb873ee56
def rotate(self, matrix): <NEW_LINE> <INDENT> for i in range(len(matrix)): <NEW_LINE> <INDENT> for j in range(i, len(matrix[0])): <NEW_LINE> <INDENT> matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] <NEW_LINE> <DEDENT> <DEDENT> num_row, num_col = len(matrix), len(matrix[0]) <NEW_LINE> for i in range(len(matrix))...
:type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
625941f5d268445f265b54a4
def open(path, delimiter=None, mode='r', buffering=-1, encoding=None, errors=None, newline=None): <NEW_LINE> <INDENT> if not re.match('^[rbt]{1,3}$', mode): <NEW_LINE> <INDENT> raise ValueError('mode argument must be only have r, b, and t') <NEW_LINE> <DEDENT> compress_cls = get_compressed_cls(path) <NEW_LINE> if compr...
Additional entry point to Sequence which parses input files as defined by options. Path specifies what file to parse. If delimiter is not None, then the file is read in bulk then split on it. If it is None (the default), then the file is parsed as sequence of lines. The rest of the options are passed di...
625941f53d592f4c4ed1d691
def get_nn(embs, query_emb): <NEW_LINE> <INDENT> dist = np.linalg.norm(embs - query_emb, axis=1) <NEW_LINE> assert len(dist) == len(embs) <NEW_LINE> return np.argmin(dist), np.min(dist)
Get the nearest-neighbour, i.e. smallest l2 distance.
625941f50fa83653e46575ec
@pytest.fixture <NEW_LINE> def fake_session() -> HexpySession: <NEW_LINE> <INDENT> return HexpySession(token="test-token-00000")
Return fake HexpySession
625941f515fb5d323cde114f
def available_nets(self): <NEW_LINE> <INDENT> unfinished_nets = [] <NEW_LINE> comprehension = [unfinished_nets.append(net) for net in self.netlist if not net.finished] <NEW_LINE> return unfinished_nets
Returns all net objects in the netlist that aren't marked as finished.
625941f507f4c71912b11aba
def sentToVec(sentence): <NEW_LINE> <INDENT> sent_vec=np.zeros((1,numDimensions)) <NEW_LINE> flag=0 <NEW_LINE> for word in sentence: <NEW_LINE> <INDENT> word_vec=np.zeros((1,numDimensions)) <NEW_LINE> if word in model: <NEW_LINE> <INDENT> if word!=0: <NEW_LINE> <INDENT> word_vec=np.array(model[word]) <NEW_LINE> if flag...
Function: Transform a comment into a comment vector Parameters: sentence: a comment with normalized length E.g ['同意', '自我', '集体', '高潮', 0, 0, 0] Return: sent_vec: a sentence vector after words are transformed into word vectors E.g[ word1[v1,v2,v3,...,vd] ...
625941f545492302aab5e8ff
def asum(data, shape, axis=None): <NEW_LINE> <INDENT> newshape = [] <NEW_LINE> tmp = [] <NEW_LINE> if axis == None: <NEW_LINE> <INDENT> reduced_data = sum(data) <NEW_LINE> newshape = () <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for i in range(shape[axis]): <NEW_LINE> <INDENT> tmp.append(extract(data, shape, axis, i...
Sum of array elements over a given axis. Parameters ---------- data : list Input data. shape : tuple The shape of the input array axis : int, optional Axis along which the sums are computed. The default is to compute the sum of the flattened array. Returns ------- sum_along_axis : tuple (reduced_data,...
625941f54e4d5625662d4a04
def edit_copy(self, event=None): <NEW_LINE> <INDENT> self.text_area.event_generate("<Control-c>")
Ctrl+C
625941f5a79ad161976cc77b
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ToDo_Lists.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.
625941f501c39578d7e75471
def defineBoundary(self): <NEW_LINE> <INDENT> import numpy as np <NEW_LINE> originVec = np.array([self.surfaceCoords[0, 0], self.surfaceCoords[0, 1] - self.slopeHeight - self.maxDepth]) <NEW_LINE> extraCoords = np.array([ [self.surfaceCoords[-1, 0], self.surfaceCoords[-1, 1] - self.maxDepth], [self.surfaceCoords[0, 0],...
Method to obtain the coordinates of the boundary vertices of the slope and plot it if it is wanted. The origin of the coordinates is in the corner of the bottom with the back of the slope. The coordinates define a close polygon, ie, the first pair of coordinates is the same than the last one. Returns: ...
625941f50383005118ecfc15
def _parse_mode_text(self, start): <NEW_LINE> <INDENT> pos = start <NEW_LINE> while True: <NEW_LINE> <INDENT> pos = self._text.find("{", pos) <NEW_LINE> if pos == -1: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> tag = self._text[pos:pos + 2] <NEW_LINE> if tag in self._tag_map: <NEW_LINE> <INDENT> break <NEW_LINE> <DED...
Parse while in text mode.
625941f5ad47b63b2c50a5b5
def relational_operator(op): <NEW_LINE> <INDENT> def decorator(fn): <NEW_LINE> <INDENT> @operator(op) <NEW_LINE> @wraps(fn) <NEW_LINE> def wrapper(self, left, right): <NEW_LINE> <INDENT> left, right = self.relational_values(left, right) <NEW_LINE> return fn(self, left, right) <NEW_LINE> <DEDENT> return wrapper <NEW_LIN...
Wrap an operator method so that its values are both of the correct primitive type for a relational comparison.
625941f5283ffb24f3c55f2f
def next_batch_triplet(self, batch_size, shuffle=True): <NEW_LINE> <INDENT> start = self._index_in_epoch <NEW_LINE> if self._epochs_completed == 0 and start == 0: <NEW_LINE> <INDENT> self._epochs_completed += 1 <NEW_LINE> <DEDENT> if start + batch_size > self._num_train_patch: <NEW_LINE> <INDENT> self._epochs_completed...
Return the next `batch_size` examples from this data set.
625941f5c432627299f05280
def mysql_to_neo4j(bank_neo4j,scene_id,scene_name,topic_id,topic_name): <NEW_LINE> <INDENT> bank_neo4j.schema_init( scene_id=scene_id, scene_name=scene_name, topic_id=topic_id, topic_name=topic_name ) <NEW_LINE> STORIES_LIST = neo4j_datafrom(topic_id = topic_id, topic_name = topic_name) <NEW_LINE> BatchToNeo4j(data=STO...
数据存入neo4j中 :return:
625941f53539df3088e2e981
def get_pkgdir(root=None): <NEW_LINE> <INDENT> return os.path.join(get_local_site_pkgs(root),'rsf')
Return directory of the RSF Python package
625941f507f4c71912b11abb
def get_upcoming(): <NEW_LINE> <INDENT> season_data = json.loads(fetch_url(config.SEASONS_URL, request_token=True)) <NEW_LINE> current_season = season_data.get('currentSeasonId') <NEW_LINE> current_round = None <NEW_LINE> for s in season_data.get('seasons'): <NEW_LINE> <INDENT> if s.get('id') == current_season: <NEW_LI...
Make a dummy file list for users to see upcoming matches/times
625941f5d486a94d0b98e77c
def __setitem__( self, key: str, value: typing.Any, skip_on_error: bool=False, explicit: bool=True ) -> None: <NEW_LINE> <INDENT> if self.is_known_property(key, explicit=explicit) is False: <NEW_LINE> <INDENT> if "jail" in dir(self): <NEW_LINE> <INDENT> _jail = self.jail <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _j...
Set a configuration value.
625941f53617ad0b5ed6852c
def runDataRef(self, patchRef): <NEW_LINE> <INDENT> if self.config.hasFakes: <NEW_LINE> <INDENT> exposure = patchRef.get("fakes_" + self.config.coaddName + "Coadd", immediate=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> exposure = patchRef.get(self.config.coaddName + "Coadd", immediate=True) <NEW_LINE> <DEDENT> ...
! @brief Run detection on a coadd. Invokes @ref run and then uses @ref write to output the results. @param[in] patchRef: data reference for patch
625941f5cc40096d61595f83
def __init__(self, gtab, axial_diffusivity=AD, radial_diffusivity=RD, solver_params=None, params_file='temp', scaling_factor=SCALE_FACTOR, sub_sample=None, over_sample=None, mode='relative_signal', verbose=False): <NEW_LINE> <INDENT> data = np.zeros(len(gtab.bvals)) <NEW_LINE> self.cache = SparseDeconvolutionModel(data...
gtab : GradientTable class instance
625941f5cc0a2c11143dd4c7
def test_fuzzy_paper(): <NEW_LINE> <INDENT> crs = np.array([[generic_vals["M"], generic_vals["MH"], generic_vals["ML"], generic_vals["H"], generic_vals["H"], generic_vals["H"]], [generic_vals["MH"], generic_vals["MH"], generic_vals["ML"], generic_vals["MH"], generic_vals["MH"], generic_vals["MH"]], [generic_vals["MH"],...
:return:
625941f55166f23b2e1a578f
def process_whitelist(data, white_list = 'whitelist.txt'): <NEW_LINE> <INDENT> if not os.path.isfile(os.path.join(os.path.dirname(os.path.abspath(__file__)), white_list)): <NEW_LINE> <INDENT> open(os.path.join(os.path.dirname(os.path.abspath(__file__)), white_list), 'a').close() <NEW_LINE> <DEDENT> data = [element for ...
Removes everything in whitelist from data
625941f594891a1f4081c0e2
def pulse_dt2dw(dt,lam0=800,Output='frequency'): <NEW_LINE> <INDENT> dw=4*np.log(2)/Pi/dt <NEW_LINE> if Output=='frequency': <NEW_LINE> <INDENT> return dw <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return dw/c*(lam0*10**-9)**2
pulse spectral width from duration assuming Gaussian pulse and FWHM values dt in s Output in Hz (Output='frequency') or nm (Output='wavelength') if nm then lam0: central wavelength is required [in nm]
625941f5d8ef3951e3243b73
def _inflight_exc(self, clarification=""): <NEW_LINE> <INDENT> return ValueError( "INFLIGHT format should be " + repr(self._dated_format) + " : " + clarification)
Raise a ValueError() for an INFLIGHT PEDIGREE showing the expected format augmented by additional `clarification` str.
625941f5be383301e01b5aaf
@app.route("/<v1>/user/register", methods=["POST"]) <NEW_LINE> def register(v1): <NEW_LINE> <INDENT> data = request.get_json() <NEW_LINE> username = data.get("username") <NEW_LINE> password = data.get("password") <NEW_LINE> email = data.get("email") <NEW_LINE> if not username: <NEW_LINE> <INDENT> return jsonify({"messa...
End point to register a new user
625941f54527f215b584ca87
def write(dist_path, nims, no_quiz_feedback, test_time): <NEW_LINE> <INDENT> logpath = os.path.join(dist_path, 'metadata.log') <NEW_LINE> with open(logpath, 'w') as logfile: <NEW_LINE> <INDENT> json.dump( package(nims, no_quiz_feedback, test_time), logfile )
Write out a metadata.log file in JSON format. :param dist_path: path to distribution :param nims: list of NIMs given to generate_study on the command line :param no_quiz_feedback: boolean option given to generate_study on the command line :param test_time: post-test time in seconds given to generate_study on the comma...
625941f556ac1b37e62647f8
def bootstrap(X, N, H0, *args): <NEW_LINE> <INDENT> assert callable(H0), 'H0 must be a callable that returns a scalar sample' <NEW_LINE> tail = 0 <NEW_LINE> for i in xrange(N): <NEW_LINE> <INDENT> tail += int(H0(*args) >= X) <NEW_LINE> <DEDENT> if tail > float(N)/2: <NEW_LINE> <INDENT> tail = tail - N <NEW_LINE> <DEDEN...
Get a one-tail p-value for an algorithmic sampling process H0(*args) must return a scalar null sample value. The sign of the returned p-value indicates whether X is less than (-) or greater than (+) the median of the sample distribution. Arguments: X -- the value for which to return a p-value N -- sampling size of ...
625941f5ad47b63b2c50a5b6
def _getFromFile(self, filepath, limitSearch=None): <NEW_LINE> <INDENT> results = self.restGET('/entity/md5/%s' %utils.md5_for_file(filepath).hexdigest())['results'] <NEW_LINE> if limitSearch is not None: <NEW_LINE> <INDENT> paths = [self.restGET('/entity/%s/path' %ent['id']) for ent in results] <NEW_LINE> results = [e...
Gets a Synapse entityBundle based on the md5 of a local file See :py:func:`synapseclient.Synapse.get`. :param filepath: path to local file :param limitSearch: Limits the places in Synapse where the file is searched for.
625941f57cff6e4e81117fbb
def __repr__(self): <NEW_LINE> <INDENT> s = '<ch: %(channel)d, meas: %(measure)d, beat: %(beat)d, dur: %(duration)d, name: %(name)s, oct: %(octave)d, flag: %(start)s>\n' % self.__dict__ <NEW_LINE> return s
Human readable note. @return: Printable representation of a note and its params @rtype: string
625941f50383005118ecfc16
@aggregation <NEW_LINE> def SUM(entries): <NEW_LINE> <INDENT> return sum(entries)
Sum up the values in groups
625941f54e696a04525c9a84
def validate(self): <NEW_LINE> <INDENT> for node_name, node in self._subnodes.items(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> node.validate() <NEW_LINE> <DEDENT> except (exceptions.ValidationError, exceptions.SubnodeValidationError) as err: <NEW_LINE> <INDENT> raise exceptions.SubnodeValidationError(node_name) fr...
Recursively validate all sub-node values. If validation succeeds, the method terminates silently. Otherwise, an exception is raised. Raises: dsch.exceptions.SubnodeValidationError: if validation fails.
625941f54f6381625f115070
def sigmoid_derivative(x): <NEW_LINE> <INDENT> s = sigmoid(x) <NEW_LINE> ds = s(1 - s) <NEW_LINE> return ds
Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x. You can store the output of the sigmoid function into variables and then use it to calculate the gradient. Arguments: x -- A scalar or numpy array Return: ds -- Your computed gradient.
625941f54f6381625f115071
def RPR_GetMediaItemTakeByGUID(project,guid): <NEW_LINE> <INDENT> a=_ft['GetMediaItemTakeByGUID'] <NEW_LINE> f=CFUNCTYPE(c_uint64,c_uint64,c_uint64)(a) <NEW_LINE> t=(rpr_packp('ReaProject*',project),rpr_packp('GUID*',guid)) <NEW_LINE> r=f(t[0],t[1]) <NEW_LINE> return rpr_unpackp('MediaItem_Take*',r)
Python: MediaItem_Take RPR_GetMediaItemTakeByGUID(ReaProject project, const GUID guid)
625941f5435de62698dfe283
def test_dependency_inheritance(self): <NEW_LINE> <INDENT> dependencies = get_class_dependencies(InheritedBlock) <NEW_LINE> self.assertIsNotNone(dependencies) <NEW_LINE> self.assertIn("nio", dependencies) <NEW_LINE> self.assertEqual(dependencies["nio"][1], "2.0.1")
Asserts that dependencies are inherited
625941f530dc7b7665901f95
def arxiv_plot_extract(obj, eng): <NEW_LINE> <INDENT> from invenio.utils.plotextractor.api import ( get_tarball_from_arxiv, get_marcxml_plots_from_tarball ) <NEW_LINE> from invenio.modules.workflows.utils import convert_marcxml_to_bibfield <NEW_LINE> from invenio.utils.shell import Timeout <NEW_LINE> if "_result" not i...
Extract plots from an arXiv archive.
625941f5283ffb24f3c55f30
def messagesUser(user): <NEW_LINE> <INDENT> checkparam = "name" <NEW_LINE> if check.user(checkparam,user) == True: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error = "El usuario no existe, indique uno existente o cree uno nuevo" <NEW_LINE> raise ValueError(error) <NEW_LINE> <DEDENT> query = ...
Devuelve todos los mensajes que ha escrito un usuario que le pases como argumento.
625941f5498bea3a759ba0e3
def getAlleles(vcffile, Pop=False): <NEW_LINE> <INDENT> _s=-1 <NEW_LINE> alllist=[] <NEW_LINE> with open(vcffile, 'rU') as vfile: <NEW_LINE> <INDENT> for _geno in vfile: <NEW_LINE> <INDENT> if _geno[0]!='#': <NEW_LINE> <INDENT> _alllst=_geno.split() <NEW_LINE> if Pop or len(set(re.split('/|\|', _alllst[-1].split(':')[0...
Extract the alleles and their numerical code at (heterozygous) sites from a VCF file. Return \ the number, position and a dictionary, for the alleles and their coding as a list of triple tuples. If the VCF file belongs to a member of a population, keep all of the SNPs. Otherwise, throw away the homozygous ones.
625941f59c8ee82313fbbdad
def load_gfx(path): <NEW_LINE> <INDENT> graphics = {} <NEW_LINE> for item in os.listdir(path): <NEW_LINE> <INDENT> item_path = os.path.join(path, item) <NEW_LINE> name, ext = os.path.splitext(item) <NEW_LINE> if ext == "": <NEW_LINE> <INDENT> graphics.update(recursive_load_gfx(item_path)) <NEW_LINE> <DEDENT> else: <NEW...
Loads all the files in the graphics folder and also one more folder level deep. Doesn't recurse files deeper than that.
625941f54a966d76dd55164c
def get_public_email_addresses(self): <NEW_LINE> <INDENT> return self.session.get(config.BASE_URL + '/user/public_emails')
Method to retrieve public email addresses
625941f58a43f66fc4b54694
def duplicate_file(filename: str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> shutil.copy(filename, filename + ".dup") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass
Duplicate a file
625941f5377c676e912727dc
def setup_command_line(subparsers): <NEW_LINE> <INDENT> parser = subparsers.add_parser( 'simulate', help='run forward simulations with selfing') <NEW_LINE> parser.add_argument( 'config', type=argparse.FileType('r'), help='the settings of simulation as a JSON file') <NEW_LINE> parser.add_argument( 'substs', type=str, na...
Sets up command line interface.
625941f5566aa707497f4b96
def statuses(self) -> List[Status]: <NEW_LINE> <INDENT> r_json = self._get_json("status") <NEW_LINE> statuses = [ Status(self._options, self._session, raw_stat_json) for raw_stat_json in r_json ] <NEW_LINE> return statuses
Get a list of status Resources from the server. Returns: List[Status]
625941f5fff4ab517eb2fa77
def add_repositories(self, name=None, owner=None, description=None, resource=None, category=None, url=None, mute=False): <NEW_LINE> <INDENT> data = dict( name = self.to_unicode(name), owner = self.to_unicode(owner), description = self.to_unicode(description), resource = self.to_unicode(resource), category = self.to_uni...
Adds a repository to the database and returns the affected row count.
625941f560cbc95b062c6b7a
def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return VehicleStatsDecorationsObdEngineSeconds( value = 9723103 ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return VehicleStatsDecorationsObdEngineSeconds( value = 9723103, )
Test VehicleStatsDecorationsObdEngineSeconds include_option is a boolean, when False only required params are included, when True both required and optional params are included
625941f550485f2cf553d3d2
def weight_matrix(X, x, tau): <NEW_LINE> <INDENT> return np.diag(np.exp(-1 * ((x - X[:, 1])**2 / (2 * tau ** 2))))
Calculate the weight matrix for a given query point x.
625941f5377c676e912727dd
def read(connection, mask): <NEW_LINE> <INDENT> global keep_running <NEW_LINE> client_address = connection.getpeername() <NEW_LINE> print('read({})'.format(client_address)) <NEW_LINE> data = connection.recv(1024) <NEW_LINE> mc = memcache.Client(['127.0.0.1:11211'], debug=0) <NEW_LINE> if data: <NEW_LINE> <INDENT> print...
Callback for read events
625941f57d43ff24873a32dc
@pytest.mark.parametrize("value", [1, 1.0, 1 + 2j]) <NEW_LINE> def test_constant_short(value): <NEW_LINE> <INDENT> constant = optplan.make_constant(value) <NEW_LINE> complex_value = complex(value) <NEW_LINE> assert constant.value.real == complex_value.real <NEW_LINE> assert constant.value.imag == complex_value.imag
Tests `make_constant` creation using the short form (e.g. `Constant(6)`).
625941f5fb3f5b602dac3cd1
def getLinks(res_handler): <NEW_LINE> <INDENT> soup = bs(res_handler, 'html.parser') <NEW_LINE> links = [a.get('href') for a in soup.find_all('a') if a.get('href') != ''] <NEW_LINE> return links
@param res_handle: HTTP Response handler @return: list of strings
625941f57cff6e4e81117fbc
def score(word): <NEW_LINE> <INDENT> letterPoints = { 'a': 1, 'b': 4, 'c': 4, 'd': 2, 'e': 1, 'f': 4, 'g': 3, 'h': 3, 'i': 1, 'j': 10, 'k': 5, 'l': 2, 'm': 4, 'n': 2, 'o': 1, 'p': 4, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 2, 'v': 5, 'w': 4, 'x': 8, 'y': 3, 'z': 10 } <NEW_LINE> score = 0 <NEW_LINE> for ch in word: <NEW_L...
Define what each letter is worth in the game
625941f53d592f4c4ed1d692
def test_check_for_doc_inline_markup(self): <NEW_LINE> <INDENT> salt_dir = CODE_DIR <NEW_LINE> if salt.utils.platform.is_windows(): <NEW_LINE> <INDENT> cmd = 'findstr /C:":doc:" /S /P {0}\\*'.format(salt_dir) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> salt_dir += '/' <NEW_LINE> cmd = 'grep -r :doc: ' + salt_dir <NEW...
We should not be using the ``:doc:`` inline markup option when cross-referencing locations. Use ``:ref:`` or ``:mod:`` instead. This test checks for reference to ``:doc:`` usage. See Issue #12788 for more information. https://github.com/saltstack/salt/issues/12788
625941f566656f66f7cbc7e3
def convert_utc_to_standard(self, utc_str: str, utc_format: str, hour: int): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> utcTime = datetime.strptime(utc_str, utc_format) <NEW_LINE> standard = utcTime + timedelta(hours=hour) <NEW_LINE> return standard <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print...
UTC时间字符串转换为时间戳 ("2019-11-11T12:15:05.786Z","%Y-%m-%dT%H:%M:%S.%fZ",8) return:2019-11-11 20:15:05.786000 ("2019-11-11 12:15:05.786","%Y-%m-%dT%H:%M:%S.%fZ",0) return: 2019-11-11 12:15:05.786000
625941f5596a89723608a0ee
def setup(self, config: ConfigType) -> None: <NEW_LINE> <INDENT> self.hass.add_job(self.async_setup(config))
Set up a full entity component. This doesn't block the executor to protect from deadlocks.
625941f53eb6a72ae02ecb26
def __level_repr(self, arr, d): <NEW_LINE> <INDENT> s = ' ' * d <NEW_LINE> for node in arr: <NEW_LINE> <INDENT> if node is None: <NEW_LINE> <INDENT> s = s + '!' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = s + str(node.key) <NEW_LINE> <DEDENT> s = s + ' ' * (2 * d + 1) <NEW_LINE> <DEDENT> return s
helper for repr
625941f576d4e153a657f169
def remove_aliases(*args): <NEW_LINE> <INDENT> lines = [] <NEW_LINE> remove_next = False <NEW_LINE> for line in fs.read_lines(introspection.shell_configuration_path()): <NEW_LINE> <INDENT> if strings.startswith_any(line, ["alias " + alias for alias in args]): <NEW_LINE> <INDENT> remove_next = True <NEW_LINE> if len(lin...
This function ... :param args: :return:
625941f5f7d966606f6aa642
def process(self): <NEW_LINE> <INDENT> if self.tickEvent: <NEW_LINE> <INDENT> while self.tickEvent.active(): <NEW_LINE> <INDENT> self.tickEvent.cancel() <NEW_LINE> self.tick()
Mustly useful in tests. This repeats the tick process of this Condition until the Condition is finished without waiting.
625941f5009cb60464c639e3
def _on_connect_partition(dbapi_con, con_record): <NEW_LINE> <INDENT> from sqlite import _on_connect_bundle as ocb <NEW_LINE> dbapi_con.execute('PRAGMA page_size = 8192') <NEW_LINE> dbapi_con.execute('PRAGMA temp_store = MEMORY') <NEW_LINE> dbapi_con.execute('PRAGMA cache_size = 50000') <NEW_LINE> dbapi_con.execute('PR...
ISSUE some Sqlite pragmas when the connection is created.
625941f51f5feb6acb0c5180