code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def calculate_next_q_value_memory(self, next_state: torch.Tensor) -> torch.Tensor: <NEW_LINE> <INDENT> next_q_values = self.model(next_state) <NEW_LINE> return torch.max(next_q_values, 1)[0] | Method that calculates the next Q value given the next state. Used to calculate the loss when
the memory is in used. This method handle a list of states.
:param next_state: list of states of the environment after acting
:return: estimation of the next state q value | 625941bf96565a6dacc8f619 |
def _negotiate_SOCKS5(self, dest_addr, dest_port): <NEW_LINE> <INDENT> proxy_type, addr, port, rdns, username, password = self.proxy <NEW_LINE> if username and password: <NEW_LINE> <INDENT> self.sendall(b"\x05\x02\x00\x02") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.sendall(b"\x05\x01\x00") <NEW_LINE> <DEDENT> chosen_auth = self._recvall(2) <NEW_LINE> if chosen_auth[0:1] != b"\x05": <NEW_LINE> <INDENT> raise GeneralProxyError("SOCKS5 proxy server sent invalid data") <NEW_LINE> <DEDENT> if chosen_auth[1:2] == b"\x02": <NEW_LINE> <INDENT> self.sendall(b"\x01" + chr(len(username)).encode() + username + chr(len(password)).encode() + password) <NEW_LINE> auth_status = self._recvall(2) <NEW_LINE> if auth_status[0:1] != b"\x01": <NEW_LINE> <INDENT> raise GeneralProxyError("SOCKS5 proxy server sent invalid data") <NEW_LINE> <DEDENT> if auth_status[1:2] != b"\x00": <NEW_LINE> <INDENT> raise SOCKS5AuthError("SOCKS5 authentication failed") <NEW_LINE> <DEDENT> <DEDENT> elif chosen_auth[1:2] != b"\x00": <NEW_LINE> <INDENT> if chosen_auth[1:2] == b"\xFF": <NEW_LINE> <INDENT> raise SOCKS5AuthError("All offered SOCKS5 authentication methods were rejected") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise GeneralProxyError("SOCKS5 proxy server sent invalid data") <NEW_LINE> <DEDENT> <DEDENT> req = b"\x05\x01\x00" <NEW_LINE> try: <NEW_LINE> <INDENT> addr_bytes = socket.inet_aton(dest_addr) <NEW_LINE> req += b"\x01" + addr_bytes <NEW_LINE> <DEDENT> except socket.error: <NEW_LINE> <INDENT> if rdns: <NEW_LINE> <INDENT> addr_bytes = None <NEW_LINE> req += b"\x03" + chr(len(dest_addr)).encode() + dest_addr.encode() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> addr_bytes = socket.inet_aton(socket.gethostbyname(dest_addr)) <NEW_LINE> req += b"\x01" + addr_bytes <NEW_LINE> <DEDENT> <DEDENT> req += struct.pack(">H", dest_port) <NEW_LINE> self.sendall(req) <NEW_LINE> resp = self._recvall(4) <NEW_LINE> if resp[0:1] != b"\x05": <NEW_LINE> <INDENT> raise GeneralProxyError("SOCKS5 proxy server sent invalid data") <NEW_LINE> <DEDENT> status = ord(resp[1:2]) <NEW_LINE> if status != 0x00: <NEW_LINE> <INDENT> error = SOCKS5_ERRORS.get(status, "Unknown error") <NEW_LINE> raise SOCKS5Error("{:#04x}: {}".format(status, error)) <NEW_LINE> <DEDENT> if resp[3:4] == b"\x01": <NEW_LINE> <INDENT> bound_addr = self._recvall(4) <NEW_LINE> <DEDENT> elif resp[3:4] == b"\x03": <NEW_LINE> <INDENT> resp += self.recv(1) <NEW_LINE> bound_addr = self._recvall(ord(resp[4:5])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise GeneralProxyError("SOCKS5 proxy server sent invalid data") <NEW_LINE> <DEDENT> bound_port = struct.unpack(">H", self._recvall(2))[0] <NEW_LINE> self.proxy_sockname = bound_addr, bound_port <NEW_LINE> if addr_bytes: <NEW_LINE> <INDENT> self.proxy_peername = socket.inet_ntoa(addr_bytes), dest_port <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.proxy_peername = dest_addr, dest_port | Negotiates a connection through a SOCKS5 server. | 625941bfd18da76e23532420 |
def mifareCloneCard(self): <NEW_LINE> <INDENT> cmd = '%s%s\x00\x00\x00' %(chr(self.CLA_MIFARE), chr(R502SpyLibrary.INS_MIFARE_CLONE)) <NEW_LINE> rsp = self.__scInterface.transmit(cmd) <NEW_LINE> if rsp[-2 : ] == '\x90\x00': <NEW_LINE> <INDENT> return True, rsp[ : -2] <NEW_LINE> <DEDENT> return False, rsp[0] | @brief:
@return: True and response data / False and the error code. | 625941bf67a9b606de4a7e09 |
def _do_insert(self, sql, timestamp, value): <NEW_LINE> <INDENT> timestamp_utc = _timestamp_to_utc(timestamp) <NEW_LINE> self._cursor.execute(sql, (timestamp_utc.strftime(_TIMESTAMP_FORMAT), value)) <NEW_LINE> self._connection.commit() | Executes and commits a SQL insert command.
Args:
sql: SQL query string for the insert command.
timestamp: datetime instance representing the record timestamp.
value: Value to insert for the record. | 625941bf24f1403a92600ab6 |
def load_config(self, sep="\t"): <NEW_LINE> <INDENT> f = open(self.path) <NEW_LINE> lines = f.readlines() <NEW_LINE> self.load_summary(lines[0].strip(), sep) <NEW_LINE> total_features = self.get_total_features() <NEW_LINE> for i in range(total_features): <NEW_LINE> <INDENT> self.load_feature(lines[i + 1].strip(), sep) <NEW_LINE> <DEDENT> self.load_feature(lines[total_features + 1].strip(), sep) | load the config file to get data set description
:param sep: separator to parse each line in the file
:return: configuration of the data set | 625941bfbe7bc26dc91cd552 |
def loadFiringRates(exp,area,typeunit): <NEW_LINE> <INDENT> filename = join(ROOT, 'data', 'Polished', exp, 'neuronDB.h5') <NEW_LINE> f = h5py.File(filename, 'r') <NEW_LINE> if typeunit == 'mua': <NEW_LINE> <INDENT> x = f['/' + area + '/mua/data/count'][:, 0:1440] <NEW_LINE> <DEDENT> if typeunit == 'su': <NEW_LINE> <INDENT> x = f['/' + area + '/su/data/count'][:, 0:1440] <NEW_LINE> <DEDENT> if typeunit == 'all': <NEW_LINE> <INDENT> x1 = f['/' + area + '/mua/data/count'][:, 0:1440] <NEW_LINE> x2 = f['/' + area + '/su/data/count'][:, 0:1440] <NEW_LINE> x = np.vstack((x1, x2)) <NEW_LINE> del x1,x2 <NEW_LINE> <DEDENT> return x.T | Load firing rates matrix of a specific combination of
experiment (Control, Experimental, Naive), area (v1, ll)
and type of unit (mua,su,all).
Returns a matrix of the form (n.of stimuli, n.of neurons) | 625941bf10dbd63aa1bd2af3 |
def get_params_from_yaml(self, keyname): <NEW_LINE> <INDENT> return { self.PARAM_GROUP : LocalState.get_group(keyname), self.PARAM_KEYNAME : keyname, self.PARAM_PROJECT : LocalState.get_project(keyname), self.PARAM_SECRETS : LocalState.get_client_secrets_location(keyname), self.PARAM_VERBOSE : False } | Searches through the locations.yaml file to build a dict containing the
parameters necessary to interact with Google Compute Engine.
Args:
keyname: A str that uniquely identifies this AppScale deployment.
Returns:
A dict containing all of the credentials necessary to interact with
Google Compute Engine. | 625941bfcb5e8a47e48b79fb |
def uniquify(conc_lines): <NEW_LINE> <INDENT> from collections import OrderedDict <NEW_LINE> unique_lines = [] <NEW_LINE> checking = [] <NEW_LINE> for index, (_, speakr, start, middle, end) in enumerate(conc_lines): <NEW_LINE> <INDENT> joined = ' '.join([speakr, start, 'MIDDLEHERE:', middle, ':MIDDLEHERE', end]) <NEW_LINE> if joined not in checking: <NEW_LINE> <INDENT> unique_lines.append(conc_lines[index]) <NEW_LINE> <DEDENT> checking.append(joined) <NEW_LINE> <DEDENT> return unique_lines | get unique concordance lines | 625941bf596a897236089a11 |
def judgeCjdltOpen(self): <NEW_LINE> <INDENT> list=[2,4,7] <NEW_LINE> if self.todayWeek in list: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | 二、四、日是超级大乐透开机号创建日期 | 625941bf4c3428357757c277 |
def _prepare_cmd(self): <NEW_LINE> <INDENT> return [ "mke2fs -q -F -O journal_dev -b 4096 %s" % self.comp.dev ] | Return target journal device format command line. | 625941bf566aa707497f44ba |
def id_rem2(a, b, details=2): <NEW_LINE> <INDENT> return 'Polynome([[%r, 1], [%r, 0]], details=%s)**2' % (a, -b, details) | Construit un Polynome de la forme (ax-b)^2
Renvoie une chaine | 625941bf796e427e537b0511 |
def _update_fields_values(self, values, fields): <NEW_LINE> <INDENT> for field, value in zip(fields, values): <NEW_LINE> <INDENT> field.update_value(value, self.lastwritetime) | update the field values once data successfully written | 625941bf956e5f7376d70dbc |
def process_performance_results( program_objects, first_date, last_date, results_type, exercise_property, property_value): <NEW_LINE> <INDENT> first = first_date.toPyDate().strftime("%Y-%m-%d") <NEW_LINE> last = last_date.toPyDate().strftime("%Y-%m-%d") <NEW_LINE> result_dates = [] <NEW_LINE> result_values = [] <NEW_LINE> result_starts = [] <NEW_LINE> sorted_starts = sorted(program_objects.keys()) <NEW_LINE> for start in sorted_starts: <NEW_LINE> <INDENT> if first <= start <= last: <NEW_LINE> <INDENT> result_starts.append( datetime.datetime.strptime(start, "%Y-%m-%d").date()) <NEW_LINE> <DEDENT> perf_results = program_objects[start].performance_results( results_type, exercise_property) <NEW_LINE> sorted_begans = sorted(perf_results.keys()) <NEW_LINE> for began in sorted_begans: <NEW_LINE> <INDENT> began_date = began[:10] <NEW_LINE> if (first <= began_date <= last and property_value in perf_results[began]): <NEW_LINE> <INDENT> result_dates.append( datetime.datetime.strptime(began_date, "%Y-%m-%d").date()) <NEW_LINE> result_values.append(perf_results[began][property_value]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return result_dates, result_values, result_starts | Return a performance results data set that can be plotted.
This function iterates over the user's Program record objects to find all
Programs with constituent Workout period began dates between the first_date
and last_date args. Calls each applicable Program's performance_results
method with the results_type and exercise_property args to determine the
performance results. Determines which results apply to only the Exercise
property value specified by the property_value arg. The performance results
dict is in the format:
{Workout period began: {
Exercise property: result value for all Sessions, ...}, ...}
Returns a tuple with an x-coord list with all applicable Workout period
began dates, a y-coord list with corresponding performance result values
for the specified Exercise property value, and an x-coord list with all
Program start dates found within the specified date range. These lists are
n the format:
--X: Workout Period Began Dates--
[first Workout began date, second Workout began date, ...]
--Y: Performance Result Values--
[first date value, second date value, ...]
--X(vertical lines): Program Start Dates--
[first Program start, second Program start, ...]
Performance results are displayed in a line plot. Program start dates are
shown as vertical lines intersecting the corresponding x-axis date values.
:param program_objects: The user's Program record objects
:type program_objects: dict
:param first_date: The earliest constituent Workout began date to process
:type first_date: QDate
:param last_date:The latest constituent Workout began date to process
:type last_date: QDate
:param results_type: The type of performance results: 'effort' for total
effort sum, 'intensity' for maximum intensity, 'magnitude' for total
magnitude sum
:type results_type: str
:param exercise_property: The Exercise property to which performance
results are mapped: 'itemid' for Exercise item ID, 'focusmuscle' for
focus muscle, 'tags' for tags
:type exercise_property: str
:param property_value: An Exercise ID, focus muscle, or tag
:type property_value: str
:return: Clean data in the format: (Workout began dates list, performance
results for property value list, Program start dates list)
:rtype: tuple | 625941bf44b2445a33931fe5 |
def brown(num_points=1024, b_minus2=1.0, fs=1.0): <NEW_LINE> <INDENT> return (1.0/float(fs))*numpy.cumsum( white(num_points, b0=b_minus2*(4.0*math.pi*math.pi), fs=fs)) | Brownian or random walk (diffusion) noise with 1/f^2 PSD
Not really a color... rather Brownian or random-walk.
Obtained by integrating white-noise.
Parameters
----------
num_points: int, optional
number of samples
b_minus2: float, optional
desired power-spectral density is b2*f^-2
fs: float, optional
sampling frequency, i.e. 1/fs is the time-interval between
datapoints
Returns
-------
Random walk sample: numpy.array | 625941bfbde94217f3682d41 |
def testValidateFound(self): <NEW_LINE> <INDENT> event = { 'basePath': { 'p': 'value' } } <NEW_LINE> sut = APIGateway(mockLoggerFactory, event) <NEW_LINE> validator = MagicMock() <NEW_LINE> sut.getParameter('param', 'basePath', 'p', False, validator) <NEW_LINE> validator.assert_called_once_with('value') | APIGateway.getParameter() should call the validator if passed [with found param] | 625941bf4e696a04525c939a |
def patch(self, url, **kwargs): <NEW_LINE> <INDENT> return self.request('PATCH', url, **kwargs) | Sends a PATCH request and returns a :class:`HttpResponse` object.
:params url: url for the new :class:`HttpRequest` object.
:param \*\*kwargs: Optional arguments for the :meth:`request` method. | 625941bf4d74a7450ccd4111 |
def delete_vcard(self, href, etag): <NEW_LINE> <INDENT> self._check_write_support() <NEW_LINE> remotepath = str(self.url.base + href) <NEW_LINE> headers = self.headers <NEW_LINE> headers['content-type'] = 'text/vcard' <NEW_LINE> if etag is not None: <NEW_LINE> <INDENT> headers['If-Match'] = etag <NEW_LINE> <DEDENT> response = self.session.delete(remotepath, headers=headers, **self._settings) <NEW_LINE> response.raise_for_status() | deletes vcard from server
deletes the resource at href if etag matches,
if etag=None delete anyway
:param href: href of card to be deleted
:type href: str()
:param etag: etag of that card, if None card is always deleted
:type href: str()
:returns: nothing | 625941bf4a966d76dd550f5b |
def should_include_node(ctx, directives): <NEW_LINE> <INDENT> if directives: <NEW_LINE> <INDENT> skip_ast = None <NEW_LINE> for directive in directives: <NEW_LINE> <INDENT> if directive.name.value == GraphQLSkipDirective.name: <NEW_LINE> <INDENT> skip_ast = directive <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if skip_ast: <NEW_LINE> <INDENT> args = get_argument_values( GraphQLSkipDirective.args, skip_ast.arguments, ctx.variables, ) <NEW_LINE> return not args.get('if') <NEW_LINE> <DEDENT> include_ast = None <NEW_LINE> for directive in directives: <NEW_LINE> <INDENT> if directive.name.value == GraphQLIncludeDirective.name: <NEW_LINE> <INDENT> include_ast = directive <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if include_ast: <NEW_LINE> <INDENT> args = get_argument_values( GraphQLIncludeDirective.args, include_ast.arguments, ctx.variables, ) <NEW_LINE> return bool(args.get('if')) <NEW_LINE> <DEDENT> <DEDENT> return True | Determines if a field should be included based on the @include and
@skip directives, where @skip has higher precidence than @include. | 625941bf0383005118ecf532 |
def gauss(x): <NEW_LINE> <INDENT> c = 1/(np.sqrt(2*np.pi)) <NEW_LINE> gauss = c*np.exp(-x**2/2) <NEW_LINE> return gauss | Returns the Gaussian function dependent on the input float | 625941bf3346ee7daa2b2cb8 |
def handle_nulls(s, drop_na=False, fill_value=0): <NEW_LINE> <INDENT> if drop_na: <NEW_LINE> <INDENT> return s.dropna() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return fill_nulls(s, fill_value) | Handles null values in a series.
Parameters:
-----------
s: pandas.Series
Series to evaluate
drop_na: bool, default False
If true, null values are dropped. If false
nulls are replaced by the fill_value
fill_value: optional, default 0
The value to fill nas with. Ignored if nulls
are being dropped.
Returns:
-------
pandas.Series | 625941bf287bf620b61d39b3 |
def login(manifesto_file, username): <NEW_LINE> <INDENT> with open(manifesto_file) as file: <NEW_LINE> <INDENT> list_of_usernames = file.readlines() <NEW_LINE> <DEDENT> if list_of_usernames: <NEW_LINE> <INDENT> for name in list_of_usernames: <NEW_LINE> <INDENT> if username == name.split(', ')[0]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | (file, str) -> NoneType, bool
Checks to see if the provided username is in the file | 625941bf10dbd63aa1bd2af4 |
def choose_backend(backend): <NEW_LINE> <INDENT> if backend is None: <NEW_LINE> <INDENT> return cdf, pdf, ppf <NEW_LINE> <DEDENT> elif backend == 'mpmath': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import mpmath <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> raise ImportError('Install "mpmath" to use this backend') <NEW_LINE> <DEDENT> return mpmath.ncdf, mpmath.npdf, _gen_ppf(mpmath.erfc, math=mpmath) <NEW_LINE> <DEDENT> elif backend == 'scipy': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from scipy.stats import norm <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> raise ImportError('Install "scipy" to use this backend') <NEW_LINE> <DEDENT> return norm.cdf, norm.pdf, norm.ppf <NEW_LINE> <DEDENT> raise ValueError('%r backend is not defined' % backend) | Returns a tuple containing cdf, pdf, ppf from the chosen backend.
>>> cdf, pdf, ppf = choose_backend(None)
>>> cdf(-10)
7.619853263532764e-24
>>> cdf, pdf, ppf = choose_backend('mpmath')
>>> cdf(-10)
mpf('7.6198530241605255e-24')
.. versionadded:: 0.3 | 625941bffb3f5b602dac35de |
def setUp(self): <NEW_LINE> <INDENT> Revision.objects.all().delete() <NEW_LINE> self.model.objects.all().delete() <NEW_LINE> reversion.register(self.model) <NEW_LINE> with reversion.revision: <NEW_LINE> <INDENT> self.test = self.model.objects.create(name="test1.0") <NEW_LINE> <DEDENT> with reversion.revision: <NEW_LINE> <INDENT> self.test.name = "test1.1" <NEW_LINE> self.test.save() <NEW_LINE> <DEDENT> with reversion.revision: <NEW_LINE> <INDENT> self.test.name = "test1.2" <NEW_LINE> self.test.save() | Sets up the ReversionTestModel. | 625941bf31939e2706e4cdbb |
def relabel(self): <NEW_LINE> <INDENT> vim_buffer = self.copy_vim_buffer() <NEW_LINE> buf = Buffer.init(vim_buffer) <NEW_LINE> curpos_point = self.get_cursor_point() <NEW_LINE> rect = buf.get_rect_on_cursor(curpos_point) <NEW_LINE> label_start_pos = None <NEW_LINE> if rect is not None: <NEW_LINE> <INDENT> rect.delete_label() <NEW_LINE> buf.set_rect(rect) <NEW_LINE> vim_point = Buffer.translate_buffer_to_vim_buffer( rect.get_label_start_point()) <NEW_LINE> label_start_pos = Buffer.translate_point_to_curpos( self.nvim.call("getcurpos"), vim_point) <NEW_LINE> self.redraw(buf, label_start_pos) <NEW_LINE> self.nvim.command("startinsert") <NEW_LINE> self.nvim.command("augroup RecterCorrectFormatLoad") <NEW_LINE> self.nvim.command("autocmd!") <NEW_LINE> self.nvim.command("autocmd InsertLeave * RecterCorrectFormat") <NEW_LINE> self.nvim.command("augroup END") | +-------+
||
+-------+ | 625941bf9b70327d1c4e0d22 |
def compute_ngrams(toks, n=2): <NEW_LINE> <INDENT> ngrams = {} <NEW_LINE> for i in range(len(toks) - n + 1): <NEW_LINE> <INDENT> if toks[i] in ngrams: <NEW_LINE> <INDENT> ngrams[toks[i]].append(tuple(toks[i + 1:i + n])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ngrams[toks[i]] = [tuple(toks[i + 1:i + n])] <NEW_LINE> <DEDENT> <DEDENT> return ngrams | Returns an n-gram dictionary based on the provided list of tokens. | 625941bf55399d3f05588601 |
def test(offset): <NEW_LINE> <INDENT> print("[*] Payload set to only overwrite the EIP") <NEW_LINE> buf = '\x11(setup sound ' <NEW_LINE> buf += '\x41' * offset <NEW_LINE> buf += struct.pack('<L', 0x42424242) <NEW_LINE> buf += '\x43' * 7 <NEW_LINE> buf += '\x90\x00#' <NEW_LINE> return buf | Test offset
| 625941bf8c3a873295158305 |
def test_broken_meta() -> None: <NEW_LINE> <INDENT> with pytest.raises(ParseError): <NEW_LINE> <INDENT> parse("Args:") <NEW_LINE> <DEDENT> with pytest.raises(ParseError): <NEW_LINE> <INDENT> parse("Args:\n herp derp") | Test parsing broken meta. | 625941bf96565a6dacc8f61a |
def getDetailsByID(self, server, token, userID): <NEW_LINE> <INDENT> self.uri = '/api/v1/users/{0}'.format(userID) <NEW_LINE> self.server = server + self.uri <NEW_LINE> headers = {'Content-Type': 'application/json','Authorization': 'Bearer {0}'.format(token)} <NEW_LINE> results = requests.get(self.server, headers=headers) <NEW_LINE> return results.content | Get detailed information of user by ID
Arguments:
server {string} -- Server URI
token {string} -- Token value to be used for accessing the API
userID {string} -- ID of the user
Returns:
string -- Detailed information of user by ID | 625941bfbe8e80087fb20b94 |
def create_comments(self): <NEW_LINE> <INDENT> for comment in self.comments: <NEW_LINE> <INDENT> comment.execute() | Creates all of the comments in :prop:comments | 625941bf3c8af77a43ae36ec |
def handle(text, mic, profile): <NEW_LINE> <INDENT> getresults(text, mic) | Responds to user-input, by telling word meanings".
Arguments:
text -- user-input, ex - "Find meaning of 'elephant'"
mic -- used to interact with the user (for both input and output)
profile -- contains information related to the user | 625941bf26068e7796caec29 |
def tearDown(self): <NEW_LINE> <INDENT> super(A2SSTestCase, self).tearDown() | Override teardown actions (for every test). | 625941bf60cbc95b062c6491 |
def rename_pct_cols(df, ver): <NEW_LINE> <INDENT> return df.rename(columns={'R_pct': ver + '_R_pct', 'M_pct': ver + '_M_pct'}) | Renames the percent columns to be prefaced with the version.
i.e. R_pct becomes 15v1_R_pct | 625941bf6aa9bd52df036cf0 |
def addOneRow(self, root, v, d): <NEW_LINE> <INDENT> if d == 1: <NEW_LINE> <INDENT> node = TreeNode(v) <NEW_LINE> node.left = root <NEW_LINE> root = node <NEW_LINE> return root <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._addOneRow(root,v,d) | :type root: TreeNode
:type v: int
:type d: int
:rtype: TreeNode | 625941bf07f4c71912b113cf |
def on_success(self, data): <NEW_LINE> <INDENT> if 'delete' in data: <NEW_LINE> <INDENT> self.on_delete(data.get('delete')) <NEW_LINE> <DEDENT> elif 'limit' in data: <NEW_LINE> <INDENT> self.on_limit(data.get('limit')) <NEW_LINE> <DEDENT> elif 'disconnect' in data: <NEW_LINE> <INDENT> self.on_disconnect(data.get('disconnect')) | Called when data has been successfull received from the stream
Feel free to override this to handle your streaming data how you
want it handled.
See https://dev.twitter.com/docs/streaming-apis/messages for messages
sent along in stream responses.
:param data: data recieved from the stream
:type data: dict | 625941bf498bea3a759b99fe |
def test_get_bound_height_out_of_range(): <NEW_LINE> <INDENT> p = np.arange(900, 300, -100) * units.hPa <NEW_LINE> h = np.arange(1, 7) * units.kilometer <NEW_LINE> with pytest.raises(ValueError): <NEW_LINE> <INDENT> _get_bound_pressure_height(p, 8 * units.kilometer, height=h) <NEW_LINE> <DEDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> _get_bound_pressure_height(p, 100 * units.meter, height=h) | Test when bound is out of data range in height. | 625941bf63b5f9789fde7033 |
def _do_extra_actions(api_content, cc_content, request_fields, actions_form, context): <NEW_LINE> <INDENT> for field, form_value in actions_form.cleaned_data.items(): <NEW_LINE> <INDENT> if field in request_fields and form_value != api_content[field]: <NEW_LINE> <INDENT> api_content[field] = form_value <NEW_LINE> if field == "following": <NEW_LINE> <INDENT> if form_value: <NEW_LINE> <INDENT> context["cc_requester"].follow(cc_content) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> context["cc_requester"].unfollow(cc_content) <NEW_LINE> <DEDENT> <DEDENT> elif field == "abuse_flagged": <NEW_LINE> <INDENT> if form_value: <NEW_LINE> <INDENT> cc_content.flagAbuse(context["cc_requester"], cc_content) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cc_content.unFlagAbuse(context["cc_requester"], cc_content, removeAll=False) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> assert field == "voted" <NEW_LINE> signal = thread_voted if cc_content.type == 'thread' else comment_voted <NEW_LINE> signal.send(sender=None, user=context["request"].user, post=cc_content) <NEW_LINE> if form_value: <NEW_LINE> <INDENT> context["cc_requester"].vote(cc_content, "up") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> context["cc_requester"].unvote(cc_content) | Perform any necessary additional actions related to content creation or
update that require a separate comments service request. | 625941bf8e71fb1e9831d6f8 |
def get(self, key, default=None, mb=None, account=None): <NEW_LINE> <INDENT> if account: <NEW_LINE> <INDENT> if mb: <NEW_LINE> <INDENT> if key in self.config[account][mb].keys(): <NEW_LINE> <INDENT> return self.config[account][mb][key] <NEW_LINE> <DEDENT> if key in self.config[account].keys(): <NEW_LINE> <INDENT> return self.config[account][key] <NEW_LINE> <DEDENT> if key in self.config.keys(): <NEW_LINE> <INDENT> return self.config[key] <NEW_LINE> <DEDENT> <DEDENT> if key in self.config[account].keys(): <NEW_LINE> <INDENT> return self.config[account][key] <NEW_LINE> <DEDENT> if key in self.config.keys(): <NEW_LINE> <INDENT> return self.config[key] <NEW_LINE> <DEDENT> <DEDENT> if key in self.config.keys(): <NEW_LINE> <INDENT> return self.config[key] <NEW_LINE> <DEDENT> return default | >>> conf = '''a = 1
... c = 1
... ta1 {
... a = 2
... b = 1
... tmb1 {
... b = 2
... c = 2
... d = 1
... }
... }'''
>>> c = Config()
>>> ctx = Config.Context()
>>> for line in conf.splitlines():
... c.parse_line(line, ctx)
>>> c.get('a', default='test', mb='tmb1', account='ta1')
'2'
>>> c.get('b', default='test', mb='tmb1', account='ta1')
'2'
>>> c.get('c', default='test', mb='tmb1', account='ta1')
'2'
>>> c.get('d', default='test', mb='tmb1', account='ta1')
'1'
>>> c.get('a', default='test', account='ta1')
'2'
>>> c.get('b', default='test', account='ta1')
'1'
>>> c.get('c', default='test', account='ta1')
'1'
>>> c.get('d', default='test', account='ta1')
'test'
>>> c.get('a', default='test', account='ta1')
'2'
>>> c.get('b', default='test', account='ta1')
'1'
>>> c.get('c', default='test', account='ta1')
'1'
>>> c.get('d', default='test', account='ta1')
'test'
>>> c.get('a', default='test')
'1'
>>> c.get('b', default='test')
'test'
>>> c.get('c', default='test')
'1'
>>> c.get('d', default='test')
'test'
:param key: the key to fetch
:param default: a default value to return if the key is not found
:param mb: name of the mailbox
:param account: name of the account
:return: something | 625941bf30bbd722463cbd12 |
def test_put_employee_too_long_name_fail(self): <NEW_LINE> <INDENT> url = reverse('employee-detail', kwargs={'pk':'1'}) <NEW_LINE> data = { 'first_name': 'Johniddasfeufhfweffsdfdsbvsdvdsuhfiuhwefwef', 'last_name': 'Doe', 'title':'Manager'} <NEW_LINE> response = self.client.put(url, data, format='json', HTTP_AUTHORIZATION="Token " + self.token) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) | Test failing a PUT if the first_name is too long | 625941bf6aa9bd52df036cf1 |
def moveZeroes(self, nums): <NEW_LINE> <INDENT> if not nums or len(nums) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> i, j = 0, 0 <NEW_LINE> while j < len(nums): <NEW_LINE> <INDENT> if nums[j] != 0: <NEW_LINE> <INDENT> nums[i], nums[j] = nums[j], nums[i] <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> j += 1 <NEW_LINE> <DEDENT> return | :type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead. | 625941bf236d856c2ad44725 |
def run_test(self): <NEW_LINE> <INDENT> with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor: <NEW_LINE> <INDENT> futures = [ executor.submit(self.regression, i) for i in range(self.train.shape[1]) ] <NEW_LINE> for idx, future in tqdm(enumerate(concurrent.futures.as_completed(futures)), total=len(futures)): <NEW_LINE> <INDENT> y_idx, err, err_b = future.result() <NEW_LINE> self.scores.loc[y_idx] = err <NEW_LINE> if err_b: <NEW_LINE> <INDENT> self.scores_b.loc[y_idx] = err_b <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return self.scores, self.scores_b | run all segments | 625941bf7c178a314d6ef3a9 |
def stats(filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(filename, "r") as file: <NEW_LINE> <INDENT> file_content = file.read() <NEW_LINE> lines = file_content.splitlines() <NEW_LINE> words = file_content.split() <NEW_LINE> lines_count = len(lines) <NEW_LINE> words_count = len(words) <NEW_LINE> file_size = file.seek(0, 2) <NEW_LINE> file_name = file.name <NEW_LINE> <DEDENT> return [lines_count, words_count, file_size, file_name] <NEW_LINE> <DEDENT> except FileNotFoundError as fnf_error: <NEW_LINE> <INDENT> print("{}: {}".format(fnf_error.args[1], fnf_error.filename)) <NEW_LINE> <DEDENT> except PermissionError as perm_error: <NEW_LINE> <INDENT> print("{}: {}".format(perm_error.args[1], perm_error.filename)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("DONE") | This function returns four values:
- lines in the file,
- words in the file,
- size of the file,
- file name | 625941bfd58c6744b4257bae |
def test_unsupported_version_response(self): <NEW_LINE> <INDENT> async def _unsupported_version_response(self): <NEW_LINE> <INDENT> packet = await SFTPHandler.recv_packet(self) <NEW_LINE> self.send_packet(FXP_VERSION, None, UInt32(99)) <NEW_LINE> return packet <NEW_LINE> <DEDENT> with patch('asyncssh.sftp.SFTPServerHandler.recv_packet', _unsupported_version_response): <NEW_LINE> <INDENT> with self.assertRaises(SFTPBadMessage): <NEW_LINE> <INDENT> self._dummy_sftp_client() | Test sending an unsupported version in response to init | 625941bf99fddb7c1c9de2e0 |
def get_source(self): <NEW_LINE> <INDENT> wd = self.workdir + "mate-dock-applet" <NEW_LINE> if self.get_applet_version() == "current": <NEW_LINE> <INDENT> if not os.path.exists(wd): <NEW_LINE> <INDENT> self.run_shell_command("git clone https://github.com/robint99/mate-dock-applet.git", self.workdir) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.run_shell_command("git pull origin master", wd) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if not os.path.exists(wd): <NEW_LINE> <INDENT> os.makedirs(wd) <NEW_LINE> <DEDENT> av = self.get_applet_version() <NEW_LINE> self.run_shell_command("wget https://github.com/robint99/mate-dock-applet/tarball/%s" %av, self.workdir) <NEW_LINE> self.run_shell_command("tar -xvf %s%s -C %s --strip-components=1" %(self.workdir, av, wd)) | Get the source for the dock applet.
If we're getting the source from git do a git clone if we don't already have
any source code, otherwise do go pull origin master.
If we're getting a specific version, hmmmm...
Note: the working directory must have been created before calling this .... | 625941bfb545ff76a8913d64 |
def testTargetFound(self): <NEW_LINE> <INDENT> self.injectEvent(vision.EventType.TARGET_FOUND, vision.TargetEvent, 0, 0, 0, 0, x = 0.5, y = -0.5, range = 4, squareNess = 1) <NEW_LINE> self.assertGreaterThan(self.controller.depth, self.estimator.depth) <NEW_LINE> self.assertGreaterThan(self.controller.speed, 0) <NEW_LINE> self.assertGreaterThan(self.controller.sidewaysSpeed, 0) <NEW_LINE> self.assertEqual(self.controller.yawChange, 0) | Make sure new found events move the vehicle | 625941bf57b8e32f524833e8 |
def factor(n): <NEW_LINE> <INDENT> prime_factors = [] <NEW_LINE> divisor = 2 <NEW_LINE> while n != 1: <NEW_LINE> <INDENT> exponent = 0 <NEW_LINE> while n % divisor == 0: <NEW_LINE> <INDENT> exponent += 1 <NEW_LINE> n = n / divisor <NEW_LINE> <DEDENT> if exponent > 0: <NEW_LINE> <INDENT> prime_factors.append((divisor, exponent)) <NEW_LINE> <DEDENT> divisor += 1 <NEW_LINE> <DEDENT> return prime_factors | Given n, computre its prime factorization and return in list of tuples
of (prime, exponent) where exponent is nonzero
TODO Probably needs to be programmed defensively, check that input >1, etc | 625941bf23e79379d52ee4b4 |
def solve_polinom(koefs, x_value): <NEW_LINE> <INDENT> return sum([koef(x_value) for koef in koefs]) | Вычисляет значение интерполянта в точке x
:param koefs: коэффициенты Лагранжа
:param x_value: значение точки x
:return: | 625941bf7c178a314d6ef3aa |
def zlib_stream(data): <NEW_LINE> <INDENT> return BytesIO(compress(data.encode())) | Return test data as a zlib-compressed stream.
| 625941bf4e4d5625662d4329 |
def process_request(self, request): <NEW_LINE> <INDENT> google_user = users.get_current_user() <NEW_LINE> account = None <NEW_LINE> is_admin = False <NEW_LINE> logging.info(request.META['HTTP_USER_AGENT']) <NEW_LINE> if google_user: <NEW_LINE> <INDENT> user_id = google_user.user_id() <NEW_LINE> is_admin = users.is_current_user_admin() <NEW_LINE> q = Account.all() <NEW_LINE> q.filter('google_user =', google_user) <NEW_LINE> account = q.get() <NEW_LINE> if not account: <NEW_LINE> <INDENT> nickname = hashlib.md5(google_user.nickname()).hexdigest()[:10] <NEW_LINE> account = Account(user_id = user_id, nickname = nickname) <NEW_LINE> account.put() <NEW_LINE> box = Box(title='My Box') <NEW_LINE> box.put() <NEW_LINE> <DEDENT> <DEDENT> request.user = account <NEW_LINE> Account.current_user_account = account <NEW_LINE> request.user_is_admin = is_admin | This function sets up the user object
Depending on the value of require_login, it
can return None as 'profile'. | 625941bf377c676e912720f7 |
def find_boundary_marker(self, face_index, markers): <NEW_LINE> <INDENT> for boundary_marker in markers: <NEW_LINE> <INDENT> for face in self.boundary_faces[boundary_marker]: <NEW_LINE> <INDENT> if face_index == face[0]: <NEW_LINE> <INDENT> return boundary_marker | Returns the boundary marker containing
face_index. | 625941bf8e71fb1e9831d6f9 |
def android(request): <NEW_LINE> <INDENT> return render(request, 'applications/applications_android.jade') | Applications > Android | 625941bf460517430c3940d9 |
def _uninstall( action='remove', name=None, version=None, pkgs=None, normalize=True, ignore_epoch=False, **kwargs): <NEW_LINE> <INDENT> if action not in ('remove', 'purge'): <NEW_LINE> <INDENT> return {'name': name, 'changes': {}, 'result': False, 'comment': 'Invalid action \'{0}\'. ' 'This is probably a bug.'.format(action)} <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> pkg_params = __salt__['pkg_resource.parse_targets']( name, pkgs, normalize=normalize)[0] <NEW_LINE> <DEDENT> except MinionError as exc: <NEW_LINE> <INDENT> return {'name': name, 'changes': {}, 'result': False, 'comment': 'An error was encountered while parsing targets: ' '{0}'.format(exc)} <NEW_LINE> <DEDENT> targets = _find_remove_targets(name, version, pkgs, normalize, ignore_epoch=ignore_epoch, **kwargs) <NEW_LINE> if isinstance(targets, dict) and 'result' in targets: <NEW_LINE> <INDENT> return targets <NEW_LINE> <DEDENT> elif not isinstance(targets, list): <NEW_LINE> <INDENT> return {'name': name, 'changes': {}, 'result': False, 'comment': 'An error was encountered while checking targets: ' '{0}'.format(targets)} <NEW_LINE> <DEDENT> if action == 'purge': <NEW_LINE> <INDENT> old_removed = __salt__['pkg.list_pkgs'](versions_as_list=True, removed=True, **kwargs) <NEW_LINE> targets.extend([x for x in pkg_params if x in old_removed]) <NEW_LINE> <DEDENT> targets.sort() <NEW_LINE> if not targets: <NEW_LINE> <INDENT> return {'name': name, 'changes': {}, 'result': True, 'comment': 'None of the targeted packages are installed' '{0}'.format(' or partially installed' if action == 'purge' else '')} <NEW_LINE> <DEDENT> if __opts__['test']: <NEW_LINE> <INDENT> return {'name': name, 'changes': {}, 'result': None, 'comment': 'The following packages will be {0}d: ' '{1}.'.format(action, ', '.join(targets))} <NEW_LINE> <DEDENT> changes = __salt__['pkg.{0}'.format(action)](name, pkgs=pkgs, version=version, **kwargs) <NEW_LINE> new = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs) <NEW_LINE> failed = [x for x in pkg_params if x in new] <NEW_LINE> if action == 'purge': <NEW_LINE> <INDENT> new_removed = __salt__['pkg.list_pkgs'](versions_as_list=True, removed=True, **kwargs) <NEW_LINE> failed.extend([x for x in pkg_params if x in new_removed]) <NEW_LINE> <DEDENT> failed.sort() <NEW_LINE> if failed: <NEW_LINE> <INDENT> return {'name': name, 'changes': changes, 'result': False, 'comment': 'The following packages failed to {0}: ' '{1}.'.format(action, ', '.join(failed))} <NEW_LINE> <DEDENT> comments = [] <NEW_LINE> not_installed = sorted([x for x in pkg_params if x not in targets]) <NEW_LINE> if not_installed: <NEW_LINE> <INDENT> comments.append('The following packages were not installed: ' '{0}'.format(', '.join(not_installed))) <NEW_LINE> comments.append('The following packages were {0}d: ' '{1}.'.format(action, ', '.join(targets))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> comments.append('All targeted packages were {0}d.'.format(action)) <NEW_LINE> <DEDENT> return {'name': name, 'changes': changes, 'result': True, 'comment': ' '.join(comments)} | Common function for package removal | 625941bf63f4b57ef000106e |
def samplemixinmethod(method): <NEW_LINE> <INDENT> method.__issamplemixin__ = True <NEW_LINE> return method | Marks a method as being a mixin.
Adds the '__issamplemixin__' attribute with value True to the decorated function.
Examples:
>>> @samplemixinmethod
>>> def f():
... pass
>>> f.__issamplemixin__
True | 625941bfec188e330fd5a6f2 |
def shift_down(self, num = 1): <NEW_LINE> <INDENT> return self.shift(0, num) | Moves the selector down, but number of rows given by "num" parameter. | 625941bff548e778e58cd4cb |
def in_place_uniform_shuffle(the_list): <NEW_LINE> <INDENT> n = len(the_list) <NEW_LINE> for i in xrange(0, n - 1): <NEW_LINE> <INDENT> j = get_random(i, n - 1) <NEW_LINE> the_list[i], the_list[j] = the_list[j], the_list[i] | in place shuffle of a the_list | 625941bf7d847024c06be208 |
@app.route('/restart') <NEW_LINE> @requires_auth <NEW_LINE> def app_restart_parsec(): <NEW_LINE> <INDENT> ext = kill_process('parsecd.exe') <NEW_LINE> print('We tried to kill parsec with response:\n', ext) <NEW_LINE> error = 'An unknown error has happened. I think you should take a peak at the console for this!' <NEW_LINE> if str(ext) == '0': <NEW_LINE> <INDENT> time.sleep(1) <NEW_LINE> test = str(kill_process('parsecd.exe')) <NEW_LINE> if test == '128' or test == '0': <NEW_LINE> <INDENT> ext = start_parsec() <NEW_LINE> print('Attempting to start Parsec Daemon with exit code: ', ext) <NEW_LINE> return flask.render_template('success.html') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error = 'Parsec daemon could not be stopped.' <NEW_LINE> <DEDENT> <DEDENT> if str(ext) == '128': <NEW_LINE> <INDENT> error = 'Parsec was not running at this time. Please try going to /start' <NEW_LINE> <DEDENT> return flask.render_template('error.html', error = error) | Kills parsec's daemon and returns a HTTP response | 625941bf379a373c97cfaa92 |
def initial_solution(weights1, weights2, max_cost): <NEW_LINE> <INDENT> from subprocess import check_output <NEW_LINE> max_weights = max(np.max(weights1), np.max(weights2)) <NEW_LINE> inarg = '{} {}\n{} {}\n'.format(weights1.size, weights2.size, max_cost, max_weights) <NEW_LINE> inarg += ' '.join([str(float(_)) for _ in weights1]) <NEW_LINE> inarg += '\n' + ' '.join([str(float(_)) for _ in weights1]) <NEW_LINE> with open('in', 'w') as args: <NEW_LINE> <INDENT> args.write(inarg) <NEW_LINE> <DEDENT> res = check_output('./a.out < in'.format(inarg), shell=True) <NEW_LINE> return [float(_) for _ in res.split()] | Find an initial solution using russel method from the Yossi Rubner
implemention. | 625941bf24f1403a92600ab7 |
def solid(self, color=_dark): <NEW_LINE> <INDENT> for led in range(LED_COUNT): <NEW_LINE> <INDENT> self.leds[led] = color <NEW_LINE> <DEDENT> self.__show() | Light all leds in single colour | 625941c03c8af77a43ae36ed |
def __auth(self, json_received, request): <NEW_LINE> <INDENT> print(json_received) <NEW_LINE> user = self.__return_username(json_received) <NEW_LINE> if user is not None: <NEW_LINE> <INDENT> self.common_request.update({user: request}) <NEW_LINE> json_response = (self.__make_json_from_attribute_user (self.__get_attribute_user (get_specific_user(user),1) ) ) <NEW_LINE> return request.websocket.send(json_response) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> request.websocket.send(self.__make_json_error("auth", 6)) | метод аутентификации
:param json: аутентификации
:param request: сокет - соединение
:return: сообщение клиенту | 625941c06e29344779a62563 |
def load(self): <NEW_LINE> <INDENT> if os.path.isfile(self.filename): <NEW_LINE> <INDENT> logger.debug('loading code database...') <NEW_LINE> f = file(self.filename, 'rb') <NEW_LINE> self._database = cPickle.load(f) <NEW_LINE> f.close() <NEW_LINE> logger.debug('code database loaded.') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._database = {} <NEW_LINE> <DEDENT> return | Load the code browser 'database'. | 625941c0656771135c3eb7bb |
def stop(self): <NEW_LINE> <INDENT> self.doQuit.set() | Set a flag to indicate that the sound thread should end. | 625941c0187af65679ca506d |
def deleteDuplicates(self, head): <NEW_LINE> <INDENT> curr = head <NEW_LINE> while curr and curr.next: <NEW_LINE> <INDENT> if curr.val == curr.next.val: <NEW_LINE> <INDENT> curr.next=curr.next.next <NEW_LINE> <DEDENT> if curr.next is not None: <NEW_LINE> <INDENT> if curr.val!=curr.next.val: <NEW_LINE> <INDENT> curr = curr.next <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return head | :type head: ListNode
:rtype: ListNode | 625941c01f037a2d8b94614d |
def test_future_question(self): <NEW_LINE> <INDENT> future_question = create_question(question_text="Future question", days=5) <NEW_LINE> url = reverse("polls:results", args=(future_question.id,)) <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEqual(response.status_code, 404) | Test that the Result View won't show any future question (ResultView.get_queryset works) | 625941c0bd1bec0571d9057d |
def keltner_channel(df, n): <NEW_LINE> <INDENT> KelChM = pd.Series(((df['High'] + df['Low'] + df['Close']) / 3).rolling(n, min_periods=n).mean(), name='KelChM_' + str(n)) <NEW_LINE> KelChU = pd.Series(((4 * df['High'] - 2 * df['Low'] + df['Close']) / 3).rolling(n, min_periods=n).mean(), name='KelChU_' + str(n)) <NEW_LINE> KelChD = pd.Series(((-2 * df['High'] + 4 * df['Low'] + df['Close']) / 3).rolling(n, min_periods=n).mean(), name='KelChD_' + str(n)) <NEW_LINE> df = df.join(KelChM) <NEW_LINE> df = df.join(KelChU) <NEW_LINE> df = df.join(KelChD) <NEW_LINE> return df | Calculate Keltner Channel for given data.
:param df: pandas.DataFrame
:param n:
:return: pandas.DataFrame | 625941c015fb5d323cde0a5b |
def _nodal_planes(self, obj, element): <NEW_LINE> <INDENT> subelement = etree.Element('nodalPlanes') <NEW_LINE> if obj.nodal_plane_1: <NEW_LINE> <INDENT> el = etree.Element('nodalPlane1') <NEW_LINE> self._value(obj.nodal_plane_1.strike, obj.nodal_plane_1.strike_errors, el, 'strike') <NEW_LINE> self._value(obj.nodal_plane_1.dip, obj.nodal_plane_1.dip_errors, el, 'dip') <NEW_LINE> self._value(obj.nodal_plane_1.rake, obj.nodal_plane_1.rake_errors, el, 'rake') <NEW_LINE> self._extra(obj.nodal_plane_1, el) <NEW_LINE> subelement.append(el) <NEW_LINE> <DEDENT> if obj.nodal_plane_2: <NEW_LINE> <INDENT> el = etree.Element('nodalPlane2') <NEW_LINE> self._value(obj.nodal_plane_2.strike, obj.nodal_plane_2.strike_errors, el, 'strike') <NEW_LINE> self._value(obj.nodal_plane_2.dip, obj.nodal_plane_2.dip_errors, el, 'dip') <NEW_LINE> self._value(obj.nodal_plane_2.rake, obj.nodal_plane_2.rake_errors, el, 'rake') <NEW_LINE> self._extra(obj.nodal_plane_2, el) <NEW_LINE> subelement.append(el) <NEW_LINE> <DEDENT> if obj.preferred_plane: <NEW_LINE> <INDENT> subelement.attrib['preferredPlane'] = str(obj.preferred_plane) <NEW_LINE> <DEDENT> self._extra(obj, subelement) <NEW_LINE> if len(subelement) > 0: <NEW_LINE> <INDENT> element.append(subelement) | Converts a NodalPlanes into etree.Element object.
:type pick: :class:`~obspy.core.event.NodalPlanes`
:rtype: etree.Element | 625941c0b5575c28eb68df4e |
def getNextNode(self, point, axis, amount): <NEW_LINE> <INDENT> p = list(point) <NEW_LINE> p[axis] += amount <NEW_LINE> return tuple(p) | Increments the <axis> dimension in the point by <amount> | 625941c04f88993c3716bfb9 |
def test_create_wrapper_validator(self): <NEW_LINE> <INDENT> inmap = self.std_map() <NEW_LINE> inmap.update({'foreign data wrapper fdw1': { 'validator': 'postgresql_fdw_validator'}}) <NEW_LINE> sql = self.to_sql(inmap) <NEW_LINE> assert fix_indent(sql[0]) == "CREATE FOREIGN DATA WRAPPER fdw1 " "VALIDATOR postgresql_fdw_validator" | Create a foreign data wrapper with a validator function | 625941c08a43f66fc4b53fb6 |
def qryMarketData(self): <NEW_LINE> <INDENT> self.reqID += 1 <NEW_LINE> req = {} <NEW_LINE> self.reqQryDepthMarketData(req, self.reqID) | 查询合约截面数据 | 625941c08a43f66fc4b53fb7 |
def trunk_add_subports(self, tenant_id, trunk_id, sub_ports): <NEW_LINE> <INDENT> spec = { 'tenant_id': tenant_id, 'sub_ports': sub_ports, } <NEW_LINE> trunk = self.client.trunk_add_subports(trunk_id, spec) <NEW_LINE> sub_ports_to_remove = [ sub_port for sub_port in trunk['sub_ports'] if sub_port in sub_ports] <NEW_LINE> self.addCleanup( _safe_method(self.trunk_remove_subports), tenant_id, trunk_id, sub_ports_to_remove) | Add subports to the trunk.
:param tenant_id: ID of the tenant.
:param trunk_id: ID of the trunk.
:param sub_ports: List of subport dictionaries to be added in format
{'port_id': <ID of neutron port for subport>,
'segmentation_type': 'vlan',
'segmentation_id': <VLAN tag>} | 625941c0090684286d50ec32 |
def organization_update( context: Context, data_dict: DataDict) -> ActionResult.OrganizationUpdate: <NEW_LINE> <INDENT> return _group_or_org_update(context, data_dict, is_org=True) | Update a organization.
You must be authorized to edit the organization.
.. note:: Update methods may delete parameters not explicitly provided in the
data_dict. If you want to edit only a specific attribute use `organization_patch`
instead.
For further parameters see
:py:func:`~ckan.logic.action.create.organization_create`.
:param id: the name or id of the organization to update
:type id: string
:param packages: ignored. use
:py:func:`~ckan.logic.action.update.package_owner_org_update`
to change package ownership
:returns: the updated organization
:rtype: dictionary | 625941c0fff4ab517eb2f389 |
def handle(self, msgType, di): <NEW_LINE> <INDENT> assert self.notify.debugCall() <NEW_LINE> if msgType not in self.__type2message: <NEW_LINE> <INDENT> self.notify.warning('Received unknown message: %d' % msgType) <NEW_LINE> return <NEW_LINE> <DEDENT> message = self.__type2message[msgType] <NEW_LINE> sentArgs=loads(di.getString()) <NEW_LINE> if type(sentArgs) != list: <NEW_LINE> <INDENT> self.notify.warning('Received non-list item in %s message: %r' % (message, sentArgs)) <NEW_LINE> return <NEW_LINE> <DEDENT> Messenger.send(self, message, sentArgs=sentArgs) | Send data from the net on the local netMessenger. | 625941c076d4e153a657ea7f |
def test_create_should_register_new_session_with_keys(self): <NEW_LINE> <INDENT> label = self.session.create_dynamodb_session(access_key='key', secret_key='secret') <NEW_LINE> try: <NEW_LINE> <INDENT> self.session._cache.switch(label) <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> self.fail("Label '%s' should be exist." % label) <NEW_LINE> <DEDENT> self.session.delete_all_dynamodb_sessions() | Create session should successfully register new session with keys. | 625941c0d486a94d0b98e094 |
def main(): <NEW_LINE> <INDENT> factorions = [] <NEW_LINE> for x in range(10,50001): <NEW_LINE> <INDENT> fac_sum = 0 <NEW_LINE> s = str(x) <NEW_LINE> for digit in s: <NEW_LINE> <INDENT> num = int(digit) <NEW_LINE> fac_sum += factorial(num) <NEW_LINE> <DEDENT> if fac_sum == x: <NEW_LINE> <INDENT> factorions.append(x) <NEW_LINE> <DEDENT> <DEDENT> print(sum(factorions)) <NEW_LINE> print("---%s seconds---" %(t.time()-start)) | Finds the sum off all factorions (exluding 1 and 2). | 625941c0cad5886f8bd26f29 |
def predict(self, x_test, k=5, wt='distance'): <NEW_LINE> <INDENT> target = self.data_raw.shape[1]-1 <NEW_LINE> x_train = self.codebook.matrix[:, :target] <NEW_LINE> y_train = self.codebook.matrix[:, target] <NEW_LINE> clf = neighbors.KNeighborsRegressor(k, weights=wt) <NEW_LINE> clf.fit(x_train, y_train) <NEW_LINE> x_test = self._normalizer.normalize_by(self.data_raw[:, :target], x_test) <NEW_LINE> predicted_values = clf.predict(x_test) <NEW_LINE> return self._normalizer.denormalize_by(self.data_raw[:, target], predicted_values) | Similar to SKlearn we assume that we have X_tr, Y_tr and X_test. Here it is assumed that target is the last
column in the codebook and data has dim-1 columns
:param x_test: input vector
:param k: number of neighbors to use
:param wt: method to use for the weights (more detail in KNeighborsRegressor docs)
:returns: predicted values for the input data | 625941c038b623060ff0ad3d |
def load_sample_images(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from scipy.misc import imread <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> from scipy.misc.pilutil import imread <NEW_LINE> <DEDENT> <DEDENT> except ImportError: <NEW_LINE> <INDENT> raise ImportError("The Python Imaging Library (PIL)" "is required to load data from jpeg files") <NEW_LINE> <DEDENT> module_path = join(dirname(__file__), "images") <NEW_LINE> with open(join(module_path, 'README.txt')) as f: <NEW_LINE> <INDENT> descr = f.read() <NEW_LINE> <DEDENT> filenames = [join(module_path, filename) for filename in os.listdir(module_path) if filename.endswith(".jpg")] <NEW_LINE> images = [imread(filename) for filename in filenames] <NEW_LINE> return Bunch(images=images, filenames=filenames, DESCR=descr) | Load sample images for image manipulation.
Loads both, ``china`` and ``flower``.
Return
------
data : Bunch
Dictionary-like object with the following attributes :
'images', the two sample images, 'filenames', the file
names for the images, and 'DESCR'
the full description of the dataset.
Examples
--------
To load the data and visualize the images::
# >>> from sklearn.datasets import load_sample_images
# >>> dataset = load_sample_images()
# >>> len(dataset.images)
# 2
# >>> first_img_data = dataset.images[0]
# >>> first_img_data.shape
# (427, 640, 3)
# >>> first_img_data.dtype
# dtype('uint8')
# >>> import pylab as pl
# >>> pl.gray()
# >>> pl.matshow(dataset.images[0]) # Visualize the first image
# >>> pl.show() | 625941c00c0af96317bb8137 |
@register.inclusion_tag('rbac/breadcrumb.html') <NEW_LINE> def breadcrumb(request): <NEW_LINE> <INDENT> return {'breadcrumb_list': request.breadcrumb_list} | 面包屑导航 | 625941c0293b9510aa2c31e7 |
def test_get_base_players(self): <NEW_LINE> <INDENT> players = self.x.get_base_players() <NEW_LINE> player = random.choice(players) <NEW_LINE> logging.info(player) <NEW_LINE> self.assertIsInstance(players, list) <NEW_LINE> self.assertGreater(len(players), 50) <NEW_LINE> self.assertIn('player_id', player.keys()) | Returns: | 625941c01d351010ab855a6c |
def sigmoid(self, x): <NEW_LINE> <INDENT> return 1 / (1 + np.exp(-x)) | pega os valores das somas do input e normaliza esses valores atraves de uma sigmoid
ou seja os valores das somas dos inputs estarão entre 0 e 1 | 625941c08e05c05ec3eea2c2 |
def remove(self, key): <NEW_LINE> <INDENT> if self.key == key: <NEW_LINE> <INDENT> if self.right and self.left: <NEW_LINE> <INDENT> [psucc, succ] = self.right._findMin(self) <NEW_LINE> if psucc.left == succ: <NEW_LINE> <INDENT> psucc.left = succ.right <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> psucc.right = succ.right <NEW_LINE> <DEDENT> succ.left = self.left <NEW_LINE> succ.right = self.right <NEW_LINE> return succ <NEW_LINE> <DEDENT> elif self.left: <NEW_LINE> <INDENT> return self.left <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.right <NEW_LINE> <DEDENT> <DEDENT> elif self.key < key: <NEW_LINE> <INDENT> if self.right: <NEW_LINE> <INDENT> self.right = self.right.remove(key) <NEW_LINE> <DEDENT> <DEDENT> elif self.key > key: <NEW_LINE> <INDENT> if self.left: <NEW_LINE> <INDENT> self.left = self.left.remove(key) <NEW_LINE> <DEDENT> <DEDENT> return self | Delete node and balance the tree
Case 1: not left or right child
Case 2: has one left or right child
Case 3: has left and right child
:param key:
:return: | 625941c0091ae35668666eb2 |
def menu_func (self, context): <NEW_LINE> <INDENT> self.layout.operator (import_dsf_pose.bl_idname, text = 'dsf-pose (.d[su]f)') | display the menu entry for calling the importer. | 625941c097e22403b379cee8 |
def encode_check(payload): <NEW_LINE> <INDENT> checksum = double_sha256(payload, True)[:4] <NEW_LINE> if payload[0] == 0x00: <NEW_LINE> <INDENT> return b58encode(b'\x00') + b58encode(payload[1:] + checksum) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return b58encode(payload + checksum) | Returns the base58 encoding with a 4-byte checksum.
:param payload: The data (as bytes) to encode. | 625941c067a9b606de4a7e0a |
def get_hardware_fcport(self, hardware_fcport_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async'): <NEW_LINE> <INDENT> return self.get_hardware_fcport_with_http_info(hardware_fcport_id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.get_hardware_fcport_with_http_info(hardware_fcport_id, **kwargs) <NEW_LINE> return data | get_hardware_fcport # noqa: E501
Get one fibre-channel port # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_hardware_fcport(hardware_fcport_id, async=True)
>>> result = thread.get()
:param async bool
:param int hardware_fcport_id: Get one fibre-channel port (required)
:param str lnn: Logical node number.
:return: HardwareFcports
If the method is called asynchronously,
returns the request thread. | 625941c03617ad0b5ed67e48 |
def example_H2O2_TS(): <NEW_LINE> <INDENT> h2o2 = molkit.from_smarts('[H]OO[H]') <NEW_LINE> dihe = Dihedral(1, 2, 3, 4) <NEW_LINE> s1 = Settings() <NEW_LINE> s1.constraint.update(dihe.get_settings(0.0)) <NEW_LINE> dftb_opt = dftb(templates.geometry.overlay(s1), h2o2) <NEW_LINE> dftb_freq = dftb(templates.freq, dftb_opt.molecule) <NEW_LINE> s2 = Settings() <NEW_LINE> s2.inithess = dftb_freq.hessian <NEW_LINE> orca_ts = orca(templates.ts.overlay(s2), dftb_opt.molecule) <NEW_LINE> result = run(orca_ts) <NEW_LINE> ts_dihe = round(dihe.get_current_value(result.molecule)) <NEW_LINE> n_optcycles = result.optcycles <NEW_LINE> print('Dihedral angle (degrees): {:.0f}'.format(ts_dihe)) <NEW_LINE> print('Number of optimization cycles: {:d}'.format(n_optcycles)) <NEW_LINE> return ts_dihe, n_optcycles | This example generates an approximate TS for rotation in hydrogen peroxide
using DFTB, and performs a full TS optimization in Orca.
It illustrates using a hessian from one package, DFTB in this case,
to initialize a TS optimization in another, i.e. Orca in this case | 625941c0de87d2750b85fcdf |
def from_vector(self, vector, order=None): <NEW_LINE> <INDENT> if order is None: <NEW_LINE> <INDENT> order = self.get_order() <NEW_LINE> <DEDENT> return self._from_dict({order[index]: coeff for (index, coeff) in vector.items()}) | Build an element of ``self`` from a (sparse) vector.
.. SEEALSO:: :meth:`get_order`, :meth:`CombinatorialFreeModule.Element._vector_`
EXAMPLES::
sage: QS3 = SymmetricGroupAlgebra(QQ, 3)
sage: b = QS3.from_vector(vector((2, 0, 0, 0, 0, 4))); b
2*[1, 2, 3] + 4*[3, 2, 1]
sage: a = 2*QS3([1,2,3])+4*QS3([3,2,1])
sage: a == b
True | 625941c01f5feb6acb0c4aa3 |
def __init__(self, data_path): <NEW_LINE> <INDENT> self.data_path = data_path <NEW_LINE> with open(os.path.join(self.data_path, 'config.yaml')) as fin: <NEW_LINE> <INDENT> self.config = yaml.load(fin) <NEW_LINE> <DEDENT> for p in [self.exif_path(), self.feature_path(), self.robust_matches_path()]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.makedirs(p) <NEW_LINE> <DEDENT> except os.error as exc: <NEW_LINE> <INDENT> if exc.errno == errno.EEXIST and os.path.isdir(p): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise | Create dataset instance. Empty directories (for EXIF, robust matches, etc) will be created if they don't exist
already.
:param data_path: Path to directory containing dataset | 625941c030c21e258bdfa3eb |
def __init__(self, py_dict=None): <NEW_LINE> <INDENT> super(DNSSettingsSchema, self).__init__() <NEW_LINE> self.domain_name = None <NEW_LINE> self.primary_dns = None <NEW_LINE> self.secondary_dns = None <NEW_LINE> if py_dict is not None: <NEW_LINE> <INDENT> self.get_object_from_py_dict(py_dict) | Constructor to create DNSSettingsSchema object
@param py_dict : python dictionary to construct this object | 625941c0596a897236089a13 |
def _frame_generator(self, a): <NEW_LINE> <INDENT> for i in a: <NEW_LINE> <INDENT> yield self[i] | Return a generator that produces each frame identified by ID in `a`. | 625941c08c0ade5d55d3e908 |
def __init__(self, code, fam=None, user=None, sysop=None): <NEW_LINE> <INDENT> if code.lower() != code: <NEW_LINE> <INDENT> pywikibot.log(u'BaseSite: code "%s" converted to lowercase' % code) <NEW_LINE> code = code.lower() <NEW_LINE> <DEDENT> if not all(x in pywikibot.family.CODE_CHARACTERS for x in str(code)): <NEW_LINE> <INDENT> pywikibot.log(u'BaseSite: code "%s" contains invalid characters' % code) <NEW_LINE> <DEDENT> self.__code = code <NEW_LINE> if isinstance(fam, basestring) or fam is None: <NEW_LINE> <INDENT> self.__family = pywikibot.family.Family.load(fam) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__family = fam <NEW_LINE> <DEDENT> self.obsolete = False <NEW_LINE> if self.__code in self.__family.obsolete: <NEW_LINE> <INDENT> if self.__family.obsolete[self.__code] is not None: <NEW_LINE> <INDENT> self.__code = self.__family.obsolete[self.__code] <NEW_LINE> pywikibot.log(u'Site %s instantiated using code %s' % (self, code)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.obsolete = True <NEW_LINE> pywikibot.log(u'Site %s instantiated and marked "obsolete" ' u'to prevent access' % self) <NEW_LINE> <DEDENT> <DEDENT> elif self.__code not in self.languages(): <NEW_LINE> <INDENT> if self.__family.name in list(self.__family.langs.keys()) and len(self.__family.langs) == 1: <NEW_LINE> <INDENT> self.__code = self.__family.name <NEW_LINE> if self.__family == pywikibot.config.family and code == pywikibot.config.mylang: <NEW_LINE> <INDENT> pywikibot.config.mylang = self.__code <NEW_LINE> warn(u'Global configuration variable "mylang" changed to ' u'"%s" while instantiating site %s' % (self.__code, self), UserWarning) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise UnknownSite(u"Language '%s' does not exist in family %s" % (self.__code, self.__family.name)) <NEW_LINE> <DEDENT> <DEDENT> self._username = [normalize_username(user), normalize_username(sysop)] <NEW_LINE> self.use_hard_category_redirects = ( self.code in self.family.use_hard_category_redirects) <NEW_LINE> self._pagemutex = threading.Lock() <NEW_LINE> self._locked_pages = [] | Constructor.
@param code: the site's language code
@type code: str
@param fam: wiki family name (optional)
@type fam: str or Family
@param user: bot user name (optional)
@type user: str
@param sysop: sysop account user name (optional)
@type sysop: str | 625941c0b830903b967e985d |
def find_inorder_first_node(p): <NEW_LINE> <INDENT> if p is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> node = p <NEW_LINE> while not node.ltag and node.left is not None: <NEW_LINE> <INDENT> node = node.left <NEW_LINE> <DEDENT> return node | 找到子树 p 的中序序列的第一个节点 | 625941c0566aa707497f44bc |
def ts(self): <NEW_LINE> <INDENT> from .timeseries import TimeSeries <NEW_LINE> s = TimeSeries(client=self) <NEW_LINE> return s | Access the timeseries namespace, providing support for
redis timeseries data. | 625941c0d6c5a10208143f98 |
def check_command_type_struct_fields( ctxt: IDLCompatibilityContext, old_type: syntax.Struct, new_type: syntax.Struct, cmd_name: str, old_idl_file: syntax.IDLParsedSpec, new_idl_file: syntax.IDLParsedSpec, old_idl_file_path: str, new_idl_file_path: str): <NEW_LINE> <INDENT> for old_field in old_type.fields or []: <NEW_LINE> <INDENT> if old_field.unstable: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> new_field_exists = False <NEW_LINE> for new_field in new_type.fields or []: <NEW_LINE> <INDENT> if new_field.name == old_field.name: <NEW_LINE> <INDENT> new_field_exists = True <NEW_LINE> check_command_type_struct_field(ctxt, old_type.name, old_field, new_field, cmd_name, old_idl_file, new_idl_file, old_idl_file_path, new_idl_file_path) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if not new_field_exists: <NEW_LINE> <INDENT> ctxt.add_new_command_type_field_missing_error(cmd_name, old_type.name, old_field.name, old_idl_file_path) | Check compatibility between old and new type fields. | 625941c0167d2b6e31218ae6 |
def SetExpanded(self, expanded): <NEW_LINE> <INDENT> if expanded != self.IsExpanded(): <NEW_LINE> <INDENT> self.Collapse(not expanded) <NEW_LINE> self.OnPaneChanged() | Set whether the contained widget is collapsed or expanded. If there will be no change, don't do anything. | 625941c050485f2cf553cce8 |
def seek(self, time): <NEW_LINE> <INDENT> command = 'seek ' + str(time) <NEW_LINE> self.run_command(command) | Seek in seconds, for instance 'seek 12'. | 625941c04c3428357757c27a |
def parse_gc_dist(self, f): <NEW_LINE> <INDENT> s_name = self.get_s_name(f) <NEW_LINE> d = dict() <NEW_LINE> reference_species = None <NEW_LINE> reference_d = dict() <NEW_LINE> avg_gc = 0 <NEW_LINE> for l in f['f']: <NEW_LINE> <INDENT> if l.startswith('#'): <NEW_LINE> <INDENT> sections = l.strip("\n").split("\t", 3) <NEW_LINE> if len(sections) > 2: <NEW_LINE> <INDENT> reference_species = sections[2] <NEW_LINE> <DEDENT> continue <NEW_LINE> <DEDENT> sections = l.strip("\n").split("\t", 3) <NEW_LINE> gc = int(round(float(sections[0]))) <NEW_LINE> content = float(sections[1]) <NEW_LINE> avg_gc += gc * content <NEW_LINE> d[gc] = content <NEW_LINE> if len(sections) > 2: <NEW_LINE> <INDENT> reference_content = float(sections[2]) <NEW_LINE> reference_d[gc] = reference_content <NEW_LINE> <DEDENT> <DEDENT> self.general_stats_data[s_name]['avg_gc'] = avg_gc <NEW_LINE> if s_name in self.qualimap_bamqc_gc_content_dist: <NEW_LINE> <INDENT> log.debug("Duplicate Mapped Reads GC content distribution sample name found! Overwriting: {}".format(s_name)) <NEW_LINE> <DEDENT> self.qualimap_bamqc_gc_content_dist[s_name] = d <NEW_LINE> if reference_species and reference_species not in self.qualimap_bamqc_gc_by_species: <NEW_LINE> <INDENT> self.qualimap_bamqc_gc_by_species[reference_species] = reference_d <NEW_LINE> <DEDENT> self.add_data_source(f, s_name=s_name, section='mapped_gc_distribution') | Parse the contents of the Qualimap BamQC Mapped Reads GC content distribution file | 625941c097e22403b379cee9 |
def read_var_header(self): <NEW_LINE> <INDENT> hdr = self._matrix_reader.read_header() <NEW_LINE> n = reduce(lambda x, y: x*y, hdr.dims, 1) <NEW_LINE> remaining_bytes = hdr.dtype.itemsize * n <NEW_LINE> if hdr.is_complex and not hdr.mclass == mxSPARSE_CLASS: <NEW_LINE> <INDENT> remaining_bytes *= 2 <NEW_LINE> <DEDENT> next_position = self.mat_stream.tell() + remaining_bytes <NEW_LINE> return hdr, next_position | Read and return header, next position
Parameters
----------
None
Returns
-------
header : object
object that can be passed to self.read_var_array, and that
has attributes ``name`` and ``is_global``
next_position : int
position in stream of next variable | 625941c0507cdc57c6306c25 |
def draw(self, objects): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for obj in objects: <NEW_LINE> <INDENT> obj.draw(self.__screen) <NEW_LINE> <DEDENT> <DEDENT> except TypeError: <NEW_LINE> <INDENT> objects.draw(self.__screen) | Draws all of the given objects onto the screen.
:param objects: The objects to draw onto the screen. Can be a single object or a list of objects | 625941c09c8ee82313fbb6c4 |
def __init__(self, returnType, name, *arguments, **kargs): <NEW_LINE> <INDENT> super(ApiFunction, self).__init__(returnType) <NEW_LINE> self.tagName = name <NEW_LINE> self.name = name <NEW_LINE> self.returnAttribute = None <NEW_LINE> self.fixedAttributes = {} <NEW_LINE> if kargs: <NEW_LINE> <INDENT> if 'tagName' in kargs: <NEW_LINE> <INDENT> self.tagName = kargs['tagName'] <NEW_LINE> <DEDENT> if 'returnAttribute' in kargs: <NEW_LINE> <INDENT> self.returnAttribute = kargs['returnAttribute'] <NEW_LINE> <DEDENT> <DEDENT> for argument in arguments: <NEW_LINE> <INDENT> self.addArgument(*argument) | function arguments are expected to be tuples
containing: (type, name, isReference)
Keyword arguments allowed:
tagName - POSXML tag to be generated
returnAttribute - POSXML tag attribute that represents
the return value of the function. | 625941c0f7d966606f6a9f51 |
def unif(n): <NEW_LINE> <INDENT> return np.ones((n,))/n | return a uniform histogram of length n (simplex)
Parameters
----------
n : int
number of bins in the histogram
Returns
-------
h : np.array (n,)
histogram of length n such that h_i=1/n for all i | 625941c030dc7b76659018b8 |
def __init__(self, name, lSites, lDirection, lDepth, lWidth=0.5): <NEW_LINE> <INDENT> GPE.__init__(self, name) <NEW_LINE> self.setString("externalPotential", "lattice") <NEW_LINE> self.set("latticeSites", lSites) <NEW_LINE> self.set("latticeDirection", lDirection) <NEW_LINE> self.set("latticeDepth", lDepth) <NEW_LINE> if not hasattr(lWidth, '__getitem__'): <NEW_LINE> <INDENT> lWidth = 3 * [lWidth] <NEW_LINE> <DEDENT> self.set("latticeWidthX", lWidth[0]) <NEW_LINE> self.set("latticeWidthY", lWidth[1]) <NEW_LINE> self.set("latticeWidthZ", lWidth[2]) <NEW_LINE> sigma = [0, 0, 0] <NEW_LINE> for i in range(0, 3): <NEW_LINE> <INDENT> sigma[i] = math.sqrt(lWidth[i]/(2.0 * math.sqrt(lDepth))) <NEW_LINE> <DEDENT> if lSites > 1: <NEW_LINE> <INDENT> sigmaLat = 1.2 * (lSites - 1) / 2 <NEW_LINE> sigma[lDirection] = sigmaLat <NEW_LINE> <DEDENT> self.set("sigmaX", sigma[0]) <NEW_LINE> self.set("sigmaY", sigma[1]) <NEW_LINE> self.set("sigmaZ", sigma[2]) <NEW_LINE> maxP = [0, 0, 0] <NEW_LINE> for i in range(0, 3): <NEW_LINE> <INDENT> maxP[i] = 6 * lWidth[i] <NEW_LINE> <DEDENT> maxPLat = 2.0 + (float(lSites) - 1) / 2 <NEW_LINE> maxP[lDirection] = maxPLat <NEW_LINE> self.setMax(maxP[0], maxP[1], maxP[2]) | lSites: number of lattice sites
lDirection: 0, 1, 2 for x, y or z direction
lDepth: prefactor of the potential V0: - V0 * exp(...)
lWidth: either a single number or a vector of 3 different widths of the single well | 625941c0e64d504609d74790 |
def configurar_gnome(): <NEW_LINE> <INDENT> shell = Shell(AcaoQuandoOcorrerErro.REPETIR_E_IGNORAR, 10) <NEW_LINE> shell.executar("gsettings set org.gnome.desktop.interface enable-hot-corners false") <NEW_LINE> shell.executar("gsettings set org.gnome.desktop.interface clock-show-seconds true") <NEW_LINE> shell.executar("gsettings set org.gnome.desktop.interface clock-show-weekday true") <NEW_LINE> shell.executar("gsettings set org.gnome.desktop.interface show-battery-percentage true") <NEW_LINE> shell.executar("gsettings set org.gnome.desktop.datetime automatic-timezone true") <NEW_LINE> shell.executar("gsettings set org.gnome.desktop.media-handling autorun-never true") <NEW_LINE> shell.executar("gsettings set org.gnome.mutter experimental-features \"['scale-monitor-framebuffer']\"") | Configura o Gnome personalizando as configurações. | 625941c0090684286d50ec33 |
def _parse(url): <NEW_LINE> <INDENT> url = url.strip() <NEW_LINE> if not re.match(r'^\w+://', url): <NEW_LINE> <INDENT> url = '//' + url <NEW_LINE> <DEDENT> parsed = urlparse(url) <NEW_LINE> return _parsed_url_args(parsed) | Return tuple of (scheme, netloc, host, port, path),
all in bytes except for port which is int.
Assume url is from Request.url, which was passed via safe_url_string
and is ascii-only. | 625941c0287bf620b61d39b5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.