code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def readsportfile(sport): <NEW_LINE> <INDENT> combinedData = [] <NEW_LINE> os.chdir("./HTML Files/OlympicsBySport") <NEW_LINE> f = open(sport+" at the Winter Olympics.html", encoding='utf-8') <NEW_LINE> lines = f.read() <NEW_LINE> f.close() <NEW_LINE> m=re.findall('Medal table\"(.+)colspan=\"2\">Total', lines, re.DOTAL... | to get gold silver bronze medal by a country in a year | 625941dd3346ee7daa2b3082 |
def __init__(self, routing, clusters): <NEW_LINE> <INDENT> self._routing = routing <NEW_LINE> self._clusters = clusters | Initialize a configuration object
:param routing: Routing tree
:type routing: `Node`
:param clusters: Dictionary of cluster information
:type clusters: `dict` of `str` to `([str], int)` tuples | 625941ddadb09d7d5db6caa2 |
def write_file(path, content, append=False): <NEW_LINE> <INDENT> f_file = open(path, '+w') <NEW_LINE> f_file.writelines(content) <NEW_LINE> f_file.close() | Writes content to the file in path | 625941dd498bea3a759b9dc3 |
def __init__(self, credential, region): <NEW_LINE> <INDENT> super(Gs2LevelClient, self).__init__(credential, region) | コンストラクタ
:param credential: 認証情報
:type credential: IGs2Credential
:param region: GS2リージョン
:type region: str | 625941ddbde94217f3683102 |
def set_color(self, red, green, blue): <NEW_LINE> <INDENT> print(red, green, blue) | Set backlight color to provided red, green, and blue values. If PWM
is enabled then color components can be values from 0.0 to 1.0, otherwise
components should be zero for off and non-zero for on. | 625941ddeab8aa0e5d26de6d |
def assert_equal(actual, desired): <NEW_LINE> <INDENT> numpy.testing.assert_equal(actual, desired) <NEW_LINE> if isinstance(actual, numpy.ndarray) and isinstance(desired, numpy.ndarray): <NEW_LINE> <INDENT> numpy.testing.assert_equal(actual.dtype, desired.dtype) <NEW_LINE> <DEDENT> elif isinstance(actual, numpy.number)... | Test equality of actual and desired.
When both inputs are numpy array or number objects, test equality
of dtype attributes as well. | 625941dd7cff6e4e81117c9a |
def _softmax_proba(self, X, k): <NEW_LINE> <INDENT> total_score = np.zeros(np.shape(X)[0]) <NEW_LINE> k_score = np.exp(self._softmax_score(X, k)) <NEW_LINE> for i in range(self.num_classes): <NEW_LINE> <INDENT> total_score += np.exp(self._softmax_score(X, i)) <NEW_LINE> <DEDENT> return k_score / total_score | Computes the probability that each sample in the
data matrix X has of belonging to class k. | 625941dd3317a56b86939f66 |
def test_basic_nand(self): <NEW_LINE> <INDENT> cases = { (0, 0): 1, (0, 1): 1, (1, 0): 1, (1, 1): 0 } <NEW_LINE> for inputs, output in cases.items(): <NEW_LINE> <INDENT> self.helper_test_evaluate( 'A nand B', expected_result=output, A=inputs[0], B=inputs[1]) | Test a basic expression with the Boolean NAND operator. | 625941ddbf627c535bc134e4 |
def __init__(self, ai_game): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = ai_game.screen <NEW_LINE> self.settings = ai_game.settings <NEW_LINE> self.image = pygame.image.load('images/alien.bmp') <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = self.rect.width <NEW_LINE> self.rect... | Initialize the alien and set its starting possition | 625941ddc432627299f04f5c |
def substractEqual(self, *args): <NEW_LINE> <INDENT> return _MEDCoupling.MEDCouplingConstOnTimeInterval_substractEqual(self, *args) | substractEqual(self, MEDCouplingTimeDiscretization other)
1 | 625941dd76e4537e8c351989 |
def first_or_default(self, default, predicate=None): <NEW_LINE> <INDENT> if self.closed(): <NEW_LINE> <INDENT> raise ValueError("Attempt to call first_or_default() on a " "closed Queryable.") <NEW_LINE> <DEDENT> return self._first_or_default(default) if predicate is None else self._first_or_default_predicate(default, p... | The first element (optionally satisfying a predicate) or a default.
If the predicate is omitted or is None this query returns the first
element in the sequence; otherwise, it returns the first element in
the sequence for which the predicate evaluates to True. If there is no
such element the value of the default argume... | 625941dd50812a4eaa59c633 |
def _pre_activation_steps(self, context, id_, resource_inventory, data): <NEW_LINE> <INDENT> LOG.info("[%s] Pre-activation checks started" % id_) <NEW_LINE> resource_type = resource_inventory[eon_const.EON_RESOURCE_TYPE] <NEW_LINE> expected_states = eon_const.EXPECTED_STATES_ACTIVATION[resource_type] <NEW_LINE> self.va... | Performs pre-activation checks | 625941dd2ae34c7f2600d445 |
def __init__(self, config, fixperiod): <NEW_LINE> <INDENT> self._config = config <NEW_LINE> self._database = self._config['mysql']['database'] <NEW_LINE> self._table = self._config['mysql']['table'] <NEW_LINE> self._symbols = self._config['symbolpairs'] <NEW_LINE> self._start = self._config['time']['start'] <NEW_LINE> ... | 全局变量和常量
| 625941dd099cdd3c635f0f6e |
def replaceElements(arr: List[int]) -> List[int]: <NEW_LINE> <INDENT> n = -1 <NEW_LINE> for i in range(len(arr)-1, -1, -1): <NEW_LINE> <INDENT> tmp = arr[i] <NEW_LINE> arr[i] = n <NEW_LINE> if tmp > arr[i]: <NEW_LINE> <INDENT> n = tmp <NEW_LINE> <DEDENT> <DEDENT> return arr | Replace every element in the array with the greatest element among the
elements to its right, and replace the last element with -1.
:param arr: array of integers to mutate
:return: mutated array | 625941dddc8b845886cb584b |
@app.route("/bearing") <NEW_LINE> def flask_bearing_entry(): <NEW_LINE> <INDENT> return flask.render_template("bearing_entry.html") | Render bearing entry page | 625941ddf8510a7c17cf9a13 |
def __init__(self, settings, patterns): <NEW_LINE> <INDENT> super(DirAttr, self).__init__() <NEW_LINE> self.blacklist_patterns = set() <NEW_LINE> self.settings = { "encryption_mode": 'none', "public": False, } <NEW_LINE> self._init(settings, patterns) <NEW_LINE> self._settings = settings <NEW_LINE> self._patterns = pat... | settings: map str => str. a collection of settings for this
directory. that are automatically inherited by children
patterns: set str. a collection of unix-style glob patterns
used to blacklist certain files by name | 625941dd596a897236089dd2 |
def rmcmp(self, src1, src2): <NEW_LINE> <INDENT> return 'rmcmp {} {}'.format(src1, src2) | reg memery
cmp src1 src2
如果 src1 - src2 = 0 则 zf 置位
src1 > src2 则 sf 置位
:return: | 625941ddec188e330fd5aaae |
def align_to_line(self, wave): <NEW_LINE> <INDENT> for i in range(len(self)): <NEW_LINE> <INDENT> self.data_y[i] = wave.value_at(self.data_x[i]) | Aligns all points' y values to the value of a `Wave` at the
same x. | 625941dd21bff66bcd684c64 |
def play_ringtone_thread_alive(self) -> bool: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.__ringtone_thread.is_alive() <NEW_LINE> <DEDENT> except ThreadError as e: <NEW_LINE> <INDENT> print("Exception (Telephone, play_ringtone_thread_alive: {0})" .format(e)) <NEW_LINE> return False <NEW_LINE> <DEDENT> exce... | Haal de thread status op van de ringtone.
:return: Of de ringtone actief is of niet als boolean. | 625941dd56b00c62f0f1496f |
def testIndexValue(self): <NEW_LINE> <INDENT> die = dice.Die([1.5, 2.5, 3.5]) <NEW_LINE> check = [0, 1, 1, 1, 0, 0] <NEW_LINE> self.assertEqual(1, check[die]) | Test value when converting a die to an index. | 625941dd07f4c71912b11799 |
def __getattr__(self, item): <NEW_LINE> <INDENT> if item == 'name': <NEW_LINE> <INDENT> return 'no name' <NEW_LINE> <DEDENT> if item == 'age': <NEW_LINE> <INDENT> return lambda :25 | 调用不存在的属性时会用这个方法 | 625941dd91f36d47f21ac80a |
def _placeholder(dtype, shape=None, name=None): <NEW_LINE> <INDENT> return _op_def_lib.apply_op("Placeholder", dtype=dtype, shape=shape, name=name) | A placeholder op for a value that will be fed into the computation.
N.B. This operation will fail with an error if it is executed. It is
intended as a way to represent a value that will always be fed, and to
provide attrs that enable the fed value to be checked at runtime.
Args:
dtype: A `tf.DType`. The type of ele... | 625941dd6e29344779a62924 |
def new_url(module): <NEW_LINE> <INDENT> url_base = "/axapi/v3/interface/management/lldp" <NEW_LINE> f_dict = {} <NEW_LINE> return url_base.format(**f_dict) | Return the URL for creating a resource | 625941dd4e696a04525c9761 |
@anything_command() <NEW_LINE> def tlist(): <NEW_LINE> <INDENT> vim.command("Tlist") | taglist Tlist | 625941dd76d4e153a657ee47 |
def remove_db(vdb:VariantsDb): <NEW_LINE> <INDENT> vdb.is_active = 0 <NEW_LINE> vdb.save() <NEW_LINE> remove_db_from_settings(vdb.name) <NEW_LINE> remove_db_from_cache(vdb.name) | Remove that db from settings, connections, cache, and deactivate it. | 625941dd26068e7796caeff7 |
def _create_launchers(self): <NEW_LINE> <INDENT> self._print("Creating launchers") <NEW_LINE> self.create_launcher( 'WinPython Command Prompt.exe', 'cmd.ico', command='$SYSDIR\cmd.exe', args=r'/k cmd.bat', ) <NEW_LINE> self.create_launcher( 'WinPython Powershell Prompt.exe', 'powershell.ico', command='$SYSDIR\cmd.exe',... | Create launchers | 625941dd1f037a2d8b946512 |
def download_nidm_pain(data_dir=None, overwrite=False): <NEW_LINE> <INDENT> url = "https://neurovault.org/collections/1425/download" <NEW_LINE> dataset_name = "nidm_21pain" <NEW_LINE> data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir) <NEW_LINE> desc_file = op.join(data_dir, "description.txt") <NEW_LINE> if o... | Download NIDM Results for 21 pain studies from NeuroVault for tests.
.. versionadded:: 0.0.2
Parameters
----------
data_dir : :obj:`pathlib.Path` or :obj:`str`, optional
Path where data should be downloaded. By default, files are downloaded in home directory.
A subfolder, named ``neuroquery``, will be created... | 625941dd91af0d3eaac9bd30 |
def SearchJsonTandemX(volume,params): <NEW_LINE> <INDENT> datadir = params.datadir <NEW_LINE> jsonpath = params.path <NEW_LINE> minlon = params.minlon <NEW_LINE> maxlon = params.maxlon <NEW_LINE> minlat = params.minlat <NEW_LINE> maxlat = params.maxlat <NEW_LINE> user = params.username <NEW_LINE> pswd = params.password... | Search GeoJson for tandemX tiles to download
| 625941dd379a373c97cfae5b |
def S(x=ANYTHING, t=None): <NEW_LINE> <INDENT> return AbstractScalar( {VALUE: x, TYPE: t or xtype.pytype_to_myiatype(type(x))} ) | Generate a symbolic scalar. | 625941dd4a966d76dd551327 |
def _detach_document(self): <NEW_LINE> <INDENT> self._document = None <NEW_LINE> default_theme.apply_to_model(self) | This should only be called by the Document implementation to unset the document field | 625941ddd99f1b3c44c6789f |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(DumpConfiguration, self).__init__(*args, **kwargs) <NEW_LINE> self.allow_extras = True <NEW_LINE> return | DumpConfiguration constructor (allow_extras=True) | 625941dd24f1403a92600e78 |
def _handle_github(self): <NEW_LINE> <INDENT> value = click.prompt( _BUG + click.style( '1. Open an issue by typing "open";\n', fg='green', ) + click.style( '2. Print human-readable information by typing ' '"print";\n', fg='yellow', ) + click.style( '3. See the full traceback without submitting details ' '(default: "ig... | Handle exception and submit it as GitHub issue. | 625941dd60cbc95b062c6858 |
def init_model(self): <NEW_LINE> <INDENT> self.model = KSession(self.name, self.model_path, allow_growth=self.config["allow_growth"], exclude_gpus=self._exclude_gpus) <NEW_LINE> self.model.load_model() <NEW_LINE> placeholder_shape = (self.batchsize, self.input_size, self.input_size, 3) <NEW_LINE> placeholder = np.zeros... | Initialize FAN model | 625941dd99cbb53fe6792efb |
def get_name(self): <NEW_LINE> <INDENT> return self.name | Get User name | 625941ddfff4ab517eb2f752 |
def hospitalized_case(I, AGE_DATA): <NEW_LINE> <INDENT> AGE_DATA['Snapshot_hospitalized'] = round(AGE_DATA['Proportion_DE_2020'] * I * AGE_DATA['Hospitalization Rate']) <NEW_LINE> no_h = AGE_DATA['Snapshot_hospitalized'].sum() <NEW_LINE> return no_h | Calculated hospitalization cases | 625941dde76e3b2f99f3ab1c |
def eliminate_implications(expr): <NEW_LINE> <INDENT> expr = sympify(expr) <NEW_LINE> if expr.is_Atom: <NEW_LINE> <INDENT> return expr <NEW_LINE> <DEDENT> args = list(map(eliminate_implications, expr.args)) <NEW_LINE> if expr.func is Implies: <NEW_LINE> <INDENT> a, b = args[0], args[-1] <NEW_LINE> return (~a) | b <NEW_... | Change >>, <<, and Equivalent into &, |, and ~. That is, return an
expression that is equivalent to s, but has only &, |, and ~ as logical
operators.
Examples
========
>>> from sympy.logic.boolalg import Implies, Equivalent, eliminate_implications
>>> from sympy.abc import A, B, C
>>> eliminate_implications(... | 625941dda934411ee37519a9 |
def load_cmdline_args(subp, parents=[]): <NEW_LINE> <INDENT> extra_p = subp.add_parser('extra', help='Additional algorithms and tools') <NEW_LINE> extra_sub = extra_p.add_subparsers() <NEW_LINE> for importer, modname, ispkg in pkgutil.iter_modules(__path__, prefix=__name__ + '.'): <NEW_LINE> <INDENT> logger.debug("Foun... | Load all of the 'extra' modules and
have them attach themselves to the commandline
arguments via :subp: | 625941dd24f1403a92600e79 |
def fitline(x, y, lo=0, hi=1, doplot=True, quiet=True, linewidth=2): <NEW_LINE> <INDENT> lendat = len(x) <NEW_LINE> assert hi > lo <NEW_LINE> if lo >= 0 and hi <= 1: <NEW_LINE> <INDENT> loix = int(lendat*lo) <NEW_LINE> hiix = int(lendat*hi) <NEW_LINE> <DEDENT> elif lo >=0 and hi > 0: <NEW_LINE> <INDENT> loix = int(lo) ... | fitline takes the position of low and high fit limits and
returns the slope. Integer indices in the x data set can be
specified for the low and high limits, otherwise use a fraction
between 0 and 1.
In application to fractal dimension estimation, if
x = log d (radius, a.k.a. inter-point distance) and
y = log v (index,... | 625941dd44b2445a339323a9 |
def get_file(fname, parent): <NEW_LINE> <INDENT> assert parent, 'parent not set' <NEW_LINE> not_trash_query = "trashed=false" <NEW_LINE> folder_query = f"'{parent}' in parents" <NEW_LINE> name_query = f"name='{fname}'" <NEW_LINE> query = f"{folder_query} and {name_query} and {not_trash_query}" <NEW_LINE> fields = 'next... | return file_id if it exists,
otherwise return None | 625941dd187af65679ca5434 |
def testTempFilenameSuffix(self): <NEW_LINE> <INDENT> filename = self.tempfile._TempFilename(suffix='.suffix') <NEW_LINE> self.assertTrue(filename.startswith('/tmp/tmp')) <NEW_LINE> self.assertTrue(filename.endswith('.suffix')) <NEW_LINE> self.assertLess(len('/tmp/tmpX.suffix'), len(filename)) | test tempfile._TempFilename(suffix=). | 625941ddfff4ab517eb2f753 |
def get_pixels_per_mm(self): <NEW_LINE> <INDENT> pixels_per_mm_x, pixels_per_mm_y = self.get_zoom_calibration() <NEW_LINE> return (pixels_per_mm_x, pixels_per_mm_y) | Override method. | 625941dd5fc7496912cc3c93 |
def run(self): <NEW_LINE> <INDENT> raise NotImplementedException() | Run the main loop for this server instance.
:since: v1.0.0
| 625941ddcb5e8a47e48b7dbb |
def confusion_matrix(expected: np.ndarray, predicted: np.ndarray, num_classes: int) -> np.ndarray: <NEW_LINE> <INDENT> assert np.issubclass_(expected.dtype.type, np.integer), " Classes' indices must be integers" <NEW_LINE> assert np.issubclass_(predicted.dtype.type, np.integer), " Classes' indices must be integers" <NE... | Calculate and return confusion matrix for the predicted and expected labels
:param expected: array of expected classes (integers) with shape `[num_of_data]`
:param predicted: array of predicted classes (integers) with shape `[num_of_data]`
:param num_classes: number of classification classes
:return: confusion matrix ... | 625941dd2c8b7c6e89b35ad4 |
def cycle_induced_subgraph(g): <NEW_LINE> <INDENT> return nx.DiGraph( ( edge for scc in nx.strongly_connected_component_subgraphs( g ) for edge in scc.edges_iter() )) | Computes the subgraph that is maximally edge-induced by its cycles
That is, every cycle that is in g is also in cycle_induced_subgraph(g). | 625941dd66656f66f7cbc4c1 |
def compare_centers(folders, names, parttype='stars', begin=0, end=40, Rd=0, snapbase='snap_', outname='', outfolder='/home/pardy/plots/', first_only=True, com=True, contours=20, axis=None, returnOnly=False, settings=None, plot_settings='-', plot=False, measure_fourier=False): <NEW_LINE> <INDENT> if settings is None: <... | Function is being deprecated... functionality too limited and convoluted
Compare the bar-disk offset of a few different sets of snapshots | 625941dd57b8e32f524837b2 |
def sr1_update(s, y, x, gfv, opts): <NEW_LINE> <INDENT> yy = np.dot(y.T, y) <NEW_LINE> sy = np.dot(s.T, y) <NEW_LINE> tau = sy / yy <NEW_LINE> tau = np.median([opts.tau_min, tau, opts.tau_max]) <NEW_LINE> d = opts.gamma * tau <NEW_LINE> if sy - d * yy <= 1e-8 * np.sqrt(yy) * npl.norm(s - d * y): <NEW_LINE> <INDENT> uin... | Computes 0-memory SR1 update and forward step: x_k - B_k * gf | 625941dd97e22403b379d2b0 |
def _calculate_portfolio_returns(self, all_weights, relative_return): <NEW_LINE> <INDENT> self.portfolio_return = np.diagonal(np.dot(relative_return, all_weights.T)).cumprod() | Calculates cumulative portfolio returns.
:param all_weights: (np.array) Portfolio weights for the time period.
:param relative_return: (np.array) Relative returns of the assets. | 625941dd63f4b57ef0001427 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, GETAccountType): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941dd7c178a314d6ef779 |
def createObjectData(self, name): <NEW_LINE> <INDENT> return {} | :type name: str
:rtype: dict | 625941dd91af0d3eaac9bd31 |
def load_mmtf(filename, object='', discrete=0, multiplex=0, zoom=-1, quiet=1, _self=cmd): <NEW_LINE> <INDENT> from chempy.mmtf import MmtfReader <NEW_LINE> if not object: <NEW_LINE> <INDENT> object = filename_to_objectname(filename) <NEW_LINE> <DEDENT> data = MmtfReader.from_url(filename) <NEW_LINE> models = data.to_ch... | DESCRIPTION
Load an MMTF file or URL.
| 625941dd6fece00bbac2da57 |
def dobleClickCabecera(self, numColumna): <NEW_LINE> <INDENT> if hasattr(self.wParent, "gridDobleClickCabecera"): <NEW_LINE> <INDENT> self.wParent.gridDobleClickCabecera(self, self.oColumnasR.columna(numColumna)) | Se gestiona este evento, ante la posibilidad de que la ventana quiera controlar,
los doble clicks sobre la cabecera , normalmente para cambiar el orden de la columna,
llamando a la rutina correspondiente si existe (gridDobleClickCabecera) y con el
argumento del objeto columna | 625941dd15fb5d323cde0e29 |
def plotDecisionBoundary(theta, X, y, lam): <NEW_LINE> <INDENT> if X.shape[1] <= 3: <NEW_LINE> <INDENT> plot_x = np.array([min(X[:, 1])-2, max(X[:, 1])+2]) <NEW_LINE> plot_y = (-1/theta[2])*(theta[1]*plot_x + theta[0]) <NEW_LINE> plt.plot(plot_x, plot_y) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> u = np.linspace(-1... | Plot the data points & decision boundary defined by theta. | 625941dd3c8af77a43ae3ab8 |
def prepVibron(self): <NEW_LINE> <INDENT> if self.state == State.PREPVIB: <NEW_LINE> <INDENT> prepVibron_calculation(self.path_root, self.name, self.zmat, self.parameter_dictionary) <NEW_LINE> self.advance() <NEW_LINE> <DEDENT> return | wrapper method | 625941dd046cf37aa974d05b |
def __type_check(self, url): <NEW_LINE> <INDENT> match = self.regex_ep.match(url) <NEW_LINE> if match: <NEW_LINE> <INDENT> return 'bangumi', match.groupdict() <NEW_LINE> <DEDENT> match = self.regex_home.match(url) <NEW_LINE> if match: <NEW_LINE> <INDENT> return 'bangumi_home', match.groupdict() <NEW_LINE> <DEDENT> matc... | use match,not fullmatch | 625941dd7047854f462a171c |
def check_path(path): <NEW_LINE> <INDENT> if len(path) > 140: <NEW_LINE> <INDENT> msg = ('ERROR: Directory "' + path + '" is too deep. Please choose a shallow directory' '(something like "C:\PUMA").') <NEW_LINE> raise_error(msg) <NEW_LINE> <DEDENT> if "-" in path or " " in path or "." in path: <NEW_LINE> <INDENT> msg ... | Checks to make sure path name is not too long.
Long path names can cause problems with ESRI grids. | 625941dda17c0f6771cbe365 |
def test_all(prt=sys.stdout): <NEW_LINE> <INDENT> obj = PlotCli() <NEW_LINE> for idx, cmdargs in enumerate(CMDS): <NEW_LINE> <INDENT> prt.write("\n#######################################################\n") <NEW_LINE> prt.write("{I}) ARGS({ARGS})\n".format(I=idx, ARGS=cmdargs)) <NEW_LINE> args = _get_arg_list(cmdargs) ... | Test all listed plotting commands. | 625941dd507cdc57c6306ff7 |
def choose_NL_split(self): <NEW_LINE> <INDENT> max_bins_list = [] <NEW_LINE> counter = 1 <NEW_LINE> for key in self.dict1: <NEW_LINE> <INDENT> while self.compare_checklist(key, counter) is True: <NEW_LINE> <INDENT> counter += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> counter -= 1 <NEW_LINE> max_bins_list.append(c... | determines how many times the normalised distance can
be split such that there is at least one data point
in each "bin" for each cell | 625941dd460517430c394494 |
def _process_element(self, element): <NEW_LINE> <INDENT> tag = element.tag <NEW_LINE> if tag in self._element_handlers: <NEW_LINE> <INDENT> handler = self._element_handlers[tag] <NEW_LINE> logger.debug("Passing element {0!r} to method {1!r}" .format(element, handler)) <NEW_LINE> handled = handler(self, element) <NEW_LI... | Process first level element of the stream.
The element may be stream error or features, StartTLS
request/response, SASL request/response or a stanza.
:Parameters:
- `element`: XML element
:Types:
- `element`: :etree:`ElementTree.Element` | 625941dd92d797404e3044a0 |
def connect(self): <NEW_LINE> <INDENT> self.logger.debug( "Connecting to SMTP: %s:%d" % (self.host(), self.port()) ) <NEW_LINE> try: <NEW_LINE> <INDENT> self._conn = SMTP_SSL( host=self.host(), port=self.port(), timeout=self.timeout() ) <NEW_LINE> self._authenticate() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LIN... | Connects to the configured SMTP server.
| 625941dd92d797404e3044a1 |
def exportContentsAsCSV(self): <NEW_LINE> <INDENT> retval = "" <NEW_LINE> retval = retval + "Content\n" <NEW_LINE> for p in self.getAllContents(): <NEW_LINE> <INDENT> retval = retval + '\"{0}\"\n'.format(p) <NEW_LINE> <DEDENT> return retval | Export the contents only without associations
| 625941dd8da39b475bd6528c |
def filter(self, specific_fileids): <NEW_LINE> <INDENT> (interesting, parent_to_children) = self._expand_fileids_to_parents_and_children( specific_fileids) <NEW_LINE> other = Inventory(self.root_id) <NEW_LINE> other.root.revision = self.root.revision <NEW_LINE> other.revision_id = self.revision_id <NEW_LINE> if not int... | Get an inventory view filtered against a set of file-ids.
Children of directories and parents are included.
The result may or may not reference the underlying inventory
so it should be treated as immutable. | 625941dd5166f23b2e1a546e |
def _safe_eval(node, default): <NEW_LINE> <INDENT> if isinstance(node, ast.BoolOp): <NEW_LINE> <INDENT> results = [_safe_eval(value, default) for value in node.values] <NEW_LINE> if isinstance(node.op, ast.And): <NEW_LINE> <INDENT> return all(results) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return any(results) <N... | Safely evaluate the Boolean expression under the given AST node.
Substitute `default` for all sub-expressions that cannot be
evaluated (because variables or functions are undefined).
We could use eval() to evaluate more sub-expressions. However, this
function is not safe for arbitrary Python code. Even after
overwrit... | 625941dd4f6381625f114d51 |
def drop_cols_including_with_text(df_in: pd.DataFrame, text_list: list): <NEW_LINE> <INDENT> for text in text_list: <NEW_LINE> <INDENT> df_in = df_in[df_in.columns.drop(list(df_in.filter(regex=text)))] <NEW_LINE> <DEDENT> return df_in | dropColsStartingWithText: drop cols starting with text in text_list
df: data frame to drop columns
text_list: potential text list including texts to look for on df | 625941dd38b623060ff0b103 |
def plot_train_test(train, test, block_x, block_y,group_num, save_file): <NEW_LINE> <INDENT> fig, ax = plt.subplots(figsize=(12,5)) <NEW_LINE> c = ax.scatter(train["longitude"], train["latitude"], alpha=0.5, c=train["tot.catch"], cmap='viridis', label = "train") <NEW_LINE> ax.scatter(test["longitude"], test["latitude"]... | plot how data are blocked, and show the train set and test set | 625941dda219f33f34628c7b |
def test_metrics_with_summary_without_error(): <NEW_LINE> <INDENT> global output_directory <NEW_LINE> global input_log_directory <NEW_LINE> global resource_path <NEW_LINE> rules = {} <NEW_LINE> metrics = get_three_metrics(output_directory, resource_path, rules) <NEW_LINE> for metric in metrics: <NEW_LINE> <INDENT> file... | Tests to verify that metric reports are generated if the metrics are not in error. Also a summary report should be created. | 625941ddb830903b967e9c1e |
def load_template(self, template): <NEW_LINE> <INDENT> def internal_load_template(): <NEW_LINE> <INDENT> local_path = template.local_path <NEW_LINE> if local_path is not None and isfile(local_path): <NEW_LINE> <INDENT> with open(local_path) as template_file: <NEW_LINE> <INDENT> return TemplateContent.from_dict(json.loa... | load template into memory either from a local cache path or an remote uri
load template from local file > from from azure
:param template:
:return: | 625941dd23e79379d52ee876 |
def updateGeometry(self): <NEW_LINE> <INDENT> orig = QtCore.QPointF(0, 0) <NEW_LINE> end = orig + self.end - self.origin <NEW_LINE> self._line = QtCore.QLineF(orig, end) <NEW_LINE> x1 = self._line.p1().x() <NEW_LINE> x2 = self._line.p2().x() <NEW_LINE> y1 = self._line.p1().y() <NEW_LINE> y2 = self._line.p2().y() <NEW_L... | Updates the internal representation of the line and boundingRect
when it has been modified | 625941ddd268445f265b5184 |
def getShowSummary(self): <NEW_LINE> <INDENT> return self.stringsToRemove(self.showdescription) | Returns summary of the show as a string, stripped of its <b> and <p> elements.
Args:
N/A
Returns:
Summary as a string
Raises:
N/A | 625941dd5166f23b2e1a546f |
def return_event(self, event): <NEW_LINE> <INDENT> self.change_cell() <NEW_LINE> x, y = self.currentxy <NEW_LINE> self.setcurrent(x, y+1) <NEW_LINE> return "break" | Callback for the Return key. | 625941dd60cbc95b062c6859 |
def execute(self): <NEW_LINE> <INDENT> log.info("Start executing workflow '{0}'.".format(self.id)) <NEW_LINE> topology = Topology(self) <NEW_LINE> topology.translate() <NEW_LINE> for layer in topology.layers: <NEW_LINE> <INDENT> for elem in layer: <NEW_LINE> <INDENT> if isinstance(elem, Table): <NEW_LINE> <INDENT> elem... | Execute the whole workflow.
This means executing all tables according to their dependencies. | 625941dd1d351010ab855e31 |
def reset_count(self): <NEW_LINE> <INDENT> self.explore_cnt = 0 <NEW_LINE> return self | Resets the counter for exploitation mode
Returns
-------
self | 625941dd090684286d50effe |
def send_user_agent(self, connection): <NEW_LINE> <INDENT> if not self._user_agent: <NEW_LINE> <INDENT> self._user_agent = '%s %s' % (xmlrpclib.Transport.user_agent, 'gandi.cli/%s' % __version__) <NEW_LINE> <DEDENT> connection.putheader('User-Agent', self._user_agent) | Add User-Agent header to request if not already existing. | 625941dd07d97122c4178ba7 |
def __call__(db, servicePath): <NEW_LINE> <INDENT> pass | Run the processor.
The ``db`` is a ZODB instance that is used to call back into the task
service. The ``servicePath`` specifies how to traverse to the task
service itself. | 625941ddbe7bc26dc91cd910 |
def get_operator_precedence_by_sign(sign): <NEW_LINE> <INDENT> for operator in OPERATORS: <NEW_LINE> <INDENT> if operator.sign == sign: <NEW_LINE> <INDENT> return operator.precedence <NEW_LINE> <DEDENT> <DEDENT> return 0 | Returns the precedence of the sign by its value | 625941dd3d592f4c4ed1d37c |
def is_wo_id_in_event(event, *kargs, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> wo_id_from_event_bytes = event["args"]["workOrderId"] <NEW_LINE> <DEDENT> except KeyError as e: <NEW_LINE> <INDENT> logging.error("Exception caught when trying to read workOrderId" + " from event {}".format(event)) <NEW_LINE> l... | This function checks if a specific work order id(passed
in via kwargs) is there in the event as well. So, it is
basically trying to see if the event is meant for this
work order id.
Returns:
True - if the work order id matches
False - otherwise | 625941dd3346ee7daa2b3083 |
def on_upgrade(db, pre): <NEW_LINE> <INDENT> on_install(db) | will be execute when upgrade.
raise any exception to revert the upgrade.
:param db:
:param pre: previous version code
:return: | 625941dd85dfad0860c3b172 |
def hyperbolic_distance(u, v): <NEW_LINE> <INDENT> difference_norm = tf.norm( tf.subtract(x=u, y=v), ord='euclidean', axis=1) <NEW_LINE> norm_u = tf.norm(tensor=u, ord='euclidean', axis=1) <NEW_LINE> norm_v = tf.norm(tensor=v, ord='euclidean', axis=1) <NEW_LINE> content = 1 + 2 * tf.square(difference_norm) / (1 - tf.sq... | computes the hyperbolic distance between u and v
:param u: a tensor of size [1, embedding_size, batch_size]
:param v: a tensor of size [1, embedding_size, batch_size]
:return: a tensor of size [1, batch_size] containing the distances | 625941dd283ffb24f3c55c14 |
def _resolved_type(self): <NEW_LINE> <INDENT> import datetime <NEW_LINE> self.type_ratios = {test: (float(self.type_counts[test]) / float(self.count)) if self.count else None for test, testf in tests + [(None, None)]} <NEW_LINE> if self.type_ratios[binary_type] > .05: <NEW_LINE> <INDENT> return binary_type, False <NEW_... | Return the type for the columns, and a flag to indicate that the
column has codes. | 625941dd379a373c97cfae5c |
def abundant( source ): <NEW_LINE> <INDENT> return ( i for i in source if sum(properDivisors(i)) > i ) | Filter a source for abundant numbers.
>>> from euler23 import abundant
>>> list(abundant( (11, 12, 13) ))
[12] | 625941dd4d74a7450ccd44da |
def read(filename): <NEW_LINE> <INDENT> key = [] <NEW_LINE> file = open(filename, 'rb') <NEW_LINE> byte = file.read(1) <NEW_LINE> while byte != b'': <NEW_LINE> <INDENT> block = [] <NEW_LINE> for i in range(0, 4): <NEW_LINE> <INDENT> col = [] <NEW_LINE> for i in range(0, 4): <NEW_LINE> <INDENT> if byte != b'': <NEW_LINE... | Reads in file into 16-byte blocks. | 625941dd236d856c2ad44af4 |
def convertMaskStep(self, maskType): <NEW_LINE> <INDENT> if maskType > 0: <NEW_LINE> <INDENT> maskFn = self._getTmpPath('mask.img') <NEW_LINE> ImageHandler().convert(self.maskImage.get(), maskFn) | Convert the input mask to Imagic. | 625941dd66673b3332b923a7 |
def check_for_encrypted_badge_num(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def with_check(*args, **kwargs): <NEW_LINE> <INDENT> if kwargs.get('badge_num', None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> int(kwargs['badge_num']) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> kwargs['badge_num'] ... | On some pages, we pass a 'badge_num' parameter that might EITHER be a literal
badge number or an encrypted value (i.e., from a barcode scanner). This
decorator searches for a 'badge_num' parameter and decrypts it if necessary. | 625941dd4c3428357757c63c |
def process(document, rtype=None, api=None): <NEW_LINE> <INDENT> result = [] <NEW_LINE> if 'disambiguated-phrase' in document['annotations']: <NEW_LINE> <INDENT> terms, ids, kbnames = [], [], [] <NEW_LINE> for term in document['annotations']['disambiguated-phrase']: <NEW_LINE> <INDENT> term_id = term['value']['id'] <NE... | Receives a texterra-annotated annotated_text and returns its terms' list. | 625941dd1f5feb6acb0c4e61 |
def get_distribution(): <NEW_LINE> <INDENT> distribution = None <NEW_LINE> if platform.system() == 'Linux': <NEW_LINE> <INDENT> distribution = distro.name().capitalize() <NEW_LINE> distribution_words = distribution.split() <NEW_LINE> if 'Amazon' in distribution_words: <NEW_LINE> <INDENT> distribution = 'Amazon' <NEW_LI... | Return the name of the distribution the module is running on
:rtype: NativeString or None
:returns: Name of the distribution the module is running on
This function attempts to determine what Linux distribution the code is running on and return
a string representing that value. If the distribution cannot be determine... | 625941dd55399d3f055889cb |
def __init__(self, interface=("localhost", 10000)): <NEW_LINE> <INDENT> Device.__init__(self) <NEW_LINE> self._host, self._port = interface <NEW_LINE> self._use_ssl = False <NEW_LINE> self._ssl_certificate = None <NEW_LINE> self._ssl_key = None <NEW_LINE> self._ssl_ca = None <NEW_LINE> self._ssl_allow_self_signed = Fal... | Constructor
:param interface: Tuple containing the hostname and port of our target
:type interface: tuple | 625941dd2eb69b55b151cbc9 |
def test_exposed_props(self): <NEW_LINE> <INDENT> self.run_script('obj.__exposedProps__ = {};') <NEW_LINE> self.assert_warnings({ 'id': Contains('**.__exposedProps__'), 'message': Contains('deprecated'), 'description': Matches('`cloneInto` or `exportFunction`'), 'signing_help': Matches('expose APIs'), 'signing_severity... | Test that assignment to __exposedProps__ raises signing warnings. | 625941dd0fa83653e46572cf |
def move_horizontal(self, direc, dt): <NEW_LINE> <INDENT> if(self._movable == "left" and direc == -1 or self._movable == "right" and direc == 1) : <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self._grounded: <NEW_LINE> <INDENT> self._xpos += direc * (0.85 + dt) <NEW_LINE> <DEDENT> else: <NE... | this method moves the player on the x axis
depending on the direction.
It also takes into acount if the player is in the
air or not, if he is => move slower
if not => move faster | 625941dd462c4b4f79d1d9e6 |
def __init__( self, estimator: "OBJECT_DETECTOR_TYPE", patch_shape: Tuple[int, int, int] = (40, 40, 3), learning_rate: float = 5.0, max_iter: int = 500, batch_size: int = 16, verbose: bool = True, ): <NEW_LINE> <INDENT> super().__init__(estimator=estimator) <NEW_LINE> self.patch_shape = patch_shape <NEW_LINE> self.lear... | Create an instance of the :class:`.DPatch`.
:param estimator: A trained object detector.
:param patch_shape: The shape of the adversarial path as a tuple of shape (height, width, nb_channels).
:param learning_rate: The learning rate of the optimization.
:param max_iter: The number of optimization steps.
:param batch_s... | 625941ddd486a94d0b98e45d |
def __init__(self, config=None): <NEW_LINE> <INDENT> super(FollowBasicRestore, self).__init__(config=config) <NEW_LINE> self.__thing = None | Instantiation code in here, after the call to super().__init__()
| 625941dd167d2b6e31218eab |
def get(self): <NEW_LINE> <INDENT> is_cloud_admin = self.helper.is_user_cloud_admin() <NEW_LINE> apps_user_is_admin_on = self.helper.get_owned_apps() <NEW_LINE> if (not is_cloud_admin) and (not apps_user_is_admin_on): <NEW_LINE> <INDENT> self.redirect(DashPage.PATH, self.response) <NEW_LINE> <DEDENT> query = ndb.gql('S... | Handler for GET requests. | 625941ddcdde0d52a9e5334c |
def compatible_versions(self, other): <NEW_LINE> <INDENT> if len(self.candidates) == 1 and first(self.candidates).editable: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> elif len(other.candidates) == 1 and first(other.candidates).editable: <NEW_LINE> <INDENT> return other <NEW_LINE> <DEDENT> return self.version_s... | Find compatible version numbers between this abstract
dependency and another one.
:param other: An abstract dependency to compare with.
:type other: :class:`~requirementslib.models.dependency.AbstractDependency`
:return: A set of compatible version strings
:rtype: set(str) | 625941dd4e696a04525c9762 |
def get_one(self, value, column='_id', is_objectid=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if is_objectid: <NEW_LINE> <INDENT> query = {column: utils.create_objectid(value)} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query = {column: value} <NEW_LINE> <DEDENT> items = self.get_coll().find_one(query) <NEW... | 获取元素
:param value: 元素内容
:param column: 元素在集合中的栏位名
:param is_objectid: 是否是objectid类型
:return: 存在元素内容 | 625941ddd53ae8145f87a581 |
def scores(self, summoner: SummonerAccount, region: str): <NEW_LINE> <INDENT> return eval(bytes( urllib.request.urlopen( self.__score_url.format(region, summoner.summonerId, super()._get_key())).read()).decode()) | :param summoner:
:param region:
:return: | 625941dd07d97122c4178ba8 |
def _pack_data_object(self, data, **kwargs): <NEW_LINE> <INDENT> if not isinstance(data, dict): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> for pack_def in kwargs.values(): <NEW_LINE> <INDENT> key_items = pack_def.get('keys') <NEW_LINE> key_units = pack_def.get('units') <NEW_LINE> units = data.get(key_units) <N... | Pack data into object format. | 625941dd8da39b475bd6528d |
def expected_result(self, item_id, **kwargs): <NEW_LINE> <INDENT> course_ids = kwargs.get('course_ids', None) <NEW_LINE> if course_ids is None: <NEW_LINE> <INDENT> course_ids = [self.course_id] <NEW_LINE> <DEDENT> program = super(ProgramsViewTests, self).expected_result(item_id) <NEW_LINE> program.update([ ('program_ty... | Expected program metadata to populate with data. | 625941dd45492302aab5e5dd |
@csrf_exempt <NEW_LINE> @json_api <NEW_LINE> @require_POST <NEW_LINE> @require_service <NEW_LINE> @authorize <NEW_LINE> def post_predicted_masks(request, service, user_key, session_key): <NEW_LINE> <INDENT> params = request.json <NEW_LINE> params['pred_masks'] = mask_api.decode_batch_masks(params['pred_masks']) <NEW_LI... | Post the predicted masks and return a new scribble.
| 625941dd15baa723493c428d |
def obj_to_dict(obj): <NEW_LINE> <INDENT> data = serializers.serialize('json', [obj, ]) <NEW_LINE> struct = json.loads(data)[0] <NEW_LINE> response = struct['fields'] <NEW_LINE> response[u'id'] = response[u'pk'] = struct['pk'] <NEW_LINE> response[u'model'] = struct['model'] <NEW_LINE> for f in obj._meta.fields: <NEW_LI... | serializes obj for a JSON friendly version
tries to serialize JSONField | 625941ddac7a0e7691ed43dd |
def draw_square(size: int): <NEW_LINE> <INDENT> print('+'+ size * '-' +'+') <NEW_LINE> print(('|'+ size * ' ' +'|\n') * (size//2), end='') <NEW_LINE> print('+'+ size * '-' +'+') | Draw square
e.g.
+----------+
| |
| |
| |
| |
| |
+----------+
Args:
size (int): size of object | 625941ddf9cc0f698b14090f |
def __init__(self, description=None, file_name=None): <NEW_LINE> <INDENT> self._description = None <NEW_LINE> self._file_name = None <NEW_LINE> self.discriminator = None <NEW_LINE> if description is not None: <NEW_LINE> <INDENT> self.description = description <NEW_LINE> <DEDENT> if file_name is not None: <NEW_LINE> <IN... | PUTAttachmentType - a model defined in Swagger | 625941dd15baa723493c428e |
def sample_spawn(self, spawn_index: int, radius: float = 0.3): <NEW_LINE> <INDENT> return self._samples(self.spawns[spawn_index], self.obstacles, radius) | Generator for sampling points inside spawn without overlapping with
obstacles | 625941dd21a7993f00bc800b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.