code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def rank_per_file_throughput(self, sources, dst): <NEW_LINE> <INDENT> ranks = [] <NEW_LINE> for src in sources: <NEW_LINE> <INDENT> per_file_throughput = self.cls.get_per_file_throughput(src, dst) <NEW_LINE> if per_file_throughput == 0: <NEW_LINE> <INDENT> return Scheduler.select_source(src, per_file_throughput) <NEW_L... | Ranks the source sites based on the per file throughput rate between
a source destination pair in the last 1 hour | 625941e7167d2b6e31219005 |
def meap93(path): <NEW_LINE> <INDENT> import pandas as pd <NEW_LINE> path = os.path.expanduser(path) <NEW_LINE> filename = 'meap93.csv' <NEW_LINE> if not os.path.exists(os.path.join(path, filename)): <NEW_LINE> <INDENT> url = 'http://dustintran.com/data/r/wooldridge/meap93.csv' <NEW_LINE> maybe_download_and_extract(pat... | meap93
Data loads lazily. Type data(meap93) into the console.
A data.frame with 408 rows and 17 variables:
- lnchprg. perc of studs in sch lnch prog
- enroll. school enrollment
- staff. staff per 1000 students
- expend. expend. per stud, $
- salary. avg. teacher salary, $
- benefits. avg. ... | 625941e7fb3f5b602dac3b08 |
def translate(self, sym_count, func_param=False): <NEW_LINE> <INDENT> result = {'emit': "", 'result': ""} <NEW_LINE> if self.node_type == DATA_TYPE.BS_INT_DECL: <NEW_LINE> <INDENT> if func_param is False: <NEW_LINE> <INDENT> result['emit'] += self.translate_type() + self.ID.translate()["result"] + "[" + self.constraint... | Translates integer declaration
Args:
sym_count: count of temp vars in program.
func_param: Set to true if int declaration is a function parameter | 625941e70c0af96317bb8657 |
def transform_formulae_painter(taxis_list=None, axis_type=normal, steps=2 ** 10, func=None, draw_args=dict()): <NEW_LINE> <INDENT> fig = plt.figure(figsize=draw_args.get('figsize', None)) <NEW_LINE> ax = fig.add_subplot() <NEW_LINE> for taxis in taxis_list: <NEW_LINE> <INDENT> t = np.linspace(*taxis, steps) <NEW_LINE> ... | `x = f(t), y = f(t)` 类型函数作图 | 625941e7d4950a0f3b08c7b8 |
def merge_overlapping_stints(): <NEW_LINE> <INDENT> for cn in Contributor.objects.exclude(stint=None): <NEW_LINE> <INDENT> merge_stints(cn.stint_set.order_by('position', '-start_date')) | Merge stints with same person and title and with small time gap. | 625941e74a966d76dd551483 |
def get_posting(url): <NEW_LINE> <INDENT> soup = get_soup(url) <NEW_LINE> try: <NEW_LINE> <INDENT> title = soup.find(name='h3').getText() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> title = np.nan <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> posting = soup.find(name='div', attrs={'class': "jobsearch-JobComponent-de... | Get the text portion including both title and job description of the job posting from a given url
It's the first function that call a BS and return a soup object for other information extraction
Parameters:
url: The job posting link
Returns:
title: the job title (if "data scientist" is in the title)
posti... | 625941e7287bf620b61d3ed1 |
def get_account_statement( self, locale: str = None, from_record: int = None, record_count: int = None, item_date_range: dict = time_range(), include_item: str = None, wallet: str = None, session: requests.Session = None, lightweight: bool = None, ) -> Union[dict, resources.AccountStatementResult]: <NEW_LINE> <INDENT> ... | Get account statement.
:param str locale: The language to be used where applicable.
:param int from_record: Specifies the first record that will be returned
:param int record_count: Specifies the maximum number of records to be returned.
:param dict item_date_range: Return items with an itemDate within this date range... | 625941e701c39578d7e752ab |
def _is_iterable_but_not_string(obj): <NEW_LINE> <INDENT> return isinstance(obj, collections.Iterable) and not isinstance(obj, str) | Check whether obj is a non-string Iterable. | 625941e78a349b6b435e85e3 |
def _icon_class_name(file_doc): <NEW_LINE> <INDENT> if file_doc['is_folder']: <NEW_LINE> <INDENT> return 'folder' <NEW_LINE> <DEDENT> class_name = icon(file_doc['name'], file_doc.get('is_binary', [False])[0]) <NEW_LINE> if file_doc['size'] > current_app.dxr_config.max_thumbnail_size: <NEW_LINE> <INDENT> class_name += "... | Return a string for the CSS class of the icon for file document. | 625941e71b99ca400220af23 |
def to_uuid(value: Union[int, bytes, str, uuid.UUID]) -> Optional[uuid.UUID]: <NEW_LINE> <INDENT> if isinstance(value, uuid.UUID): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> elif isinstance(value, (str, bytes, int)): <NEW_LINE> <INDENT> return uuid.UUID(value) <NEW_LINE> <DEDENT> elif value is None: <NEW_LINE... | Convert the input to a UUID value. This function is idempotent and passes None unmodified.
:param value:
:return: | 625941e72ae34c7f2600d5a1 |
def say(context, title, message, main_button=None, alt_button=None, other_button=None): <NEW_LINE> <INDENT> alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_( title, main_button, alt_button, other_button, message ) <NEW_LINE> if context.windowForSheet() is not Non... | Displays a dialog with a message for the user | 625941e70c0af96317bb8658 |
def is_prime(n: int): <NEW_LINE> <INDENT> if n in (2, 3, 5, 7, 11, 13, 17, 19, 23): return(True) <NEW_LINE> elif (n<=1 or n%2==0 or n%3==0 or n%5==0): return(False) <NEW_LINE> ulimit = (int(math.ceil(math.sqrt(n)))+1) <NEW_LINE> return(not any(n%k==0 for k in range(3, ulimit, 2))) | Determine whether or not `n` is prime. | 625941e730dc7b7665901dd2 |
def assertNotLoggedIn(self, client): <NEW_LINE> <INDENT> if 'sessionid' in client.cookies: <NEW_LINE> <INDENT> sesh = SessionStore(session_key=client.cookies.get('sessionid').value) <NEW_LINE> self.assert_('_auth_user_id' not in sesh) | Asserts the that current user is not logged in. | 625941e7956e5f7376d712dc |
def construct_multivariate_dirac_delta(field: Field, values: List[FieldElement], n:int) -> MultiVarPoly: <NEW_LINE> <INDENT> multi = multivariates_over(field, n).factory <NEW_LINE> q = field.field_size <NEW_LINE> base = field(1) <NEW_LINE> for i, val in enumerate(values): <NEW_LINE> <INDENT> x_i_term = [0] * n <NEW_LIN... | Constructs the multivariate dirac delta polynomial at 0.
1_0(x) = \prod_{i=1}^n (1 - x_i^{q-1})
This can be generalized into the the dirac polynomial at y as follows.
1_y(x)\prod_{i=1}^n (1 - (x_i - y_i)^{q-1}) | 625941e791f36d47f21ac967 |
def plot_1D(col, stations, dt, Loc, Fmt, fit=False, p=0): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> fig, axarr = plt.subplots(1, col) <NEW_LINE> for station in stations: <NEW_LINE> <INDENT> dates, levels = fetch_measure_levels(station.measure_id, dt=datetime.timedelta(days=dt)) <NEW_LINE> if levels == []: <NEW_LINE> <INDENT... | Function that plots data in one dimensional grid | 625941e73eb6a72ae02ec959 |
def marketTicker(self): <NEW_LINE> <INDENT> return self.api('returnTicker') | Returns the ticker for all markets | 625941e71d351010ab855f8b |
def testUnversionedListMeta(self): <NEW_LINE> <INDENT> model = lib_openshift.models.unversioned_list_meta.UnversionedListMeta() | Test UnversionedListMeta | 625941e74f88993c3716c4d3 |
def resource_scatter_sub_eager_fallback(resource, indices, updates, name=None, ctx=None): <NEW_LINE> <INDENT> _ctx = ctx if ctx else _context.context() <NEW_LINE> _attr_dtype, (updates,) = _execute.args_to_matching_eager([updates], _ctx) <NEW_LINE> _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices],... | This is the slowpath function for Eager mode.
This is for function resource_scatter_sub | 625941e701c39578d7e752ac |
def Contains(self, pt_control, pt_canvas): <NEW_LINE> <INDENT> pass | Contains(self: GH_Widget, pt_control: Point, pt_canvas: PointF) -> bool | 625941e79b70327d1c4e1248 |
def __DeviceProxy__get_attribute_config(self, value): <NEW_LINE> <INDENT> if isinstance(value, StdStringVector) or is_pure_str(value): <NEW_LINE> <INDENT> return self._get_attribute_config(value) <NEW_LINE> <DEDENT> elif isinstance(value, collections_abc.Sequence): <NEW_LINE> <INDENT> v = seq_2_StdStringVector(value) <... | get_attribute_config( self, name) -> AttributeInfoEx
Return the attribute configuration for a single attribute.
Parameters :
- name : (str) attribute name
Return : (AttributeInfoEx) Object containing the attribute
information
Throws : ConnectionFailed, Comm... | 625941e75f7d997b87174f0c |
def longestValidParentheses(s): <NEW_LINE> <INDENT> n = len(s) <NEW_LINE> stk, rec = [], [0] * n <NEW_LINE> for i, c in enumerate(s): <NEW_LINE> <INDENT> if c == '(': <NEW_LINE> <INDENT> stk.append(i) <NEW_LINE> <DEDENT> elif stk: <NEW_LINE> <INDENT> j = stk.pop() <NEW_LINE> rec[j], rec[i] = 1, 1 <NEW_LINE> <DEDENT> <D... | 32. 最长有效括号
给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。
示例 1:
输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"
示例 2:
输入: ")()())"
输出: 4
解释: 最长有效括号子串为 "()()"
:param s: str
:return: int | 625941e7851cf427c661a97b |
def MakeDir(path): <NEW_LINE> <INDENT> if not os.path.exists(path): <NEW_LINE> <INDENT> os.mkdir(path) <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.debug('Dir {0} already exists'.format(path)) <NEW_LINE> return False | makedir if target not exists
| 625941e7a4f1c619b28b049f |
def express(self): <NEW_LINE> <INDENT> self.pre_express() <NEW_LINE> for name, gene in self.genes.items(): <NEW_LINE> <INDENT> logger.debug("Expressing gene %s with allele\n%s", name, pp.pformat(gene.allele)) <NEW_LINE> gene.express() <NEW_LINE> <DEDENT> self.post_express() <NEW_LINE> self.expressed = True | Express genes in this environment. Very much like 'compiling' the
individual to a chimera.Molecule. | 625941e70fa83653e4657429 |
def test_class_exists(self): <NEW_LINE> <INDENT> self.assertTrue(hasattr(Domain, self.klass_name)) | Domain class is defined | 625941e7d486a94d0b98e5b7 |
def add_trend_feature(features, gr, feature_name, prefix): <NEW_LINE> <INDENT> y = gr[feature_name].values <NEW_LINE> try: <NEW_LINE> <INDENT> x = np.arange(0, len(y)).reshape(-1, 1) <NEW_LINE> lr = LinearRegression() <NEW_LINE> lr.fit(x, y) <NEW_LINE> trend = lr.coef_[0] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT>... | Return linear regression parameters (linear trend) for given feature.
Arguments:
features: DataFrame where trends will be add.
gr: pandas Groupby object.
feature_name: Feature for calculating trends (string).
prefix: Prefix for the name of the new features (string).
Returns:
features: Same DataFra... | 625941e7090684286d50f15d |
def modified_containers(self, protein): <NEW_LINE> <INDENT> return self.call("modified-containers", protein) | List all containers of a protein and all its modified forms.
Arguments
---------
protein: An instance of class proteins.
Returns
-------
Both all containers of a protein (meaning protein complexes of
which this protein is a part) including itself, and all modified
forms of a protein.
LISP equivalent: modified-contai... | 625941e716aa5153ce3628e8 |
def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | Test of not equality.
EXAMPLES::
sage: P.<x> = QQ[]
sage: f0 = 4*x^5 - 30*x^3 + 45*x - 22
sage: C0 = HyperellipticCurve(f0)
sage: f1 = x^5 - x^3 + x - 22
sage: C1 = HyperellipticCurve(f1)
sage: C0 != C1
True
sage: C0 != C0
False | 625941e7cdde0d52a9e534a7 |
def Equals(self, a, b): <NEW_LINE> <INDENT> marg = 0.5 <NEW_LINE> return b <= a + marg and b >= a - marg | Return `True` if a and b are approximately equal (for the purposes
of evaluating the constraint).
:param `a`: ???
:param `b`: ??? | 625941e7097d151d1a2232c8 |
def __trunc__(self, _): <NEW_LINE> <INDENT> return None | Truncating an Integral returns itself. | 625941e763d6d428bbe44961 |
def all_wells(self, columnwise=False): <NEW_LINE> <INDENT> if columnwise: <NEW_LINE> <INDENT> num_cols = self.container_type.col_count <NEW_LINE> num_rows = self.container_type.well_count // num_cols <NEW_LINE> return WellGroup([self._wells[row * num_cols + col] for col in xrange(num_cols) for row in xrange(num_rows)])... | Return a WellGroup representing all Wells belonging to this Container.
Parameters
----------
columnwise : bool, optional
returns the WellGroup columnwise instead of rowwise (ordered by
well index). | 625941e707f4c71912b118f5 |
def SetInputForegroundValue(self, *args): <NEW_LINE> <INDENT> return _itkBinaryImageToStatisticsLabelMapFilterPython.itkBinaryImageToStatisticsLabelMapFilterIUS2IUC2LM2_SetInputForegroundValue(self, *args) | SetInputForegroundValue(self, unsigned short _arg) | 625941e7566aa707497f49d3 |
def __init__(self): <NEW_LINE> <INDENT> self.Items = None <NEW_LINE> self.RequestId = None | :param Items: Database information
:type Items: list of str
:param RequestId: The unique request ID, which is returned for each request. RequestId is required for locating a problem.
:type RequestId: str | 625941e78e05c05ec3eea7e9 |
def _convert_returns(self, returns: t.Optional[docstring_parser.common.DocstringReturns]) -> str: <NEW_LINE> <INDENT> if returns is not None: <NEW_LINE> <INDENT> if returns.type_name: <NEW_LINE> <INDENT> type_data = '`{}`: '.format(returns.type_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> type_data = '' <NEW_LIN... | Convert a DocstringReturns object to a markdown string.
:return: A markdown formatted string | 625941e7ac7a0e7691ed4534 |
def __str__(self): <NEW_LINE> <INDENT> pass | Return string representation. | 625941e7c4546d3d9de72ea9 |
def compute(self, x, u, t, recompute=True): <NEW_LINE> <INDENT> tmp_time = int(t // self.dt) <NEW_LINE> tmp = x[:self.nq]-self.q_ref[tmp_time,:self.nq] <NEW_LINE> cost = 0.5*(tmp).dot(tmp) <NEW_LINE> return cost | Compute the cost for a single time instant | 625941e760cbc95b062c69b4 |
def get_calendar_events_today(calendar_url): <NEW_LINE> <INDENT> global EVENTS_CACHED <NEW_LINE> today = datetime.datetime.today() <NEW_LINE> tomorrow = today <NEW_LINE> tomorrow += datetime.timedelta(days=1) <NEW_LINE> cal = get_calendar_events(calendar_url, params={'key': API_KEY, 'singleEvents': True, 'timeMax': tom... | Get the calendar events from only today. 24 hour span from midnight. | 625941e7377c676e91272617 |
def success(self, msg): <NEW_LINE> <INDENT> suites = self._base_xml() <NEW_LINE> suite = self._get_suite(suites) <NEW_LINE> case = self._get_case(suite) <NEW_LINE> case.text = '\n'.join([case.text, msg]) if case.text else msg <NEW_LINE> self._write_junit_file(suites) | Create a junit file for a passed test
msg: The message to add | 625941e7e64d504609d74cb1 |
def __init__(self, content_dir='./data/content/', style_dir='./data/style/', output_dir = './data/output', init_type='content', noise_ratio=1., max_szie=512, content_weight=5e0, style_weight=1e4, **kwargs): <NEW_LINE> <INDENT> self.content_dir = content_dir <NEW_LINE> self.max_size = max_szie <NEW_LINE> self.content_we... | :param content_dir: path to directory containing content images
:type content_dir: str
:param style_dir: path to directory containing style images
:type style_dir: str
:param output_dir: path to output directory
:type output_dir: str
:param init_type: The inital target image. either 'content', 'tyle', or 'random'... | 625941e799fddb7c1c9de7ff |
def generate_steps(sorted_steps, mot_index): <NEW_LINE> <INDENT> global time_unit <NEW_LINE> size = len(sorted_steps) <NEW_LINE> actual_relative_steps = [] <NEW_LINE> fi = [] <NEW_LINE> for t in range(0, size): <NEW_LINE> <INDENT> actual_relative_steps.append(0) <NEW_LINE> fi.append(0) <NEW_LINE> <DEDENT> """ Nested fu... | N-tengelyes interpoláció. Ez a függvény egy tetszőleges hosszúságú,
csökkenő step listából és a hozzá rendelt motortengely-index listából olyan
szekvenciát generál, amelyben az összes tengelyen egyszerre fejeződik be. | 625941e7046cf37aa974d1b4 |
def sum(self): <NEW_LINE> <INDENT> return sum(self.build()) | Calculate sum of entries.
:returns: sum of entries.
>>> select(1, 10, 1).sum()
55
>>> select(1, 10, 1).transform(lambda n: n**2).sum()
385 | 625941e7bde94217f368325d |
def c_extension_missing(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import coverage.tracer as _ <NEW_LINE> return False <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> _ = None <NEW_LINE> return True | Coverage module has C-extension, which we can reuse for test | 625941e7a219f33f34628dd4 |
def open_links(links): <NEW_LINE> <INDENT> to_open = min(5, len(links)) <NEW_LINE> for i in range(to_open): <NEW_LINE> <INDENT> webbrowser.open(f"https://www.google.com/{links[i].get('href')}") | Opens at most 5 links in the user's browser
Keyword arguments:
links -- BeatifulSoup select objec tthat has list of links found | 625941e75e10d32532c5f396 |
def run(self): <NEW_LINE> <INDENT> wx.Yield() <NEW_LINE> wx.BeginBusyCursor() <NEW_LINE> self.wizard = Wiz_window(size_x=1000, size_y=700, title='Analysis selection wizard') <NEW_LINE> self.wizard.TEXT_FINISH = " Start" <NEW_LINE> self.new_page = New_analysis_page(self.wizard) <NEW_LINE> self.wizard.add_page(self.new_p... | Run through the analysis selection wizard, returning the results.
@return: The analysis type, analysis name, data pipe name, data pipe bundle name, and user function on_execute method list.
@rtype: tuple of str | 625941e78c3a873295158831 |
def fitCompleteCBF(X,y,dim = 20): <NEW_LINE> <INDENT> x0 = None <NEW_LINE> X_c = [] <NEW_LINE> for i in range(10): <NEW_LINE> <INDENT> A,b,c, x0 = fitCBF(X,y,X_c,dim,x0) <NEW_LINE> def obj(x): <NEW_LINE> <INDENT> return x.T @ (Dyn_A .T @ A + A @ Dyn_A) @ x + 2 * MAX_INPUT * np.linalg.norm(Dyn_B.T @ A @ x,ord = 1) <NEW_... | call the `fitCBF` iteratively, each step augment the dataset with some data points
that makes the optimization of u hard | 625941e7d164cc61757831c0 |
def noise_global(rho, p, graph=None): <NEW_LINE> <INDENT> k = len(rho) <NEW_LINE> return p * rho + (1 - p) * np.ones(k) / k | Apply a global white noise channel to the state.
Parameters
----------
rho : np.ndarray
Is the state acted on. Should be a 2**N-dimensional vector
with the diagonal entries of the density matrix in the graph
state basis.
p : scalar
Error parameter of the channel should be in interval [0, 1].
graph : Gr... | 625941e73eb6a72ae02ec95a |
def test_TREE10(self): <NEW_LINE> <INDENT> W = PartiallySortedArray([1,2,4]) <NEW_LINE> T = gdmCodeTree(W) <NEW_LINE> self.assertEqual(T.toStringWithAllWeightsCalculated(),'(7,(3,[1],[2]),[4])') <NEW_LINE> L = T.depths() <NEW_LINE> self.assertEqual(sorted(L),[1,2,2]) | Exponential Sequence. | 625941e7a79ad161976cc5b6 |
def __init__(self, hrs=0, mins=0, secs=0): <NEW_LINE> <INDENT> self.hours = hrs <NEW_LINE> self.minutes = mins <NEW_LINE> self.seconds = secs | Create a MyTime object initialized to hrs, mins, secs | 625941e7a79ad161976cc5b7 |
def toolParameterzFinalMillDepthUpdate(self, text): <NEW_LINE> <INDENT> self.ui.zFinalMillDepthLineEdit.setPalette(self.palette) <NEW_LINE> val = text.toFloat() <NEW_LINE> if val[1]: <NEW_LINE> <INDENT> selected_indexes_list = self.ui.layersShapesTreeView.selectedIndexes(); <NEW_LINE> for model_index in selected_indexe... | Slot that updates the above tools parameter when the
corresponding LineEdit changes
@param text: the value of the LineEdit | 625941e771ff763f4b549b04 |
def _M2(Xvar, Yvar, mask_X=None, mask_Y=None, xsum=0, xconst=0, ysum=0, yconst=0): <NEW_LINE> <INDENT> if mask_X is None and mask_Y is None: <NEW_LINE> <INDENT> return _M2_dense(Xvar, Yvar) <NEW_LINE> <DEDENT> elif _is_zero(xsum) and _is_zero(ysum) or _is_zero(xconst) and _is_zero(yconst): <NEW_LINE> <INDENT> return _M... | direct (nonsymmetric) second moment matrix. Decide if we need dense, sparse, const | 625941e7b57a9660fec33cfb |
def load(self, arg, namespaces=[None], profile_memory=0, report_timing=False): <NEW_LINE> <INDENT> if arg is None or isinstance(arg, basestring): <NEW_LINE> <INDENT> dp = DataPortal(filename=arg, model=self) <NEW_LINE> <DEDENT> elif type(arg) is DataPortal: <NEW_LINE> <INDENT> dp = arg <NEW_LINE> <DEDENT> elif type(arg... | Load the model with data from a file, dictionary or DataPortal object. | 625941e74f88993c3716c4d4 |
def __init__(self): <NEW_LINE> <INDENT> self.dict = dict() <NEW_LINE> self.list = [] | Initialize your data structure here. | 625941e7460517430c3945ea |
def SG_H_V(N, w_space, p_space): <NEW_LINE> <INDENT> inc = 2 * np.pi / N <NEW_LINE> degrees = np.arange(0, 2 * np.pi, inc) <NEW_LINE> H = np.zeros((N, 2)) <NEW_LINE> for i in range(N): <NEW_LINE> <INDENT> x = degrees[i] <NEW_LINE> H[i, 0] = np.cos(x) <NEW_LINE> H[i, 1] = np.sin(x) <NEW_LINE> <DEDENT> o = np.array([np.m... | This function initializes the subgradients, hyperplane levels,
and extreme points of the value set by choosing an appropriate
origin and radius. It is based on a similar function in QuantEcon's
Games.jl | 625941e707d97122c4178d07 |
def get_project(): <NEW_LINE> <INDENT> filters = [['sg_status', 'is', 'Active']] <NEW_LINE> fields = ['name', 'id', 'sg_project_path'] <NEW_LINE> return sg.find('Project', filters, fields) | get active project | 625941e7f9cc0f698b140a68 |
def set_req_relaxed(self, req_relaxed): <NEW_LINE> <INDENT> utils.lib.zsock_set_req_relaxed(self._p, req_relaxed) | Set socket option `req_relaxed`.
Available from libzmq 4.0.0. | 625941e70a366e3fb873ec8f |
def __init__(self, res_raw: bytes, con: socket, ad: tuple) -> None: <NEW_LINE> <INDENT> self.conn = con <NEW_LINE> self.address = ad <NEW_LINE> self.raw_data = res_raw <NEW_LINE> t = res_raw.decode(errors='ignore').split('\r\n\r\n') <NEW_LINE> self.raw_h = t[0].encode() <NEW_LINE> self.headers = p_headers(t[0]) <NEW_LI... | This function make the Request instance and process the request byte string.
:param res_raw: request byte string. | 625941e7d486a94d0b98e5b8 |
def removeClosedWindows(self): <NEW_LINE> <INDENT> for window, conversation in self.conversations[:]: <NEW_LINE> <INDENT> if window.closed or conversation.closed or (window.notOpen and conversation.getStatus() == 'closed'): <NEW_LINE> <INDENT> self.conversations.remove((window, conversation)) | remove conversations for closed windows | 625941e723e79379d52ee9cf |
def test_naipe_has_inverse(self): <NEW_LINE> <INDENT> prueba = Naipe((2,3)).get_as_tuple() == (2,3) <NEW_LINE> self.assertTrue(prueba) | Revisa que la operacion de Naipe se pueda invertir | 625941e7004d5f362079a7a2 |
def evolut(self): <NEW_LINE> <INDENT> make_step_th(self.size, self.threads_count, self._state_c_ptr) | Make new state.
| 625941e7091ae356686673c8 |
def BTS(T): <NEW_LINE> <INDENT> L = len(T) <NEW_LINE> b = np.random.uniform(0,1,L)*(L-2)+1 <NEW_LINE> c = np.round(b) <NEW_LINE> c = c.astype(int) <NEW_LINE> TT = np.copy(T[c]) <NEW_LINE> return TT | DESCRIPTION:
Con esta función se pretende hacer un reordenamiento de una serie utilizando
"Boot-straping" en este caso se reordenan las dos series.
_________________________________________________________________________
INPUT:
+ T: Serie de datos que se va a reordenar
______________________________________... | 625941e7cad5886f8bd2744a |
def node_probs(self, data, alpha = 0.001): <NEW_LINE> <INDENT> index = self.cpt_index() <NEW_LINE> var = self.parent_idx() + [self.idx] <NEW_LINE> par = self.parent_idx() <NEW_LINE> cpt = data[var].copy() <NEW_LINE> cpt['Prob'] = 0 <NEW_LINE> cpt = cpt.groupby(var).count().copy() <NEW_LINE> cpt = cpt.reindex(index).fil... | Fill CPT with corresponding observational counts | 625941e7f9cc0f698b140a69 |
def load_manifest(manifest_file_name): <NEW_LINE> <INDENT> with open(manifest_file_name, 'r') as manifest_file: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cfg = yaml.load(manifest_file, Loader=yaml.SafeLoader) <NEW_LINE> <DEDENT> except yaml.YAMLError as e: <NEW_LINE> <INDENT> logger.error("Failed to load YAML manife... | Read in an arbitrary YAML manifest and return it | 625941e7a219f33f34628dd5 |
def normalize(s): <NEW_LINE> <INDENT> s = replace_whitespace(s) <NEW_LINE> s = remove_dashes(s) <NEW_LINE> s = replace_unicode(s) <NEW_LINE> s = s.lower() <NEW_LINE> return s | Normalize white spaces, dashes and case of a given string.
Parameters
----------
s : str
The string to be normalized.
Returns
-------
str
The normalized string. | 625941e77cff6e4e81117df7 |
def _verify_result(self, code, expected_result): <NEW_LINE> <INDENT> result = self._location_preprocessor.run(code, 'foo.vhd') <NEW_LINE> self.assertEqual(result, expected_result) | Assert that the code after preprocessing is equal to the expected_result | 625941e7796e427e537b0a3b |
def get_model(arch, hidden_units): <NEW_LINE> <INDENT> if arch == 'vgg13_bn': <NEW_LINE> <INDENT> model = models.vgg13_bn(pretrained=True) <NEW_LINE> input_size = model.classifier[0].in_features <NEW_LINE> <DEDENT> elif arch == 'vgg16_bn': <NEW_LINE> <INDENT> model = models.vgg16_bn(pretrained=True) <NEW_LINE> input_si... | Load pretrained model | 625941e756b00c62f0f14ace |
def pwad_remove(self, event): <NEW_LINE> <INDENT> index = self.PWADList.GetFirstSelected() <NEW_LINE> if index > -1: <NEW_LINE> <INDENT> del self.pwads[index] <NEW_LINE> self.PWADList.DeleteItem(index) | Removes the selected PWAD from the list. | 625941e715fb5d323cde0f87 |
def __init__(self): <NEW_LINE> <INDENT> self.clock = pygame.time.Clock() <NEW_LINE> self.entities = [] <NEW_LINE> self.dialogue_boxes = [] <NEW_LINE> self.to_remove = [] <NEW_LINE> self.game_state = "GAME" <NEW_LINE> self.dialogue_handler = DialogueHandler.DialogueHandler() <NEW_LINE> self.animation_handler = Animation... | Initializes the game handler.
Initializes the handler (engine) and all of the variables. Will
not specifically create entities, as this needs to be as open and
reusable as possible. | 625941e707f4c71912b118f6 |
def findLengthOfLCIS(self, nums): <NEW_LINE> <INDENT> if not nums: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> maxlen = 1 <NEW_LINE> end = 0 <NEW_LINE> for i in range(1, len(nums)): <NEW_LINE> <INDENT> if nums[i-1] >= nums[i]: <NEW_LINE> <INDENT> end = i <NEW_LINE> <DEDENT> maxlen = max(maxlen, i-end+1) <NEW_LINE>... | :type nums: List[int]
:rtype: int | 625941e78a43f66fc4b544d2 |
def __init__(self): <NEW_LINE> <INDENT> self.screen_width = 1200 <NEW_LINE> self.screen_height = 800 <NEW_LINE> self.bg_color = (0, 0, 0) <NEW_LINE> self.ship_speed = 2 <NEW_LINE> self.ship_limit = 1 <NEW_LINE> self.bullet_width = 3 <NEW_LINE> self.bullet_height = 15 <NEW_LINE> self.bullet_color = (255, 255, 255) <NEW_... | Иницилизация настройки игры | 625941e773bcbd0ca4b2c4e7 |
def get_barcode_url(slideRef, sessionID=None): <NEW_LINE> <INDENT> sessionID = _pma_session_id(sessionID) <NEW_LINE> if (slideRef.startswith("/")): <NEW_LINE> <INDENT> slideRef = slideRef[1:] <NEW_LINE> <DEDENT> url = (_pma_url(sessionID) + "barcode" + "?SessionID=" + pma._pma_q(sessionID) + "&pathOrUid=" + pma._pma_q(... | Get the URL that points to the barcode (alias for "label") for a slide | 625941e72c8b7c6e89b35c2f |
@commandWrap <NEW_LINE> def xgmGuideSculptContext(*args, **kwargs): <NEW_LINE> <INDENT> return cmds.xgmGuideSculptContext(*args, **kwargs) | :rtype: list|str|DagNode|AttrObject|ArrayAttrObject|Components1Base | 625941e723e79379d52ee9d0 |
def tokenType(self): <NEW_LINE> <INDENT> if (self.current_token in self.Keywords): <NEW_LINE> <INDENT> return self.keyWord() <NEW_LINE> <DEDENT> elif (self.current_token in self.Symbols): <NEW_LINE> <INDENT> return self.symbols() <NEW_LINE> <DEDENT> elif (self.current_token.startswith('"')): <NEW_LINE> <INDENT> return... | This function writes the current token into the output file | 625941e710dbd63aa1bd3013 |
def noninjectable(*args): <NEW_LINE> <INDENT> def decorator(function): <NEW_LINE> <INDENT> existing = getattr(function, '__noninjectables__', set()) <NEW_LINE> merged = existing | set(args) <NEW_LINE> function.__noninjectables__ = merged <NEW_LINE> return function <NEW_LINE> <DEDENT> return decorator | Mark some parameters as not injectable.
This serves as documentation for people reading the code and will prevent
Injector from ever attempting to provide the parameters.
For example:
>>> class Service:
... pass
...
>>> class SomeClass:
... @inject
... @noninjectable('user_id')
... def __init__(self, ... | 625941e7ff9c53063f47c663 |
def decrypt(key, enc): <NEW_LINE> <INDENT> msg = [] <NEW_LINE> for i, c in enumerate(enc): <NEW_LINE> <INDENT> key_c = ord(key[i % len(key)]) <NEW_LINE> msg_c = ord(c) <NEW_LINE> msg.append(chr((msg_c - key_c) % 127)) <NEW_LINE> <DEDENT> return ''.join(msg) | Simple decryption. Reverse of the encryption function
Please note that this is quite weak security, and completely breakable
with little or no effort. If you take issue with this method, don't
hesitate to offer your own implementation. I know very little about
security and would be happy for someone to school me on th... | 625941e710dbd63aa1bd3014 |
def load_external_view(self): <NEW_LINE> <INDENT> self._external_view = {} <NEW_LINE> for resource in self.resources: <NEW_LINE> <INDENT> self._external_view[resource] = self.functions.get_external_view(self.cluster, resource) | query external view from helix and load into model | 625941e785dfad0860c3b2cd |
def user_auth(self, username, password, update_session_id = True): <NEW_LINE> <INDENT> params = { "username" : username, "password" : password } <NEW_LINE> if self.execute("api.authenticate", params): <NEW_LINE> <INDENT> if update_session_id: <NEW_LINE> <INDENT> self.session_id = self.response["auth"]["params"]["sessio... | Authenticate a user. | 625941e73c8af77a43ae3c17 |
def get_default_acf(appid, name): <NEW_LINE> <INDENT> userconfig = OrderedDict() <NEW_LINE> userconfig["name"] = name <NEW_LINE> userconfig["gameid"] = appid <NEW_LINE> appstate = OrderedDict() <NEW_LINE> appstate["appID"] = appid <NEW_LINE> appstate["Universe"] = "1" <NEW_LINE> appstate["StateFlags"] = "1026" <NEW_LIN... | Return a default configuration usable to
create a runnable game in Steam | 625941e721a7993f00bc8169 |
def uniquePathsWithObstacles(self, obstacleGrid): <NEW_LINE> <INDENT> m = len(obstacleGrid) <NEW_LINE> n = len(obstacleGrid[0]) <NEW_LINE> res = [[0 for i in range(n)] for i in range(m)] <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> if obstacleGrid[0][i] == 1: <NEW_LINE> <INDENT> for j in range(i,n): <NEW_LINE> <IN... | :type obstacleGrid: List[List[int]]
:rtype: int | 625941e7a4f1c619b28b04a0 |
def parse_twitter_url(url): <NEW_LINE> <INDENT> if not is_twitter_url(url): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> parsed = safe_urlsplit(url) <NEW_LINE> path = urlpathsplit(parsed.path) <NEW_LINE> if path: <NEW_LINE> <INDENT> user_screen_name = normalize_screen_name(path[0]) <NEW_LINE> if user_screen_name... | Function returning a parsed result from a given Twitter url.
Args:
url (str) : Url from which to extract information if found.
Returns:
TwitterTweet (namedtuple containing a user_screen_name and a tweet id) instance if the url is a link to a tweet
or TwitterUser (namedtuple containing a user_screen_name) ... | 625941e75166f23b2e1a55cb |
def softmax(x): <NEW_LINE> <INDENT> original_shape = x.shape <NEW_LINE> if len(x.shape) == 1: <NEW_LINE> <INDENT> x = x.reshape(1, x.shape[0]) <NEW_LINE> <DEDENT> xexp = np.exp(x - np.max(x, 1).reshape(x.shape[0], 1)) <NEW_LINE> x = xexp / np.sum(xexp, 1).reshape(x.shape[0], 1) <NEW_LINE> x = x.reshape(original_shape) ... | Compute the softmax function for each row of the input x.
It is crucial that this function is optimized for speed because
it will be used frequently in later code.
You might find numpy functions np.exp, np.sum, np.reshape,
np.max, and numpy broadcasting useful for this task. (numpy
broadcasting documentation:
http://d... | 625941e7925a0f43d254a2ed |
def test_calc_nintyOnly(): <NEW_LINE> <INDENT> event_area = Mie(silent = True, design = 'POPS 1',wavelength = 0.6328, diameter = 1.0, indexOfRef = 1.5, nang = 100) <NEW_LINE> mDiameter = event_area.POPSdimensions['mirror diameter (mm)'] = 25. <NEW_LINE> rMirror = 20. <NEW_LINE> event_area.POPSdimensions['mirror(top)-j... | plots scattering scattering efficiency at exactly 90 deg compared to the area colected by the mirror of the POPS | 625941e763f4b57ef000157e |
def CSR_K1(self, i, traj, NdW, gamma=None): <NEW_LINE> <INDENT> if gamma != None: <NEW_LINE> <INDENT> L_fin = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> L_fin = False <NEW_LINE> <DEDENT> w_range = np.arange(-NdW[0]-1, 0)*NdW[1] <NEW_LINE> if L_fin: <NEW_LINE> <INDENT> w, KS = self.K0_fin_anf(i, traj, w_range[0]... | :param i: index of the trajectories points for the convolution kernel is calculated;
:param traj: trajectory. traj[0,:] - longitudinal coordinate,
traj[1,:],traj[2,:],traj[3,:] - rectangular coordinates, traj[4,:],traj[5,:],traj[6,:] - tangential unit vectors
:p... | 625941e7fb3f5b602dac3b0a |
def fullRedo(project, modelCountAnneal = 200, bestAnneal = 50, best = 25): <NEW_LINE> <INDENT> nTmessage("==> Recalculating and refining a new ensemble in cing.PluginCode.xplor#%s" % getCallerName()) <NEW_LINE> if 0: <NEW_LINE> <INDENT> modelCountAnneal, bestAnneal, best = 4,3,2 <NEW_LINE> <DEDENT> if project == None: ... | Return True on error. | 625941e7796e427e537b0a3c |
def _get_document_number(self, txt_id, txt_line): <NEW_LINE> <INDENT> return self.pool.get('txt.iva').get_document_number( self.cr, self.uid, txt_id, txt_line, 'inv_number') | Return document number
| 625941e7d4950a0f3b08c7bb |
def ops_check(appid, taskid): <NEW_LINE> <INDENT> arguments = "-TaskId {0} -AppId {1} -Step {2}".format(taskid, appid, "OpsCheck") <NEW_LINE> return __salt__['cmd.script']('salt://scripts/publish.ps1', args=arguments, shell='powershell') | Instruct the minion to update site by appid.
CLI Example:
.. code-block:: bash
salt '*' publish.ops_check 'api.app.ymatou.com' taskid | 625941e77d847024c06be732 |
def cudf_dtype_to_pa_type(dtype): <NEW_LINE> <INDENT> if cudf.api.types.is_categorical_dtype(dtype): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> elif ( cudf.api.types.is_list_dtype(dtype) or cudf.api.types.is_struct_dtype(dtype) or cudf.api.types.is_decimal_dtype(dtype) ): <NEW_LINE> <INDENT> re... | Given a cudf pandas dtype, converts it into the equivalent cuDF
Python dtype. | 625941e7f7d966606f6aa47b |
def run(self, handler_chains, report=True): <NEW_LINE> <INDENT> for handler_chain in handler_chains: <NEW_LINE> <INDENT> if type(handler_chain) not in set([list, tuple]): <NEW_LINE> <INDENT> handler_chain = [handler_chain] <NEW_LINE> <DEDENT> self.logger.info( '\n\n\n---------------------------\n\n' 'Running rsm-plugin... | Run handlers over instances attached to context.
Args:
handler_chains: list handler_chains for run
report: raise error if any errors found
Raises:
NonRecoverableError: if validation errors list is not empty. | 625941e7d7e4931a7ee9e391 |
def rezero_weights(m): <NEW_LINE> <INDENT> if isinstance(m, SparseWeightsBase): <NEW_LINE> <INDENT> if m.training: <NEW_LINE> <INDENT> m.rezero_weights() | Function used to update the weights after each epoch.
Call using :meth:`torch.nn.Module.apply` after each epoch if required
For example: ``m.apply(rezero_weights)``
:param m: SparseWeightsBase module | 625941e7287bf620b61d3ed3 |
def setDoubleClickInterval(self, p_int): <NEW_LINE> <INDENT> pass | setDoubleClickInterval(int) | 625941e701c39578d7e752ad |
@wsgi_wrapper.PlacementWsgify <NEW_LINE> @util.require_content('application/json') <NEW_LINE> def update_resource_provider(req): <NEW_LINE> <INDENT> uuid = util.wsgi_path_item(req.environ, 'uuid') <NEW_LINE> context = req.environ['placement.context'] <NEW_LINE> resource_provider = objects.ResourceProvider.get_by_uuid( ... | PUT to update a single resource provider.
On success return a 200 response with a representation of the updated
resource provider. | 625941e7f8510a7c17cf9b71 |
def log_text(self, text, client=None, labels=None, insert_id=None, severity=None, http_request=None): <NEW_LINE> <INDENT> client = self._require_client(client) <NEW_LINE> entry_resource = self._make_entry_resource( text=text, labels=labels, insert_id=insert_id, severity=severity, http_request=http_request) <NEW_LINE> d... | API call: log a text message via a POST request
See:
https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/entries/write
:type text: text
:param text: the log message.
:type client: :class:`gcloud.logging.client.Client` or ``NoneType``
:param client: the client to use. If not passed, falls back to the... | 625941e78a349b6b435e85e5 |
def load_obj(name): <NEW_LINE> <INDENT> with open('obj/' + name + '.pkl', 'rb') as f: <NEW_LINE> <INDENT> return pickle.load(f) | load pickle from given file. extension required is .pkl | 625941e73617ad0b5ed68369 |
def assertXmlNamespace(self, node, prefix, uri): <NEW_LINE> <INDENT> self.assertIn(prefix, node.nsmap) <NEW_LINE> self.assertEqual(node.nsmap.get(prefix), uri) | Asserts `node` declares namespace `uri` using `prefix`.
One can use this method on element node. | 625941e73346ee7daa2b31e1 |
def SetCacheMax(*args): <NEW_LINE> <INDENT> return _gdal.SetCacheMax(*args) | SetCacheMax(int nBytes) | 625941e74a966d76dd551486 |
def _allocate_file_blocks(self, path, size): <NEW_LINE> <INDENT> block_size_mb = 1 <NEW_LINE> block_count = size * units.Gi / (block_size_mb * units.Mi) <NEW_LINE> self._execute('dd', 'if=/dev/zero', 'of=%s' % path, 'bs=%dM' % block_size_mb, 'count=%d' % block_count, run_as_root=True) | Preallocate file blocks by writing zeros. | 625941e72ae34c7f2600d5a2 |
def handle_hooktest_log(self, owner, repository, request): <NEW_LINE> <INDENT> if not request.data: <NEW_LINE> <INDENT> raise BadRequest(description="No post data") <NEW_LINE> <DEDENT> elif request.content_type != "application/json": <NEW_LINE> <INDENT> raise BadRequest(description="Data is not json encoded") <NEW_LINE... | Handle data received from Redis server commands
:param owner: Name of the owner
:param repository: Name of the repository
:param request: request object
:return: Status Code | 625941e730bbd722463cc23a |
def _matches(element_def, element): <NEW_LINE> <INDENT> return _name_matches(element_def, element) and _content_matches(element_def, element) and _attributes_match(element_def, element) | Tests whether an element matches an element definition. | 625941e7442bda511e8be884 |
def handle_condition(self, value): <NEW_LINE> <INDENT> resource_condition = self.template_json.get("Conditions") <NEW_LINE> condition = resource_condition.get(value) <NEW_LINE> if condition: <NEW_LINE> <INDENT> updated_condition = self.process_function(condition) <NEW_LINE> if condition != updated_condition: <NEW_LINE>... | handle "condition" by getting reference from | 625941e7d18da76e2353294e |
def memoize(func): <NEW_LINE> <INDENT> cache = {} <NEW_LINE> @functools.wraps(func) <NEW_LINE> def wrapper(*args): <NEW_LINE> <INDENT> if args in cache: <NEW_LINE> <INDENT> return cache[args] <NEW_LINE> <DEDENT> print('Calling %s()' % func.__name__) <NEW_LINE> result = func(*args) <NEW_LINE> cache[args] = result <NEW_L... | Cache the result of the function so it doesn't need to be called
again, if the same arguments are provided a second time.
:param func: input function for memoization.
:return: new function with memoization support. | 625941e7aad79263cf390eba |
def __init__(self, m, crossover_choice, omega=1, phi_l=0.5, phi_g=0.5): <NEW_LINE> <INDENT> self.manipulator = m <NEW_LINE> self.position = self.manipulator.random() <NEW_LINE> self.best = self.position <NEW_LINE> self.omega = omega <NEW_LINE> self.phi_l = phi_l <NEW_LINE> self.phi_g = phi_g <NEW_LINE> self.crossover_c... | m: a configuraiton manipulator
omega: influence of the particle's last velocity, a float in range [0,1] ; omega=1 means even speed
phi_l: influence of the particle's distance to its historial best position, a float in range [0,1]
phi_g: influence of the particle's distance to the global best position, a float in range ... | 625941e730dc7b7665901dd4 |
def can_be_seen(self): <NEW_LINE> <INDENT> return self.checkPermission(view) | Indicates if the current user has access to the current forum. | 625941e71f5feb6acb0c4fbb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.