code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def initializer(func): <NEW_LINE> <INDENT> names, varargs, keywords, defaults = getfullargspec(func) <NEW_LINE> @wraps(func) <NEW_LINE> def wrapper(self, *args, **kargs): <NEW_LINE> <INDENT> for name, arg in list(zip(names[1:], args)) + list(kargs.items()): <NEW_LINE> <INDENT> setattr(self, name, arg) <NEW_LINE> <DEDEN... | Automatically assigns the parameters.
http://stackoverflow.com/questions/1389180/python-automatically-initialize
-instance-variables
>>> class process:
... @initializer
... def __init__(self, cmd, reachable=False, user='root'):
... pass
>>> p = process('halt', True)
>>> p.cmd, p.reachable, p.user
('hal... | 625941c6a219f33f34628987 |
def docker_ver(args): <NEW_LINE> <INDENT> oldstr = run_shell(args, "docker --version | awk '{print $3}'") <NEW_LINE> newstr = oldstr.replace(",", "") <NEW_LINE> return(newstr.rstrip()) | Display Docker version | 625941c671ff763f4b5496a5 |
def predict(self, x): <NEW_LINE> <INDENT> return self.model.func(x, *self.params) | Predict values of the dependent variable based on values of the
indpendent variable.
Parameters
----------
x : float or array
Values of the independent variable. Can be values presented in
the experiment. For out-of-sample prediction (e.g. in
cross-validation), these can be values
that were not present... | 625941c6a17c0f6771cbe06e |
def random_points(n): <NEW_LINE> <INDENT> return [random_point() for _ in range(n)] | ランダムな座標のリストを生成する処理
:rtype: list | 625941c6283ffb24f3c5591e |
@report <NEW_LINE> def testSvmTheoreticalSpectrumGeneratorTrainer(): <NEW_LINE> <INDENT> ff = pyopenms.SvmTheoreticalSpectrumGeneratorTrainer() <NEW_LINE> assert pyopenms.SvmTheoreticalSpectrumGeneratorTrainer().trainModel is not None <NEW_LINE> assert pyopenms.SvmTheoreticalSpectrumGeneratorTrainer().normalizeIntensit... | @tests: SvmTheoreticalSpectrumGeneratorTrainer
SvmTheoreticalSpectrumGeneratorTrainer.__init__ | 625941c65166f23b2e1a5175 |
def refresh(self): <NEW_LINE> <INDENT> self._counter += 1 <NEW_LINE> if self._counter == self._interval: <NEW_LINE> <INDENT> self._value = self.getLocalValue() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass | Refresh on a certain interval. | 625941c6d4950a0f3b08c36c |
def list_images(self): <NEW_LINE> <INDENT> if not (self.tenant_id and self.region): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> shared_images = self._get_shared_images(self.tenant_id, self.region, __version__) <NEW_LINE> images = {} <NEW_LINE> for i in shared_images: <NEW_LINE> <INDENT> i... | Return a dictionary containing RackSpace server images
retrieved from gns3-ias server | 625941c692d797404e3041a6 |
def filename_to_object(filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = (Archive(filename), None) <NEW_LINE> <DEDENT> except Exception as exception: <NEW_LINE> <INDENT> result = (filename, str(exception)) <NEW_LINE> <DEDENT> return result | Given a filename create a defoe.books.archive.Archive. If an error
arises during its creation this is caught and returned as a
string.
:param filename: filename
:type filename: str or unicode
:return: tuple of form (Archive, None) or (filename, error message),
if there was an error creating Archive
:rtype: tuple(defo... | 625941c6b545ff76a8913e32 |
def endpoint_absent(name, region=None, profile=None, interface=None, **connection_args): <NEW_LINE> <INDENT> ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Endpoint for service "{0}"{1} is already absent'.format(name, ', interface "{0}",'.format(interface) if interface is not None else '')} <NEW_LINE> ... | Ensure that the endpoint for a service doesn't exist in Keystone catalog
name
The name of the service whose endpoints should not exist
region (optional)
The region of the endpoint. Defaults to ``RegionOne``.
interface
The interface type, which describes the visibility
of the endpoint. (for V3 API) | 625941c6d58c6744b4257c7c |
def SoXtGLWidget_getClassTypeId(): <NEW_LINE> <INDENT> return _soxt.SoXtGLWidget_getClassTypeId() | SoXtGLWidget_getClassTypeId() -> SoType | 625941c64f6381625f114a58 |
def process_response(self, request, response): <NEW_LINE> <INDENT> if response.status_code != 500 and hasattr(request, 'token') and request.token.is_active: <NEW_LINE> <INDENT> if not request.token.expiration: <NEW_LINE> <INDENT> max_age = config.IS_CORE_AUTH_COOKIE_AGE <NEW_LINE> expires_time = time.time() + max_age <... | Set cookie with token key if user is authenticated | 625941c66fb2d068a760f0b8 |
def parse_reqservice(reqservice): <NEW_LINE> <INDENT> rs_lexer = ECS_Lexer() <NEW_LINE> output = {} <NEW_LINE> if type(reqservice) != ListType: <NEW_LINE> <INDENT> raise InvalidRulesSintaxException("Invalid ReqService field: Type error: Not a list of 2 element lists") <NEW_LINE> <DEDENT> elif len(reqservice) > 0: <NEW_... | Parse given ReqService field.
@param reqservice Requested service properties by a node. The type of
this field is a list of 2 element lists, each specifying a pair:
(variable name, varuable value).
@return Dictionary with the parsed data. The format of the dictionary:
key: variable name; value: variable value. | 625941c6baa26c4b54cb113d |
def plot(self, loss_list): <NEW_LINE> <INDENT> window_size = len(loss_list) // 100 <NEW_LINE> plt.figure(1) <NEW_LINE> sub_plot(221, self.scores, y_label='Score') <NEW_LINE> sub_plot(223, self.avg_scores, y_label='Avg Score', x_label='Episodes') <NEW_LINE> sub_plot(222, loss_list, y_label='Loss') <NEW_LINE> avg_loss = ... | Plot stats in nice graphs. | 625941c630c21e258bdfa4b8 |
def create_pretrained_embedding(pretrained_weights, trainable=False, **kwargs): <NEW_LINE> <INDENT> in_dim, out_dim = pretrained_weights.shape <NEW_LINE> embedding = Embedding(in_dim, out_dim, weights=[pretrained_weights], trainable=False, **kwargs) <NEW_LINE> return embedding | Create embedding layer from a pretrained weights array | 625941c64f88993c3716c084 |
def to_json(self): <NEW_LINE> <INDENT> return_string = "{\"cue_list_number\": " + str(self.cue_list_number) + ", \"cues\": " <NEW_LINE> return_string = return_string + "[" <NEW_LINE> for cue in self.cues: <NEW_LINE> <INDENT> return_string = return_string + cue.to_json() <NEW_LINE> return_string = return_string + "," <N... | Return CueList as a json string | 625941c6cdde0d52a9e5304e |
def bin_prop_jeffreys_interval(trials, successes, α=0.05): <NEW_LINE> <INDENT> n = int(trials) <NEW_LINE> x = int(successes) <NEW_LINE> assert 0 <= x <= n <NEW_LINE> beta = scipy.stats.beta(x + 0.5, n - x + 0.5) <NEW_LINE> if x == 0: <NEW_LINE> <INDENT> low = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> low = beta.p... | Binomial proportions confidence Jeffrey's interval.
Parameters
----------
trials : np.ndarray
number of trials
successes : int
number of successes
α : float, 0<α<1
width of confidence interval
Returns
-------
low, high : tuple of floats
The lower and upper bounds of the proportions confidence interval... | 625941c6a934411ee37516b0 |
def vf_squared_hellinger(x, y, critic): <NEW_LINE> <INDENT> f1 = 1.0-torch.exp(-critic(x)) <NEW_LINE> f2 = (1.0-torch.exp(-critic(y)))/torch.exp(-critic(y)) <NEW_LINE> result = torch.mean(f1)-torch.mean(f2) <NEW_LINE> return result | Complete me. DONT MODIFY THE PARAMETERS OF THE FUNCTION. Otherwise, tests might fail.
*** The notation used for the parameters follow the one from Nowazin et al: https://arxiv.org/pdf/1606.00709.pdf
In other word, x are samples from the distribution P and y are samples from the distribution Q. The critic is the
equiva... | 625941c6b5575c28eb68e01b |
@cli.group() <NEW_LINE> def data(): <NEW_LINE> <INDENT> pass | Data related commands. | 625941c6a4f1c619b28b0058 |
def test_decimal(self): <NEW_LINE> <INDENT> def generator(row, col): <NEW_LINE> <INDENT> from decimal import Decimal <NEW_LINE> return Decimal("%d.%02d" % (row, col)) <NEW_LINE> <DEDENT> self._check_data_integrity(('col1 DECIMAL(5,2)',), generator) | test DECIMAL | 625941c655399d3f055886d0 |
def get_param_count(self): <NEW_LINE> <INDENT> return 0 | Return the number of parameters that this generator,
as configured, requires to be optimised.
Outputs:
param_count: non-negative integer - the number of
parameters required. | 625941c632920d7e50b281eb |
def window_grp_speed_05(df, cols = ['Speed_mean'], thres=8, metrics = {"max","mean"}): <NEW_LINE> <INDENT> metrics = sorted(metrics) <NEW_LINE> df['stop_ind'] = np.where(df["stop_sum"]>thres,1,0) <NEW_LINE> df['ind'] = df['missing_ind_max'] + df['signal_weak_max'] + df['stop_ind'] <NEW_LINE> df1 = df.groupby(['bookingI... | Agg. features at sliding window of 10s and overlap window of 5s
:cols = Agg. Columns
:thres: threshold where we consider window as Speed event
:param x:window_feas
:type x: pandas.DataFrame
:return type: DataFrame | 625941c6f8510a7c17cf9718 |
def back_calc_ri(self, spin_index=None, ri_id=None, ri_type=None, frq=None): <NEW_LINE> <INDENT> raise RelaxImplementError('back_calc_ri') | Back-calculation of relaxation data.
@keyword spin_index: The global spin index.
@type spin_index: int
@keyword ri_id: The relaxation data ID string.
@type ri_id: str
@keyword ri_type: The relaxation data type.
@type ri_type: str
@keyword frq: The field strength.
@t... | 625941c63cc13d1c6d3c7397 |
def check_validation_errors(self, params, error_list): <NEW_LINE> <INDENT> err_str = 'KBaseReport parameter validation errors' <NEW_LINE> with self.assertRaisesRegex(TypeError, err_str) as cm: <NEW_LINE> <INDENT> self.getImpl().create_extended_report(self.getContext(), params) <NEW_LINE> <DEDENT> error_message = str(cm... | Check that the appropriate errors are thrown when validating extended report params
Args:
params - parameters to create_extended_report
error_list - set of text regexes to check against the error string
Returns True | 625941c68e71fb1e9831d7c6 |
def __mul__(self, operand): <NEW_LINE> <INDENT> new = copy.deepcopy(self) <NEW_LINE> for term in new.terms: <NEW_LINE> <INDENT> term *= operand <NEW_LINE> <DEDENT> return new | Scalar multiplication. | 625941c6f7d966606f6aa01f |
def get_coverage(counts, file_path="coverage.csv"): <NEW_LINE> <INDENT> odf = overall_coverage(counts) <NEW_LINE> ddf = developable_coverage(counts) <NEW_LINE> df = odf.join(ddf) <NEW_LINE> df["area"] = df.index <NEW_LINE> df = df[["area", "overall_percentage", "developable_percentage"]] <NEW_LINE> df.to_csv(DP.join("t... | Combine overall and developable coverage statistics. | 625941c6b57a9660fec3389f |
def Newton_system(F, J, x, eps): <NEW_LINE> <INDENT> F_value = F(x) <NEW_LINE> F_norm = np.linalg.norm(F_value, ord=2) <NEW_LINE> iteration_counter = 0 <NEW_LINE> while abs(F_norm) > eps and iteration_counter < 100: <NEW_LINE> <INDENT> delta = np.linalg.solve(J(x), -F_value) <NEW_LINE> x = x + delta <NEW_LINE> F_value ... | Solve nonlinear system F=0 by Newton's method.
J is the Jacobian of F. Both F and J must be functions of x.
At input, x holds the start value. The iteration continues
until ||F|| < eps. | 625941c610dbd63aa1bd2bc0 |
def patch_one(self, origin_cgroup): <NEW_LINE> <INDENT> url = ( vari.BASE_URL + "/v1/contact-groups/{}".format(origin_cgroup["id"]) ) <NEW_LINE> payload = cghelp.grab_patch_json(origin_cgroup) <NEW_LINE> self.patch_endpoint(url, payload) | Patch existing.
:param origin_cgroup: json, the original. | 625941c63617ad0b5ed67f14 |
def scmhash(self, notetype: NotetypeDict) -> str: <NEW_LINE> <INDENT> buf = "" <NEW_LINE> for field in notetype["flds"]: <NEW_LINE> <INDENT> buf += field["name"] <NEW_LINE> <DEDENT> for template in notetype["tmpls"]: <NEW_LINE> <INDENT> buf += template["name"] <NEW_LINE> <DEDENT> return checksum(buf) | Return a hash of the schema, to see if models are compatible. | 625941c69f2886367277a8ab |
def readit(in_file, per_lines=False, in_encoding='utf-8', in_errors=None): <NEW_LINE> <INDENT> with open(in_file, 'r', encoding=in_encoding, errors=in_errors) as _rfile: <NEW_LINE> <INDENT> _content = _rfile.read() <NEW_LINE> <DEDENT> if per_lines is True: <NEW_LINE> <INDENT> _content = _content.splitlines() <NEW_LINE>... | Reads a file.
Parameters
----------
in_file : str
A file path
per_lines : bool, optional
If True, returns a list of all lines, by default False
in_encoding : str, optional
Sets the encoding, by default 'utf-8'
in_errors : str, optional
How to handle encoding errors, either 'strict' or 'ignore', by defa... | 625941c6442bda511e8be436 |
def getQValue(self, state, action): <NEW_LINE> <INDENT> sum = 0 <NEW_LINE> feature_dict = self.featExtractor.getFeatures(state, action) <NEW_LINE> for feature in feature_dict.keys(): <NEW_LINE> <INDENT> sum += feature_dict[feature] * self.w[feature] <NEW_LINE> <DEDENT> return sum | Should return Q(state,action) = w * featureVector
where * is the dotProduct operator | 625941c6ec188e330fd5a7be |
@pytest.mark.xfail <NEW_LINE> @pytest.mark.parametrize(('oil', 'temp', 'expected_balance'), [('oil_benzene', 288.15, 9731.05479)]) <NEW_LINE> def test_full_run_no_evap(sample_model_fcn2, oil, temp, expected_balance): <NEW_LINE> <INDENT> low_wind = constant_wind(1., 270, 'knots') <NEW_LINE> low_waves = Waves(low_wind, W... | test dissolution outputs post step for a full run of model. Dump json
for 'weathering_model.json' in dump directory | 625941c65f7d997b87174ab3 |
def put(self, request, membership_id): <NEW_LINE> <INDENT> theirs, yours = self.get_instance(request, membership_id) <NEW_LINE> if yours.is_admin: <NEW_LINE> <INDENT> theirs.is_admin = not theirs.is_admin <NEW_LINE> theirs.save() <NEW_LINE> <DEDENT> return MembershipPresenter(theirs).serialized | A membership object does not need to ever be modified. The only
value that can be changed is whether or not is_admin is true.
For simplicity, a PUT in this case will simply toggle the value. | 625941c68e05c05ec3eea390 |
def serialize_query(data, meta): <NEW_LINE> <INDENT> return { 'data': data, 'meta': meta } | . | 625941c64f88993c3716c085 |
def __init__( self, is_split_sentence=False, rewrite_csv=False, get_only_amendments=True ): <NEW_LINE> <INDENT> self.is_split_sentence = is_split_sentence <NEW_LINE> self.rewrite_csv = rewrite_csv <NEW_LINE> self.get_only_amendments = get_only_amendments | Class initilization
Parameters
----------
is_split_sentence : bool, optional
set True if you want the amendment splitted in sentences, by default True
rewrite_csv : bool, optional
Set True if you want to overwrite csv from json files, by default False | 625941c6046cf37aa974cd65 |
def get_labels(path_to_csv): <NEW_LINE> <INDENT> df = pd.read_csv(path_to_csv) <NEW_LINE> df['file_name'] = 'Calc-Training_' + df['patient_id'] + '_' + df['left or right breast'] + '_' + df['image view'] + '_' + df['abnormality id'].astype(str) + '_mask.png' <NEW_LINE> df = df[['file_name', 'pathology']] ... | Concatenates various components of the named files to a list and returns the file_name and pathology
params:
path_to_csv: path to the CSV with the file list
returns:
a data frame containing the file_name (as an index) and the pathology. | 625941c6ad47b63b2c509f9c |
def getResourceChanges(data): <NEW_LINE> <INDENT> logger.debug("filter resource_changes from plan") <NEW_LINE> if "resource_changes" in data.keys(): <NEW_LINE> <INDENT> return data["resource_changes"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.error("no resource_changes found") <NEW_LINE> return [] | Filters Resource Changes from Plan.
Retrieves the resource_changes portion from terraform plan.
Args:
data (dict): dict from json.load('<terraform plan in json format>')
Returns:
List of resource_changes | 625941c6097d151d1a222e78 |
def numpy(self, workers=cpu_count): <NEW_LINE> <INDENT> return matrix_utils.get_local_matrix(self, workers) | Convert the BigMatrix to a local numpy array.
Parameters
----------
workers : int, optional
The number of local workers to use when converting the array.
Returns
-------
out : ndarray
The numpy version of the BigMatrix object. | 625941c6236d856c2ad447f5 |
def insert_translator_comments(po_filepaths): <NEW_LINE> <INDENT> for po_filepath in po_filepaths: <NEW_LINE> <INDENT> logging.debug("Adding translator comments to %s" % po_filepath) <NEW_LINE> pofile = polib.pofile(po_filepath) <NEW_LINE> for po_entry in pofile: <NEW_LINE> <INDENT> if "%(" in po_entry.msgid and "%(" n... | We want to make sure that translators do not tweak format strings.
We inserted a comment into relevant translation entries when we
detect format strings, to try and help guide the translators. | 625941c6d18da76e235324f1 |
def update_libertine_container(self, new_locale=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with ContainerRunning(self.container): <NEW_LINE> <INDENT> self.containers_config.update_container_install_status(self.container_id, "updating") <NEW_LINE> return self.container.update_packages(new_locale) <NEW_LINE> <DE... | Updates the contents of the container. | 625941c682261d6c526ab4ba |
def run(self, until, graphs=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.stats.new_batch() <NEW_LINE> self.env.run(until=until) <NEW_LINE> self.info(until, graphs) <NEW_LINE> self.close_log_file() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print('An error occured during the simulation.') <NEW_LINE> rai... | Lancia una simulazione, chiamando il metodo "run" dell'ambiente di test simpy | 625941c607f4c71912b1149e |
def checkio(N): <NEW_LINE> <INDENT> res = [] <NEW_LINE> answer = "" <NEW_LINE> return base(N, res, answer) | clear res, answer values
| 625941c6796e427e537b05e1 |
def remove_person(self, handle, transaction): <NEW_LINE> <INDENT> raise NotImplementedError | Remove the Person specified by the database handle from the database,
preserving the change in the passed transaction.
This method must be overridden in the derived class. | 625941c656b00c62f0f14675 |
def longestPalindrome(self, s): <NEW_LINE> <INDENT> result = '' <NEW_LINE> for i in range(len(s)): <NEW_LINE> <INDENT> odd = self.getPalindrome(i, i, s) <NEW_LINE> if len(result) < len(odd): <NEW_LINE> <INDENT> result = odd <NEW_LINE> <DEDENT> even = self.getPalindrome(i, i + 1, s) <NEW_LINE> if len(result) < len(even)... | :type s: str
:rtype: str | 625941c667a9b606de4a7ed7 |
def list_opts(): <NEW_LINE> <INDENT> return [(g.name, o) for g, o in _opts] | Return a list of oslo.config options available.
The purpose of this is to allow tools like the Oslo sample config file
generator to discover the options exposed to users. | 625941c685dfad0860c3ae77 |
def __init__(self, section): <NEW_LINE> <INDENT> umap_prop = uMapProperties(name=StoneWallFeature.name,color=StoneWallFeature.color,weight=StoneWallFeature.weight) <NEW_LINE> super().__init__(section, umap_prop) | Parameters
----------
section : 開始地点、終了地点の時間、緯度、経度 | 625941c6090684286d50ed01 |
def client_id(self): <NEW_LINE> <INDENT> return get_client_id() | Returns the client id (string) of this client.
| 625941c6796e427e537b05e2 |
def test_legalPlay_2(): <NEW_LINE> <INDENT> player_1 = SPlayer(color = 'blue', position = Position(0, 1), player = MPlayer(name = 'Michael')) <NEW_LINE> board = Board([player_1]) <NEW_LINE> player_1.tiles_owned = [Tile(3, [[0, 1], [2, 3], [4, 5], [6, 7]]), Tile(3, [[0, 1], [2, 3], [4, 5], [6, 7]]), Tile(3, [[0, 1], [2,... | if all moves are elimination moves, allows player to play current tile | 625941c62c8b7c6e89b357de |
def stop(self): <NEW_LINE> <INDENT> LOGGER.debug("Stopping SamsungTVWSBridge") <NEW_LINE> self.close_remote() | Stop Bridge. | 625941c6fff4ab517eb2f458 |
def alien_spawn(self, aliens, alien_imgs): <NEW_LINE> <INDENT> x = random.randrange(20 + self.alien_side, 780 - self.alien_side) <NEW_LINE> y = -35 <NEW_LINE> img = random.randrange(0, 3) <NEW_LINE> img = alien_imgs[img] <NEW_LINE> aliens.append([img, [x, y]]) <NEW_LINE> return aliens | displays the background, player, asteroids and other updates
:param spaceship: Img of spaceship
:param player_pos: Int of player position
:return List: aliens | 625941c667a9b606de4a7ed8 |
def has_previous(self): <NEW_LINE> <INDENT> return True | Not implemented | 625941c6de87d2750b85fdae |
def chainRequest(method, *args): <NEW_LINE> <INDENT> def decorator(responseHandler): <NEW_LINE> <INDENT> def handlerWrapper(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> responseHandler(self, data) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> printException() <NEW_LINE> <DEDENT> self.nextChainedRequest()... | Decorator to register an API request in the chain. Parameters are the
API method name and optional arguments. The decorated function is the slot
that handles the reply. | 625941c6379a373c97cfab61 |
def refresh_token(self, token_url='oauth2/v3/token', **kwargs): <NEW_LINE> <INDENT> if not self.authorized and not kwargs.get('refresh_token'): <NEW_LINE> <INDENT> raise ValueError('`refresh_token` is not set') <NEW_LINE> <DEDENT> token_url = urljoin(self.sso_base_url, token_url) <NEW_LINE> kwargs.setdefault('verify', ... | Overriddes base method to refresh Tesla's SSO token. Raises
ValueError and ServerError.
token_url (optional): The token endpoint.
Extra keyword arguments to pass to base method using `kwargs`:
refresh_token (optional): The refresh_token to use.
Return type: dict | 625941c6d7e4931a7ee9df3a |
@jit <NEW_LINE> def wf(n, l, nmax, step=0.005, rmin=0.65): <NEW_LINE> <INDENT> W1 = -0.5 * n**-2.0 <NEW_LINE> W2 = (l + 0.5)**2.0 <NEW_LINE> rmax = 2 * nmax * (nmax + 15) <NEW_LINE> r_in = n**2.0 - n * (n**2.0 - l*(l + 1.0))**0.5 <NEW_LINE> step_sq = step**2.0 <NEW_LINE> if n == nmax: <NEW_LINE> <INDENT> i = 0 <NEW_LIN... | Use the Numerov method to find the wavefunction for state n*, l, where
n* = n - delta.
nmax ensures that wavefunctions from different values of n can be aligned. | 625941c6cdde0d52a9e5304f |
def get_gcrs(self, t, group, ephem=None): <NEW_LINE> <INDENT> if group is None: <NEW_LINE> <INDENT> raise ValueError("TOA group table needed for SpacecraftObs get_gcrs") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> x = np.array([flags["telx"] for flags in group["flags"]]) <NEW_LINE> y = np.array([flags["tely"] for flag... | Return spacecraft GCRS position; this assumes position flags in tim file are in km | 625941c6e1aae11d1e749cd3 |
def add_nexusport_binding(port_id, vlan_id, vni, switch_ip, instance_id, is_native=False, ch_grp=0): <NEW_LINE> <INDENT> LOG.debug("add_nexusport_binding() called") <NEW_LINE> session = bc.get_writer_session() <NEW_LINE> binding = nexus_models_v2.NexusPortBinding(port_id=port_id, vlan_id=vlan_id, vni=vni, switch_ip=swi... | Adds a nexusport binding. | 625941c676d4e153a657eb4d |
def learn(self, obs, act, reward): <NEW_LINE> <INDENT> act = np.expand_dims(act, axis=-1) <NEW_LINE> reward = np.expand_dims(reward, axis=-1) <NEW_LINE> obs = paddle.to_tensor(obs, dtype='float32') <NEW_LINE> act = paddle.to_tensor(act, dtype='int32') <NEW_LINE> reward = paddle.to_tensor(reward, dtype='float32') <NEW_L... | 根据训练数据更新一次模型参数
| 625941c6627d3e7fe0d68e6c |
def remove_plugin(self, plugin_instance): <NEW_LINE> <INDENT> plugin_name = type(plugin_instance).__name__ <NEW_LINE> if plugin_instance not in self.get_plugins(): <NEW_LINE> <INDENT> self._logger.warning(f'plugin {plugin_name} not registered, skipping...') <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT>... | unload and remove plugin_instance bot plugin | 625941c6d8ef3951e324355a |
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> common.config.add_argument(parser) <NEW_LINE> args = parser.parse_args() <NEW_LINE> account_id = args.config.active_account <NEW_LINE> api = args.config.create_context() <NEW_LINE> response = api.account.summary(account_id) <NEW_LINE> account... | Create an API context, and use it to fetch and display an Account summary.
The configuration for the context and Account to fetch is parsed from the
config file provided as an argument. | 625941c6c4546d3d9de72a50 |
def pad_msg16(msg): <NEW_LINE> <INDENT> segs = len(msg) // 16 <NEW_LINE> if len(msg) % 16 != 0: <NEW_LINE> <INDENT> segs += 1 <NEW_LINE> <DEDENT> return msg.ljust(segs * 16) | Pad message with space to the nearest length of multiple of 16.
Parameters
----------
msg : bytes
The original message.
Returns
-------
bytes
Padded message to the nearest length of multiple of 16. | 625941c63cc13d1c6d3c7398 |
def sendline(command, method='cli_show_ascii'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if CONNECTION == 'ssh': <NEW_LINE> <INDENT> result = _sendline_ssh(command) <NEW_LINE> <DEDENT> elif CONNECTION == 'nxapi': <NEW_LINE> <INDENT> result = _nxapi_request(command, method) <NEW_LINE> <DEDENT> <DEDENT> except (Termi... | Send arbitrary show or config commands to the NX-OS device.
command
The command to be sent.
method:
``cli_show_ascii``: Return raw test or unstructured output.
``cli_show``: Return structured output.
``cli_conf``: Send configuration commands to the device.
Defaults to ``cli_show_ascii``.
NOTE... | 625941c6656771135c3eb88a |
def p_nphrase_attphrase_vphrase(p): <NEW_LINE> <INDENT> p[0] = ['nphrase',p[1][1],p[1][2]*p[3][2]] | nphrase : attphrase SYN_ATT vphrase | 625941c62eb69b55b151c8ca |
def __init__(self, base_ring, name=None, element_class=None, implementation=None, category=None): <NEW_LINE> <INDENT> if element_class is None: <NEW_LINE> <INDENT> implementation = self._implementation_names(implementation, base_ring)[0] <NEW_LINE> if implementation == "FLINT": <NEW_LINE> <INDENT> from .polynomial_zmod... | TESTS::
sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_dense_mod_n as PRing
sage: R = PRing(Zmod(15), 'x'); R
Univariate Polynomial Ring in x over Ring of integers modulo 15
sage: type(R.gen())
<class 'sage.rings.polynomial.polynomial_zmod_flint.Polynomial_zmod_flint'>
... | 625941c6d4950a0f3b08c36d |
def attributes(self): <NEW_LINE> <INDENT> return { 'id': self.id, 'errors': self.errors, 'category_id': self.category_id, 'created_by': self.created_by, 'created_date': self.created_date, 'description': self.description, 'title': self.title, 'updated_date': self.updated_date } | serialized attributes that can be used for json requests | 625941c67d847024c06be2d7 |
def _buildMapping(self): <NEW_LINE> <INDENT> mapping = dict() <NEW_LINE> for lett, digit in zip(self._letters, self._digits): <NEW_LINE> <INDENT> mapping[lett] = digit <NEW_LINE> <DEDENT> return mapping | Build the letter-digit mapping. | 625941c650812a4eaa59c340 |
def is_space(s): <NEW_LINE> <INDENT> return s.isspace() | function to check if a line
is only white spaces | 625941c6236d856c2ad447f6 |
def __init__(self, bin_number=None, card_alias=None, card_association=None, card_bank_code=None, card_bank_name=None, card_family=None, card_token=None, card_user_key=None, cart_type=None, id=None): <NEW_LINE> <INDENT> self._bin_number = None <NEW_LINE> self._card_alias = None <NEW_LINE> self._card_association = None <... | SavedCard - a model defined in Swagger | 625941c61f037a2d8b94621b |
@login_required <NEW_LINE> def edit_entry(request,entry_id): <NEW_LINE> <INDENT> entry = Entry.objects.get(id=entry_id) <NEW_LINE> topic = entry.topic <NEW_LINE> if topic.owner != request.user: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> if request.method != 'POST': <NEW_LINE> <INDENT> form = EntryForm(instan... | 编辑既有的条目 | 625941c6ac7a0e7691ed40ec |
def laceStringsRecur(s1, s2): <NEW_LINE> <INDENT> def helpLaceStrings(s1, s2, out): <NEW_LINE> <INDENT> if s1 == '': <NEW_LINE> <INDENT> return out+s2 <NEW_LINE> <DEDENT> if s2 == '': <NEW_LINE> <INDENT> return out+s1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return helpLaceStrings(s1[1:], s2[1:], out+s1[0]+s2[0]) ... | s1 and s2 are strings.
Returns a new str with elements of s1 and s2 interlaced,
beginning with s1. If strings are not of same length,
then the extra elements should appear at the end. | 625941c63539df3088e2e368 |
def pack_to(self, writer): <NEW_LINE> <INDENT> writer.write(int(self._enable), 'b') | Writes the current SetHeadlight to the given BinaryWriter. | 625941c6cad5886f8bd26ff7 |
def get_task_stderr(self): <NEW_LINE> <INDENT> stderr_path = os.path.join(self.wd, ".command.err") <NEW_LINE> with open(stderr_path, "r") as f: <NEW_LINE> <INDENT> return f.read() | Get command stderr. | 625941c6004d5f362079a351 |
def light_2d(self, R, kwargs_list): <NEW_LINE> <INDENT> kwargs_list_copy = copy.deepcopy(kwargs_list) <NEW_LINE> kwargs_list_new = [] <NEW_LINE> for kwargs in kwargs_list_copy: <NEW_LINE> <INDENT> if 'q' in kwargs: <NEW_LINE> <INDENT> kwargs['q'] = 1. <NEW_LINE> <DEDENT> kwargs_list_new.append({k: v for k, v in kwargs.... | :param R:
:param kwargs_list:
:return: | 625941c6fb3f5b602dac36af |
def __init__(self, lang = "en", log = "battle.log"): <NEW_LINE> <INDENT> self.attacklog = log <NEW_LINE> self.lang = lang <NEW_LINE> self.battle = {"initiative": [], "charparty": [], "enemies": []} | Constructor
@param lang chosen Language
@param log name an path of the file where to log the battle | 625941c630dc7b7665901985 |
def greater_than(column: Union[field.Field, str], value: Any) -> ComparisonCondition: <NEW_LINE> <INDENT> return ComparisonCondition('>', column, value) | Condition where the specified column is greater than the given value.
Args:
column: Name of the column on the origin model or the Field on the origin
model class to compare from
value: The value to compare against
Returns:
A Condition subclass that will be used in the query | 625941c62ae34c7f2600d14f |
def parserows(self, pos): <NEW_LINE> <INDENT> for row in self.iteraterows(pos): <NEW_LINE> <INDENT> row.parsebit(pos) <NEW_LINE> self.add(row) | Parse all rows, finish when no more row ends | 625941c63c8af77a43ae37bc |
def get_cols(blocks,first_word,last_word): <NEW_LINE> <INDENT> cols=[] <NEW_LINE> temp=[] <NEW_LINE> text_first_word='' <NEW_LINE> indx_a=0 <NEW_LINE> foundIt=False <NEW_LINE> while indx_a< np.shape(blocks)[0] and not(foundIt): <NEW_LINE> <INDENT> b=blocks[indx_a] <NEW_LINE> for l in b['lines']: <NEW_LINE> <INDENT> for... | return the columns | 625941c6dc8b845886cb5552 |
def target_type(self): <NEW_LINE> <INDENT> return self._target_type() if self.quantizer is None else self.quantizer.target_type() | Returns the type of data of the target | 625941c6099cdd3c635f0c79 |
def delete_message(message_id): <NEW_LINE> <INDENT> pass | Remove the given message from the store.
If the referenced message is missing from the message store, the
operation is ignored.
:param message: The Message-ID of the message to delete from the store. | 625941c624f1403a92600b85 |
def assignVarOccursInG1(varName, info): <NEW_LINE> <INDENT> if varName.find(LIST_INDEX_SYMBOL) != -1: <NEW_LINE> <INDENT> varNameStrip = varName.split(LIST_INDEX_SYMBOL)[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> varNameStrip = None <NEW_LINE> <DEDENT> if varName in info['G1']: <NEW_LINE> <INDENT> return True <NE... | determines if varName occurs in the 'G1' set. For varName's that have a '#' indicator, we first split it
then see if arg[0] is in the 'G1' set. | 625941c6cb5e8a47e48b7ac9 |
def __len__(self): <NEW_LINE> <INDENT> return len(self._metrics) | Returns the numbers of hyperparametrics
| 625941c67b180e01f3dc481e |
def setUp(self): <NEW_LINE> <INDENT> super(TestSubUnneeded, self).setUp() <NEW_LINE> self.collection.register(SubUnneeded()) <NEW_LINE> self.success_templates = [ 'fixtures/templates/good/functions_sub.yaml', ] | Setup | 625941c6460517430c3941a6 |
def parse_args(description): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser( description=description, formatter_class=argparse.RawTextHelpFormatter) <NEW_LINE> group = parser.add_mutually_exclusive_group(required=True) <NEW_LINE> group.add_argument('--server', action='store_true') <NEW_LINE> group.add_argument('-... | Parse arguments. | 625941c67b25080760e39477 |
def make_safe_request(self, method): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return method() <NEW_LINE> <DEDENT> except (requests.exceptions.ConnectionError, requests.exceptions.Timeout, requests.exceptions.HTTPError, ValueError, socket.timeout): <NEW_LINE> <INDENT> return None | Make get request to specified url
in case of errors returns None and doesn't
raise exceptions
:param method: callable object
:returns: result of method call | 625941c6dd821e528d63b1c7 |
def similarity(self,word1,word2): <NEW_LINE> <INDENT> weights1 = self.vocab_dict[word1] <NEW_LINE> weights2 = self.vocab_dict[word2] <NEW_LINE> cos_sim = np.dot(weights1, weights2)/(np.linalg.norm(weights1, 2)*np.linalg.norm(weights2, 2)) <NEW_LINE> return cos_sim | computes similiarity between the two words. unknown words are mapped to one common vector
:param word1:
:param word2:
:return: a float \in [0,1] indicating the similarity (the higher the more similar) | 625941c623e79379d52ee583 |
def submit_thread(func: Callable[[Any], Any], *args: Any, **kwargs: Any) -> Future: <NEW_LINE> <INDENT> return _EXECUTOR.submit(func, *args, **kwargs) | enviar discussão para pool de discussão | 625941c67c178a314d6ef47b |
def get_content_metadata_item_id(content_metadata_item): <NEW_LINE> <INDENT> if content_metadata_item['content_type'] == 'program': <NEW_LINE> <INDENT> return content_metadata_item['uuid'] <NEW_LINE> <DEDENT> return content_metadata_item['key'] | Return the unique identifier given a content metadata item dictionary. | 625941c6ec188e330fd5a7bf |
def begin_list_available_providers( self, resource_group_name, network_watcher_name, parameters, **kwargs ): <NEW_LINE> <INDENT> polling = kwargs.pop('polling', True) <NEW_LINE> cls = kwargs.pop('cls', None) <NEW_LINE> lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) <NEW_LINE> cont_token = k... | NOTE: This feature is currently in preview and still being tested for stability. Lists all
available internet service providers for a specified Azure region.
:param resource_group_name: The name of the network watcher resource group.
:type resource_group_name: str
:param network_watcher_name: The name of the network w... | 625941c6f9cc0f698b14061a |
def amin(a, axis=None, out=None, keepdims=np._NoValue): <NEW_LINE> <INDENT> kwargs = {} <NEW_LINE> if keepdims is not np._NoValue: <NEW_LINE> <INDENT> kwargs['keepdims'] = keepdims <NEW_LINE> <DEDENT> if type(a) is not mu.ndarray: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> amin = a.min <NEW_LINE> <DEDENT> except Attr... | Return the minimum of an array or minimum along an axis.
Parameters
----------
a : array_like
Input data.
axis : None or int or tuple of ints, optional
Axis or axes along which to operate. By default, flattened input is
used.
.. versionadded: 1.7.0
If this is a tuple of ints, the minimum is sele... | 625941c6fff4ab517eb2f459 |
def _verify_openstack_userdata(self, ssh, mount_path, userdata): <NEW_LINE> <INDENT> self._verify_config_drive_data( ssh, mount_path + "/openstack/latest/user_data", userdata, "userdata (Openstack)" ) | verify Userdata in Openstack format
:param ssh: SSH connection to the VM
:param mount_path: mount point of the config drive
:param userdata: Expected userdata
:type ssh: marvin.sshClient.SshClient
:type mount_path: str
:type userdata: str | 625941c6dd821e528d63b1c8 |
def __init__(self, data, y_keys=['z{0}'.format(i) for i in range(4, 12)], x_keys=['x', 'y'], **kwargs): <NEW_LINE> <INDENT> super(kNN_Interpolator, self).__init__(y_keys=y_keys, x_keys=x_keys, **kwargs) <NEW_LINE> from sklearn.neighbors import KNeighborsRegressor <NEW_LINE> knn_args = {'n_neighbors': 45, 'weights': 'un... | x_keys, y_keys : lists of strings
The keys which we want to use as input (x) and output (y). | 625941c626238365f5f0ee8a |
def generate_mask_sub_sentence(hparams, input_x_id, id_to_word): <NEW_LINE> <INDENT> p = np.full([FLAGS.batch_size, FLAGS.sequence_length], True, dtype=bool) <NEW_LINE> input_x = [' '.join([id_to_word[char_id] for char_id in input_x_id[batch]]) for batch in range(FLAGS.batch_size)] <NEW_LINE> eos_idx = [list(input_x_id... | mask a sub sentence | 625941c65f7d997b87174ab4 |
def bin_donors_by_giving_level(dataframe: pd.DataFrame): <NEW_LINE> <INDENT> bins = [0, 50, 100, 250, 500, 1000, 2500, np.inf] <NEW_LINE> labels = [ "<strong>Friend\n$1-$49</strong>", "<strong>Supporter\n$50-$99</strong>", "<strong>Patron\n$100-$249</strong>", "<strong>Champion Level\n$250-$499</strong>", "<strong>Amba... | Apply giving-level labels.
Args:
dataframe (:class:`DataFrame`): Summed donations for each donor.
Returns:
:class:`DataFrame`: Donations and their corresponding giving-level
labels, sorted first by giving level (descending) and second by
last name (ascending). | 625941c66fb2d068a760f0b9 |
def _parse_expr(self): <NEW_LINE> <INDENT> term = self._parse_term() <NEW_LINE> l = [] <NEW_LINE> while True: <NEW_LINE> <INDENT> add = self._match_op_add() <NEW_LINE> if add: <NEW_LINE> <INDENT> t = self._parse_term() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._unget() <NEW_LINE> break <NEW_LINE> <DEDENT> l.ap... | expression ::= term (addOp term)*
:return: | 625941c638b623060ff0ae0b |
def _abort_task(self, appname, exception): <NEW_LINE> <INDENT> if self.app_events_dir: <NEW_LINE> <INDENT> trace.post( self.app_events_dir, app_events.AbortedTraceEvent( instanceid=appname, why=app_abort.AbortedReason.SCHEDULER.value, payload=exception ) ) | Set task into aborted state in case of scheduling error. | 625941c65e10d32532c5ef45 |
def add_instance(bandwidth, node_list, instance_registry, instance_num, request, request_placement, nf_index): <NEW_LINE> <INDENT> vector = get_placement_vector(request, request_placement) <NEW_LINE> pre_nodes = vector[nf_index] <NEW_LINE> post_nodes = vector[nf_index + 2] <NEW_LINE> candidate_nodes_distance = [[i, 0] ... | 为指定nf增加一个实例 | 625941c6eab8aa0e5d26db75 |
def miner_history(self, miner: str) -> dict: <NEW_LINE> <INDENT> endpoint = "miner/%s/history" % miner <NEW_LINE> return self._get_data(endpoint) | Get miner history. | 625941c67d847024c06be2d8 |
def set_learn_range(self, start_position, end_position): <NEW_LINE> <INDENT> self._set_data_range('learning', start_position, end_position) | This function sets the range within the data that is to used for
learning. | 625941c673bcbd0ca4b2c094 |
def countdown(t): <NEW_LINE> <INDENT> while t: <NEW_LINE> <INDENT> mins, secs = divmod(t, 60) <NEW_LINE> timeformat = '{:02d}:{:02d}'.format(mins, secs) <NEW_LINE> print(timeformat, end='\r') <NEW_LINE> time.sleep(1) <NEW_LINE> t -= 1 <NEW_LINE> <DEDENT> print('Next!\n\n') | Takes the time a creates a countdown. | 625941c6711fe17d8254238c |
def restart(self, suite_name=None, host=None, args=None): <NEW_LINE> <INDENT> self.suite_engine_proc.check_global_conf_compat() <NEW_LINE> if not suite_name: <NEW_LINE> <INDENT> suite_name = get_suite_name(self.event_handler) <NEW_LINE> <DEDENT> suite_dir = self.suite_engine_proc.get_suite_dir(suite_name) <NEW_LINE> if... | Restart a "cylc" suite. | 625941c6baa26c4b54cb113e |
def main(): <NEW_LINE> <INDENT> from src.gui.utils.qthelpers import qapplication <NEW_LINE> app = qapplication() <NEW_LINE> widget = PydocBrowser(None) <NEW_LINE> widget.show() <NEW_LINE> widget.initialize() <NEW_LINE> sys.exit(app.exec_()) | Run web browser | 625941c6a17c0f6771cbe06f |
def getVarsAndBounds(self, x, lb, ub): <NEW_LINE> <INDENT> lb[:] = self.blx <NEW_LINE> ub[:] = self.bux <NEW_LINE> x[:] = self.xs <NEW_LINE> return | Get the variable values and bounds | 625941c6d6c5a10208144068 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.