code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def memoize(fn: Callable) -> Callable: <NEW_LINE> <INDENT> attr_name = "_{}".format(fn.__name__) <NEW_LINE> @wraps(fn) <NEW_LINE> def memoized(self): <NEW_LINE> <INDENT> if not hasattr(self, attr_name): <NEW_LINE> <INDENT> setattr(self, attr_name, fn(self)) <NEW_LINE> <DEDENT> return getattr(self, attr_name) <NEW_LINE>... | Decorator to memoize a method.
Example
-------
class MyClass:
@memoize
def a_method(self):
print("a_method called")
return 42
>>> my_object = MyClass()
>>> my_object.a_method
a_method called
42
>>> my_object.a_method
42 | 625941ec925a0f43d254a37d |
def getparams(expression): <NEW_LINE> <INDENT> atoms = set([]) <NEW_LINE> expression = np.array(expression) <NEW_LINE> if expression.shape == (): <NEW_LINE> <INDENT> expression = expression.reshape((1,)) <NEW_LINE> <DEDENT> if expression.ndim > 1: <NEW_LINE> <INDENT> expression = expression.reshape((np.product(expressi... | Return the parameters of an expression that are not Term
instances but are instances of sympy.Symbol.
Examples
--------
>>> x, y, z = [Term(l) for l in 'xyz']
>>> f = Formula([x,y,z])
>>> getparams(f)
[]
>>> f.mean
_b0*x + _b1*y + _b2*z
>>> getparams(f.mean)
[_b0, _b1, _b2]
>>>
>>> th = sympy.Symbol(... | 625941ecd6c5a10208144550 |
def _validate_poolname(poolname): <NEW_LINE> <INDENT> r = re.match('^'+_FS_COMP+'$', poolname) <NEW_LINE> if r == None: <NEW_LINE> <INDENT> raise ZfsBadFsName(poolname) | Verify that the given poolname is a valid ZFS Zpool name
Raises a ZfsBadFsName if it's invalid | 625941ecd8ef3951e3243a3f |
def testUnpackedHashAppId(self): <NEW_LINE> <INDENT> unpacked_test_manifest_path = os.path.join( self.CRX_ID_DIR, '..', '..', 'chrome', 'test', 'data', 'extensions', 'unpacked', 'manifest_with_key.json') <NEW_LINE> temp_unpacked_crx = tempfile.mkdtemp() <NEW_LINE> shutil.copy2(unpacked_test_manifest_path, os.path.join(... | Test the output generated for a canned, unpacked extension. | 625941ec097d151d1a223358 |
def str2int(inp): <NEW_LINE> <INDENT> if inp.strip() == '': <NEW_LINE> <INDENT> return np.nan <NEW_LINE> <DEDENT> return int(inp) | Convert a set number of columns to integer, or returns None.
Parameters
----------
inp : str
string with a list of floats in it
Returns
-------
output : float
all columns returned as integers | 625941ec60cbc95b062c6a45 |
def write(self, data): <NEW_LINE> <INDENT> with self.cv: <NEW_LINE> <INDENT> if self.closed: <NEW_LINE> <INDENT> raise RuntimeError('closed') <NEW_LINE> <DEDENT> self.buf.append(data) <NEW_LINE> if len(self.buf) == 1: <NEW_LINE> <INDENT> self.cv.notify() | Writes data, called by the Response stream. | 625941ec50812a4eaa59c81e |
def get_regnet(channels_init, channels_slope, channels_mult, depth, groups, use_se=False, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): <NEW_LINE> <INDENT> divisor = 8 <NEW_LINE> assert (channels_slope >= 0) and (channels_init > 0) and (channels_mult > 1) and (channels_i... | Create RegNet model with specific parameters.
Parameters:
----------
channels_init : float
Initial value for channels/widths.
channels_slope : float
Slope value for channels/widths.
width_mult : float
Width multiplier value.
groups : int
Number of groups.
depth : int
Depth value.
use_se : bool, def... | 625941ec6fece00bbac2dc46 |
def get_link(self): <NEW_LINE> <INDENT> selector = self.selector <NEW_LINE> try: <NEW_LINE> <INDENT> component = self.resource.components[selector] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise SyntaxError("Undefined component: %s" % selector) <NEW_LINE> <DEDENT> link = component.link <NEW_LINE> if not... | Find the target component and its linktable
Returns:
tuple of S3Resource instances (component, link) | 625941ec5fcc89381b1e1bc4 |
def acquireSnap(self, n_mean): <NEW_LINE> <INDENT> snap = self._control.acquireSnap(n_mean) <NEW_LINE> self.displayImage(snap) <NEW_LINE> return snap | acquire a snapshot, ragardless of whether a pattern is applied or not | 625941ec4a966d76dd551516 |
def get_nodes_node_firmware_status_with_http_info(self, lnn, **kwargs): <NEW_LINE> <INDENT> all_params = ['lnn', 'devices', 'package'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_... | get_nodes_node_firmware_status # noqa: E501
The firmware status for the node. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_nodes_node_firmware_status_with_http_info(lnn, async_req=True)
>>> result = thread.... | 625941ec07f4c71912b11986 |
def validarEncGra(num): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if isinstance(num,float): <NEW_LINE> <INDENT> return "Debe indicar un número entero." <NEW_LINE> <DEDENT> assert 0 < num <NEW_LINE> num = int(num) <NEW_LINE> return "El más grande es: "+str(encontrarGran(num)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <I... | Entrada: num, numero a validar
Funcionalidad: Validar num para encontrarGran
Salida: Mensaje de error o encontrarGran(num) | 625941ec21bff66bcd684e4f |
def _build_detailed_report(self, report_model_config): <NEW_LINE> <INDENT> detailed_report = ReportFactory.create_report() <NEW_LINE> report_key = report_model_config.model_config_name() <NEW_LINE> model_config, _ = self._detailed_report_data[report_key] <NEW_LINE> detailed_report.add_title(title="Detailed Report") <NE... | Builder method for a detailed report | 625941ec63d6d428bbe449f2 |
def __init__(self, suit, rank): <NEW_LINE> <INDENT> self.suit = suit <NEW_LINE> self.rank = rank <NEW_LINE> self.suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] <NEW_LINE> self.ranks = ['null', 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] | Card constructor method
:param suit: int -> 0 = hearts, 1 = diamonds, 2 = clubs, 3 = spades
:param rank: int -> number rank of card | 625941ec3617ad0b5ed683f8 |
def __init__(self, start, end, zfill=0, label=""): <NEW_LINE> <INDENT> BaseAttr.__init__(self, label) <NEW_LINE> self.start = start <NEW_LINE> self.end = end <NEW_LINE> self.zfill = zfill <NEW_LINE> self.byte_count = 0 <NEW_LINE> for i in range(self.start, self.end): <NEW_LINE> <INDENT> self.byte_count += len(str(i).zf... | start, end: integers as in Python's range()
zfill: pad with leading zeros to this length | 625941ec566aa707497f4a63 |
def encode(self, command, source, dest, pretend=False): <NEW_LINE> <INDENT> assert isinstance(command, bytes) <NEW_LINE> assert isinstance(source, bytes) <NEW_LINE> assert isinstance(dest, bytes) <NEW_LINE> quiet = self.config['quiet'].get(bool) <NEW_LINE> if not quiet and not pretend: <NEW_LINE> <INDENT> self._log.inf... | Encode `source` to `dest` using command template `command`.
Raises `subprocess.CalledProcessError` if the command exited with a
non-zero status code. | 625941ec187af65679ca5621 |
def __init__(self, tbl_mgr: TableMgr, tx: Transaction): <NEW_LINE> <INDENT> self._tbl_mgr = tbl_mgr <NEW_LINE> self._tablestats = {} <NEW_LINE> self._numcalls = 0 <NEW_LINE> self.__refresh_statistics(tx) | Creates the statistics manager.
The initial statistics are calculated by
traversing the entire database.
:param tbl_mgr:
:param tx: the startup transaction | 625941ec442bda511e8be912 |
def is_dict_var(string): <NEW_LINE> <INDENT> warnings.warn(is_dict_var.__doc__, UserWarning) <NEW_LINE> return is_dict_variable(string) | Deprecated since RF 3.2. Use ``is_dict_variable`` instead. | 625941ecec188e330fd5ac96 |
def findDiagonalOrder(self, matrix): <NEW_LINE> <INDENT> ans = [] <NEW_LINE> if len(matrix) == 0 or len(matrix[0]) == 0: <NEW_LINE> <INDENT> return ans <NEW_LINE> <DEDENT> m = len(matrix) <NEW_LINE> n = len(matrix[0]) <NEW_LINE> c, r = 0, 0 <NEW_LINE> for i in range(0, m*n): <NEW_LINE> <INDENT> ans.append(matrix[r][c])... | :type matrix: List[List[int]]
:rtype: List[int] | 625941ec2ae34c7f2600d632 |
def prettify_sequence(self, input_sequence, output_title): <NEW_LINE> <INDENT> if not self.regular_print: <NEW_LINE> <INDENT> if self.current_data_type != set: <NEW_LINE> <INDENT> iter_output = self.iterate_sequence(input_sequence) <NEW_LINE> full_output = iter_output.format(*[i+1 for i in range(iter_output.count("{}")... | Uses self.iterate_through_list to prettify a list.
:param input_sequence: the sequence to be prettified.
:type: list || tuple || set
:param output_title: the title that will be used for the output sequence.
:type: str
:return: if self.regular_print is True && self.return_string is True, return the pprint Printer out... | 625941ec15fb5d323cde1019 |
def get_action(self, observation, epsilon): <NEW_LINE> <INDENT> if random.random() < epsilon: <NEW_LINE> <INDENT> return self.env.action_space.sample() <NEW_LINE> <DEDENT> model_input = np.array([observation]) <NEW_LINE> predictions = self.model.predict(model_input) <NEW_LINE> q_values_for_this_observation = { i : pred... | Return the epsilon greedy action
Arguments:
observation -- Gym observation
epsilon -- Probability for taking a random action | 625941ec63f4b57ef000160c |
def time_stats(df): <NEW_LINE> <INDENT> print('\nCalculating The Most Frequent Times of Travel...\n') <NEW_LINE> start_time = time.time() <NEW_LINE> busiest_month = df['month'].mode()[0] <NEW_LINE> print('The busiest month is {}'.format(busiest_month)) <NEW_LINE> busiest_day = df['day_of_week'].mode()[0] <NEW_LINE> pri... | Displays statistics on the most frequent times of travel. | 625941ecdd821e528d63b6a7 |
def process_response(self, response: Response) -> None: <NEW_LINE> <INDENT> if response.status_code != 101: <NEW_LINE> <INDENT> raise InvalidStatusCode(response.status_code) <NEW_LINE> <DEDENT> headers = response.headers <NEW_LINE> connection: List[ConnectionOption] = sum( [parse_connection(value) for value in headers.... | Check a handshake response received from the server.
:param response: response
:param key: comes from :func:`build_request`
:raises ~websockets.exceptions.InvalidHandshake: if the handshake response
is invalid | 625941ec091ae35668667457 |
def calculate_acc(y_pred, y): <NEW_LINE> <INDENT> tp, fp, tn, fn = 0, 0, 0, 0 <NEW_LINE> for i in range(y_pred.shape[0]): <NEW_LINE> <INDENT> if y_pred[i] == 0: <NEW_LINE> <INDENT> if y[i] == 0: <NEW_LINE> <INDENT> tn += 1 <NEW_LINE> <DEDENT> else: fn += 1 <NEW_LINE> <DEDENT> elif y[i] == 0: <NEW_LINE> <INDENT> fp += 1... | Calculates the accuracy of predicted y vector | 625941ecbe8e80087fb2113c |
@pytest.mark.parametrize( 'params, arr_desired', [({'sample_range': (0, 1)}, [[0, 0.25, 0.5, 0.75, 1] for _ in range(2)]), ({'sample_range': (-1, 1)}, [[-1, -0.5, 0, 0.5, 1] for _ in range(2)]), ({'sample_range': (0, 4)}, [[0, 1, 2, 3, 4] for _ in range(2)]), ({'sample_range': (-10, 10)}, [[-10, -5, 0, 5, 10] for _ in ... | Test that the actual results are the expected ones. | 625941ec7d43ff24873a31a6 |
def get_currencies(self) -> dict: <NEW_LINE> <INDENT> return self.__currencies | :return: dict
:version 1.0.1
:revision 11.01.2021 | 625941eccc0a2c11143dd393 |
def sanitize(device): <NEW_LINE> <INDENT> if 'label' not in device.keys(): <NEW_LINE> <INDENT> device['label'] = 'unnammed device' <NEW_LINE> <DEDENT> if 'id' not in device.keys(): <NEW_LINE> <INDENT> raise ParseError("missing unique id") <NEW_LINE> <DEDENT> if 'protocol' not in device.keys(): <NEW_LINE> <INDENT> raise... | validates the given device, sanitizing any missing fields with their defaults | 625941ec26238365f5f0f377 |
def get_entity_ids(self, domain_filter=None): <NEW_LINE> <INDENT> _LOGGER.warning( "hass.get_entiy_ids is deprecated. Use hass.states.entity_ids") <NEW_LINE> return self.states.entity_ids(domain_filter) | Returns known entity ids.
THIS METHOD IS DEPRECATED. Use hass.states.entity_ids | 625941ec6e29344779a62b12 |
def clean_boxes_to_be_deleted(p_area, p_area_clean, p_bombs): <NEW_LINE> <INDENT> for bomb in bombs: <NEW_LINE> <INDENT> for pos in get_boxes_impacted_by_flame(p_area, bomb, bomb[3], True): <NEW_LINE> <INDENT> if p_area[pos[1]][pos[0]] in [MAP_BOX, MAP_EXTRA, MAP_RANGE]: <NEW_LINE> <INDENT> if bomb[2] == 0: <NEW_LINE> ... | Delete boxes that will be destroyed by the currently setted bombs
p_area: is the reference area (non modified)
p_area_clean: area without the destroyed boxes (modificed)
p_bombs: list of bombs to apply (non modified) | 625941ecd6c5a10208144551 |
def get_qam_module(self): <NEW_LINE> <INDENT> raise NotImplementedError | Get the module of the qam.
:raises Exception: Not implemented | 625941ec5e10d32532c5f427 |
def test_init_typeerror(self): <NEW_LINE> <INDENT> self.assertRaises(TypeError, Seq, ("A", "C", "G", "T")) <NEW_LINE> self.assertRaises(TypeError, Seq, ["A", "C", "G", "T"]) <NEW_LINE> self.assertRaises(TypeError, Seq, 1) <NEW_LINE> self.assertRaises(TypeError, Seq, 1.0) | Check Seq __init__ gives TypeError exceptions. | 625941ec8e7ae83300e4b4d0 |
@catch(AzkabanError) <NEW_LINE> def main(): <NEW_LINE> <INDENT> args = docopt(__doc__) <NEW_LINE> paths = args['PATH'] <NEW_LINE> session = Session(args['--url'], args['--alias']) <NEW_LINE> try: <NEW_LINE> <INDENT> job_options = dict(opt.split('=', 1) for opt in args['--option']) <NEW_LINE> <DEDENT> except ValueError:... | AzkabanPig entry point. | 625941ecb7558d58953c540b |
def get_active_max_frequency(self): <NEW_LINE> <INDENT> from user_profile.models import UserProfile <NEW_LINE> try: <NEW_LINE> <INDENT> obj_userprofile = UserProfile.objects.get(user=self.user) <NEW_LINE> <DEDENT> except UserProfile.DoesNotExist: <NEW_LINE> <INDENT> return self.frequency <NEW_LINE> <DEDENT> max_frequen... | Get the active max frequency | 625941ec4e696a04525c994f |
def _load_remotes(self): <NEW_LINE> <INDENT> for remote in self._config.subsections('remote'): <NEW_LINE> <INDENT> name, class_ = remote.get('method') <NEW_LINE> self._remotes[remote.args] = class_(remote.args, class_.config_schema.validate(remote)) | Load remotes from configuration.
This method do the following things::
- List remotes from configuration file
- Validate remote specific configuration according to remote method chosen
- Instanciate the remote method class for the remote | 625941ec0fa83653e46574ba |
def __set_params(self, params_to_update, check_mode=True): <NEW_LINE> <INDENT> query = 'ALTER SUBSCRIPTION %s SET (%s)' % (self.name, ', '.join(params_to_update)) <NEW_LINE> return self.__exec_sql(query, check_mode=check_mode) | Update optional subscription parameters.
Args:
params_to_update (list): Parameters with values to update.
Kwargs:
check_mode (bool): If True, don't actually change anything,
just make SQL, add it to ``self.executed_queries`` and return True.
Returns:
True if successful, False otherwise. | 625941ecff9c53063f47c6f3 |
def invert(self, DEM=(1, 1, 1), dt=1, t0=0, TOL=np.exp(-4), msg=True): <NEW_LINE> <INDENT> maxD, maxE, maxM = DEM <NEW_LINE> nE, nD, nM = 0, 0, 0 <NEW_LINE> EOX = self.hdm.EMBED_ORDER_X <NEW_LINE> for nE in range(maxE): <NEW_LINE> <INDENT> self._reset_integrals_() <NEW_LINE> for t in range(self.tY): <NEW_LINE> <INDENT>... | Model inversion. | 625941ec07f4c71912b11987 |
def __init__(self, stream, db, max_len=None): <NEW_LINE> <INDENT> self.db = db <NEW_LINE> self.stream = self.db.Stream(stream) <NEW_LINE> self.max_len = max_len | An event producer
:param stream: Stream name
:param db: Walrus db object | 625941ec8c3a8732951588c3 |
def safe_random_choice(input_data, size): <NEW_LINE> <INDENT> replace = len(input_data) < size <NEW_LINE> return NUMPY_RANDOM_STATE.choice(input_data, size=size, replace=replace) | Randomly samples without replacement from a sequence. It is "safe" because
if len(input_data) < size, it will randomly sample WITH replacement
Args:
input_data is a sequence, like a torch tensor, numpy array,
python list, tuple etc
size is the number of elements to randomly sample from input... | 625941ec7d847024c06be7c2 |
def present(name, profile="splunk", **kwargs): <NEW_LINE> <INDENT> ret = {"name": name, "changes": {}, "result": None, "comment": ""} <NEW_LINE> target = __salt__["splunk_search.get"](name, profile=profile) <NEW_LINE> if target: <NEW_LINE> <INDENT> if __opts__["test"]: <NEW_LINE> <INDENT> ret["comment"] = "Would update... | Ensure a search is present
.. code-block:: yaml
API Error Search:
splunk_search.present:
search: index=main sourcetype=blah
template: alert_5min
The following parameters are required:
name
This is the name of the search in splunk | 625941ec91f36d47f21ac9fa |
def get_object_by_id(self, object_class, object_id): <NEW_LINE> <INDENT> if isinstance(object_id, object_class): <NEW_LINE> <INDENT> object_id = object_id.id <NEW_LINE> <DEDENT> object_cache = self.caches.get(object_class, None) <NEW_LINE> if object_cache is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return... | This method will first check the cache to see if there is already an
instance with that ID, in which case we don't need to perform any SQL
select. If it is not in the cache, then a new instance is created,
cached, and returned. | 625941ece5267d203edce198 |
def post(self, request, pet_id): <NEW_LINE> <INDENT> return JsonResponse({}) | tags:
- pet
summary: uploads an image
description: ''
operationId: uploadFile
parameters:
- name: additionalMetadata
in: query
description: Additional Metadata
required: false
schema:
type: string
requestBody:
content:
application/octet-stream:
schema:
type: string
... | 625941ec57b8e32f524839a0 |
def abrirJanelaSelecao(self): <NEW_LINE> <INDENT> self.janelaSelecao = JanelaSelecao(self) | Inicializa a janela de seleção | 625941ec50485f2cf553d29e |
def psychopos2pos(pos, dispsize=None): <NEW_LINE> <INDENT> if dispsize is None: <NEW_LINE> <INDENT> dispsize = settings.DISPSIZE[:] <NEW_LINE> <DEDENT> x = pos[0] + dispsize[0]/2 <NEW_LINE> y = (pos[1] * -1) + dispsize[1]/2 <NEW_LINE> return (x,y) | Returns a converted position tuple (x,y) (internal use)
arguments
pos -- a (x,y) tuple that makes sense to PsychoPy (i.e. (0,0) is
display center; bottom left is (-,-) and top right is
(+,+))
keyword arguments
dispsize -- a (width, height) tuple for the display resolution or None
... | 625941ec56ac1b37e62646c7 |
def base_show_thread(request, forum, thread, page, template): <NEW_LINE> <INDENT> paginator = Paginator(thread.posts.valid(), config('thread', 'posts_per_page', int, 20)) <NEW_LINE> page_obj = paginator.page(page) <NEW_LINE> thread.view_count += 1 <NEW_LINE> thread.save() <NEW_LINE> data = { 'forum': forum, 'thread': t... | Does the work that allows users to view a thread | 625941ec3c8af77a43ae3ca9 |
def save_pickle(fname, *kargs): <NEW_LINE> <INDENT> with bz2.BZ2File(fname, 'wb') as f: <NEW_LINE> <INDENT> pickler = pickle.Pickler(f) <NEW_LINE> for item in kargs: <NEW_LINE> <INDENT> pickler.dump(item) | Method to save a variable number of objects into a pickled file. | 625941ec1f5feb6acb0c504c |
def butterworth_bandreject(distanceArray, radialCenter, bandwidth, order): <NEW_LINE> <INDENT> return 1/(1 + ((distanceArray*bandwidth) /((distanceArray**2)-radialCenter))**(2*order)) | Function for evaluating the butterworth bandreject filter | 625941ec566aa707497f4a64 |
def date_search(df, unix_ts_date): <NEW_LINE> <INDENT> filtered_df = df.loc[df['Ts'] >= unix_ts_date] <NEW_LINE> return filtered_df | !
Create a filtered DataFrame that only contains entries that occurred on or
past the specified date.
@param df DataFrame: contains the readings from the sensor
@param unix_ts_date Integer: the universal unix time of the starting date from
which to examine the data
@return Return a Datafr... | 625941ecd164cc6175783251 |
def staged_score(self, X, y, sample_weight=None): <NEW_LINE> <INDENT> for y_pred in self.staged_predict(X): <NEW_LINE> <INDENT> if isinstance(self, ClassifierMixin): <NEW_LINE> <INDENT> yield accuracy_score(y, y_pred, sample_weight=sample_weight) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield r2_score(y, y_pred, s... | Return staged scores for X, y.
This generator method yields the ensemble score after each iteration of
boosting and therefore allows monitoring, such as to determine the
score on a test set after each boost.
Parameters
----------
X : {array-like, sparse matrix} of shape = [n_samples, n_features]
The training inpu... | 625941ec956e5f7376d7136e |
def process_message(self, message): <NEW_LINE> <INDENT> if message.topic == "^org.chicago.cta.stations.": <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = json.loads(message.value()) <NEW_LINE> self._handle_station(value) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.fatal("bad station? %s, ... | Given a kafka message, extract data | 625941ecb545ff76a8914318 |
def train(model, train, dev, train_steps, lr, metaphor_weight, alpha, beta, **kwargs): <NEW_LINE> <INDENT> optimiser = AdamW(model.parameters(), lr=lr, eps=1e-8) <NEW_LINE> scheduler = get_cosine_schedule_with_warmup( optimiser, num_warmup_steps=int(train_steps * .1), num_training_steps=train_steps ) <NEW_LINE> train_i... | Train MetaphorModel on Metaphor data.
Args:
model (nn.Module): initialised model, untrained
train (DataLoader): object containing metaphor training data.
dev (DataLoader): object containing metaphor validation data.
train_steps (int): number of updates to train for
lr (float): learning rate for opt... | 625941ecbd1bec0571d90b31 |
def concat_same_type(self, to_concat): <NEW_LINE> <INDENT> values = self._holder._concat_same_type([blk.values for blk in to_concat]) <NEW_LINE> placement = self.mgr_locs if self.ndim == 2 else slice(len(values)) <NEW_LINE> return self.make_block_same_class(values, placement=placement) | Concatenate list of single blocks of the same type. | 625941ece5267d203edce199 |
def SGD(self, X, y, eta=0.5, max_iteration=5000, epsilon=0.001): <NEW_LINE> <INDENT> N, D = X.shape <NEW_LINE> X = np.column_stack((np.ones(N), X)) <NEW_LINE> self.w = np.zeros(D + 1) <NEW_LINE> for i in range(max_iteration): <NEW_LINE> <INDENT> n = np.random.choice(range(N)) <NEW_LINE> xn, yn = X[n], y[n] <NEW_LINE> a... | Logistic Regression - Stochastic Gradient Descent
a = Xw
f(x) = sigmoid(a).round()
l(xn)' = (f(xn) - yn) xn | 625941ecf8510a7c17cf9c02 |
def adjustscore(scores: np.array, method: Optional[str] = 'quantile', n_quantiles: Optional[int] = 10000, labels: Optional[np.array] = None) -> np.array: <NEW_LINE> <INDENT> scores = np.array(scores) <NEW_LINE> if labels: <NEW_LINE> <INDENT> labels = np.array(labels) <NEW_LINE> <DEDENT> if method == 'quantile': <NEW_LI... | Wrapper function to adjust scores
Parameters:
-----------
scores: np.array
The scores generated by a model.
method: str (Default: None)
The calibration algorithm:
- 'quantile' -- sklearn's quantile transform
- 'sig3iqr' -- sigmoid 3x sklearn's robust scaler with (25%,75%)
- 'platt' -- ... | 625941ec38b623060ff0b2ef |
def onSaveLocationChange(self): <NEW_LINE> <INDENT> entered_directory = self.lineEditDownloadLocation.text() <NEW_LINE> if not os.path.isdir(entered_directory): <NEW_LINE> <INDENT> self.lineEditDownloadLocation.setText("") <NEW_LINE> self.showPopUp("Directory is not valid. Please re select") <NEW_LINE> <DEDENT> else: <... | Get save location by user text input (manual location input)
| 625941ec44b2445a33932594 |
def EApplicationStatusNames_name(*args): <NEW_LINE> <INDENT> return _Client.EApplicationStatusNames_name(*args) | EApplicationStatusNames_name(int i) -> char | 625941ec4e4d5625662d48d3 |
def get_details(data): <NEW_LINE> <INDENT> details = [] <NEW_LINE> for item in data['response']['groups'][0]['items']: <NEW_LINE> <INDENT> details.append([item['venue']['categories'][0]['name'],item['venue']['rating'],item['venue']['price']['tier']]) <NEW_LINE> <DEDENT> return details | Return a list of lists containing the details of each location | 625941ec01c39578d7e7533e |
def topological_sort(graph): <NEW_LINE> <INDENT> if graph is None or len(graph.adj_list) == 0: <NEW_LINE> <INDENT> print('ERROR - No graph to sort.') <NEW_LINE> return None <NEW_LINE> <DEDENT> all_in_degrees = compute_indegree_every_vertex(graph) <NEW_LINE> sort_result = [] <NEW_LINE> q = [] <NEW_LINE> for i in range(l... | Topological Sort, based off professors implementation.
MUST BE A DIRECTED AND ACYCLIC GRAPH(no cycles)!
Returns a list of vertices that make a path from one X to vertex Y, with X always before Y in the list.
:param graph:
:return Sort Result: | 625941ecb57a9660fec33d8e |
def __init__(self, sib, values, is_list): <NEW_LINE> <INDENT> super(SIE_tuple, self).__init__(sib) <NEW_LINE> self._sie_values = values <NEW_LINE> self._sie_is_list = is_list | Initialize an instance of :class:`SIE_tuple`.
INPUT:
- ``sib`` -- a :class:`SageInputBuilder`
- ``values`` -- a list of :class:`SageInputExpression`s representing the
elements of this tuple
- ``is_list`` -- is True if this class represents a list, False for a
tuple
EXAMPLES::
sage: from sage.misc.sage_inp... | 625941ec3617ad0b5ed683f9 |
def get_bandwidth(width, threshold): <NEW_LINE> <INDENT> best = width <NEW_LINE> min_err = float("inf") <NEW_LINE> for rows_per_band in range(1, width + 1): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> num_bands = 1. / (threshold ** rows_per_band) <NEW_LINE> <DEDENT> except ZeroDivisionError: <NEW_LINE> <INDENT> return... | Approximates the bandwidth needed to achieve a threshold.
:param width: = bands * rows # = elements in signature
:param threshold: = (1/bands) ** (1/rows) where
:returns: number of rows per band
:rtype: int | 625941ec56b00c62f0f14b5f |
def sort_sentence(sentence): <NEW_LINE> <INDENT> words = break_words(sentence) <NEW_LINE> return sort_words(words) | take in a full sentnce and return the sorted words | 625941ec66656f66f7cbc6af |
def lower_ext(abspath): <NEW_LINE> <INDENT> fname, ext = os.path.splitext(abspath) <NEW_LINE> return fname + ext.lower() | Convert file extension to lowercase.
| 625941ecd10714528d6001ec |
def test_add_same_config(self): <NEW_LINE> <INDENT> c = config.Config(config_path=self.test_cleanrc_path) <NEW_LINE> path_list = c.list_glob_path() <NEW_LINE> self.assertEqual(path_list.count(self.initialPath), 1) <NEW_LINE> runner = CliRunner() <NEW_LINE> runner.invoke(cli.add, ['fuga', 'hoge'], env=self.env) <NEW_LIN... | Cannot add same path config to a cleanrc. | 625941ec30dc7b7665901e63 |
def buscar(self,boton): <NEW_LINE> <INDENT> idcliente = utils.combo_get_value(self.wids['cmbe_cliente']) <NEW_LINE> if idcliente == None: <NEW_LINE> <INDENT> if not self.inicio: <NEW_LINE> <INDENT> albaranes = pclases.AlbaranSalida.select(pclases.AlbaranSalida.q.fecha <= self.fin, orderBy = 'fecha') <NEW_LINE> <DEDENT>... | Dadas fecha de inicio y de fin, lista todos los albaranes
pendientes de facturar. | 625941ec10dbd63aa1bd30a5 |
def get_percentage(successes, nulls, fails): <NEW_LINE> <INDENT> if successes is None: <NEW_LINE> <INDENT> return None, None, None <NEW_LINE> <DEDENT> total = successes + fails + nulls <NEW_LINE> if not total: <NEW_LINE> <INDENT> return None, None, None <NEW_LINE> <DEDENT> success = round(100. * successes / total, 2) ... | Converts integers ``successes``, ``nulls`` and ``fails`` to percents. | 625941ec8a349b6b435e8675 |
def __init__(self): <NEW_LINE> <INDENT> Repetition = 100 <NEW_LINE> plus = 0 <NEW_LINE> self.DataSet = np.empty([Repetition*32,40,16]) <NEW_LINE> for D in range(Repetition): <NEW_LINE> <INDENT> for i in range(1,11): <NEW_LINE> <INDENT> FileName = str("D:\Tesis\Python\Liclipse\Tesis\TrackingKinect\DataBaseCreatorSecuenc... | Function that set up the Data set.
The original data is a 39*16 matrix, are added one raw to form a 40*16
matrix, to ease the manipulation of the networks. | 625941ec99fddb7c1c9de891 |
def __reduce__(self): <NEW_LINE> <INDENT> return reduce_load_Giac, tuple([]) | EXAMPLES::
sage: giac.__reduce__()
(<function reduce_load_Giac at 0x...>, ())
sage: f, args = _
sage: f(*args)
Giac | 625941ece64d504609d74d42 |
def command(self, name, description=''): <NEW_LINE> <INDENT> section = _CommandManager(name, description) <NEW_LINE> self._commands.add(name) <NEW_LINE> self._sections.append(section) <NEW_LINE> return section | Adds/returns a command instance to add to the config file | 625941ec94891a1f4081bfae |
def connect_JSON(config): <NEW_LINE> <INDENT> testnet = config.get('testnet', '0') <NEW_LINE> testnet = (int(testnet) > 0) <NEW_LINE> if not 'rpcport' in config: <NEW_LINE> <INDENT> config['rpcport'] = 19998 if testnet else 9998 <NEW_LINE> <DEDENT> connect = "http://%s:%s@127.0.0.1:%s"%(config['rpcuser'], config['rpcpa... | Connect to a MoonDEX JSON-RPC server | 625941ecb7558d58953c540c |
def test_create_draft_with_multiple_requests(self): <NEW_LINE> <INDENT> self.client.ajax_post( self.problem_update_url, data={'publish': 'make_public'} ) <NEW_LINE> self.verify_publish_state(self.problem_usage_key, PublishState.public) <NEW_LINE> self.client.ajax_post( self.problem_update_url, data={ 'publish': 'create... | Create a draft request returns already created version if it exists. | 625941ec596a897236089fbc |
def on_service_tick(self): <NEW_LINE> <INDENT> if not self.enabled or self.next_schedule is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self.next_schedule <= datetime.now() and self.is_idle(): <NEW_LINE> <INDENT> self.next_schedule = _compute_next_schedule() <NEW_LINE> if self.next_schedule >= datetime.now(... | Check if update is due and trigger it | 625941ec82261d6c526ab9aa |
def getFirstLine(self): <NEW_LINE> <INDENT> line = maxsize <NEW_LINE> if hasattr(self.ref, "leadingCMLComments"): <NEW_LINE> <INDENT> if self.ref.leadingCMLComments: <NEW_LINE> <INDENT> line = CMLVersion.getFirstLine(self.ref.leadingCMLComments) <NEW_LINE> <DEDENT> <DEDENT> if hasattr(self.ref, "leadingComment"): <NEW_... | Provides the first line | 625941eca219f33f34628e65 |
@spice_error_check <NEW_LINE> def ekssum(handle: int, segno: int) -> SpiceEKSegSum: <NEW_LINE> <INDENT> handle = ctypes.c_int(handle) <NEW_LINE> segno = ctypes.c_int(segno) <NEW_LINE> segsum = stypes.SpiceEKSegSum() <NEW_LINE> libspice.ekssum_c(handle, segno, ctypes.byref(segsum)) <NEW_LINE> return segsum | Return summary information for a specified segment in a specified EK.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekssum_c.html
:param handle: Handle of EK.
:param segno: Number of segment to be summarized.
:return: EK segment summary. | 625941ec507cdc57c63071ea |
def edge(matrix: list, side: str) -> str: <NEW_LINE> <INDENT> if side == 'n': <NEW_LINE> <INDENT> return matrix[0] <NEW_LINE> <DEDENT> if side == 's': <NEW_LINE> <INDENT> return matrix[-1] <NEW_LINE> <DEDENT> if side == 'e': <NEW_LINE> <INDENT> return ''.join(map(operator.itemgetter(-1), matrix)) <NEW_LINE> <DEDENT> re... | return a side of a matrix | 625941ec4527f215b584c955 |
def searchMatrix(self, matrix, target): <NEW_LINE> <INDENT> i, j = 0, len(matrix[0]) - 1 <NEW_LINE> while i < len(matrix) and j >= 0: <NEW_LINE> <INDENT> if matrix[i][j] == target: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif matrix[i][j] < target: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> <DEDENT> else: <NEW_L... | :type matrix: List[List[int]]
:type target: int
:rtype: bool | 625941ec16aa5153ce36297b |
def print_error(self, error): <NEW_LINE> <INDENT> print(colored(error.message, 'red'), file=self.stderr) <NEW_LINE> if error.stdout or error.stderr: <NEW_LINE> <INDENT> print(file=self.stderr) <NEW_LINE> print("Here's what git said:", file=self.stderr) <NEW_LINE> print(file=self.stderr) <NEW_LINE> if error.stdout: <NEW... | Print more information about an error.
:type error: GitError | 625941ec435de62698dfe150 |
def test_past_question(self): <NEW_LINE> <INDENT> q1 = create_question(question_text="Past question.", days=-30) <NEW_LINE> create_choice(question=q1, choice_text='Question 1?', votes=0) <NEW_LINE> response = self.client.get(reverse('polls:index')) <NEW_LINE> self.assertQuerysetEqual( response.context['latest_question_... | Questions with a pub_date in the past are displayed on the
index page. | 625941ec8c3a8732951588c4 |
def lines(self) -> Iterable[str]: <NEW_LINE> <INDENT> common_padding = " " * self.indent <NEW_LINE> if self.first_indent is None: <NEW_LINE> <INDENT> first_padding = common_padding <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> first_padding = " " * self.first_indent <NEW_LINE> <DEDENT> common_prefix = self.prefix or ""... | Iterate over lines of the block | 625941ec15baa723493c447d |
@pytest.fixture <NEW_LINE> def uids(): <NEW_LINE> <INDENT> return ['pederaas', 'martekir', 'larsh', 'hansta'] | A list of uids. | 625941ec30dc7b7665901e64 |
def get( self, resource_group_name, route_filter_name, expand=None, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_versio... | Gets the specified route filter.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param route_filter_name: The name of the route filter.
:type route_filter_name: str
:param expand: Expands referenced express route bgp peering resources.
:type expand: str
:keyword callable cls... | 625941ec29b78933be1e5ba9 |
def truncate_table(self): <NEW_LINE> <INDENT> with self.table.batch_write() as batch: <NEW_LINE> <INDENT> for item in self.table.scan(): <NEW_LINE> <INDENT> batch.delete_item(searchterm=item['searchterm']) | Delete whole table | 625941ec099cdd3c635f115c |
def __init__(self, parent=None): <NEW_LINE> <INDENT> super(DialogAltaSeccion, self).__init__(parent) <NEW_LINE> self.setupUi(self) <NEW_LINE> self.DIVISION = Division_Transporte() <NEW_LINE> self.tableWidgetEmpleadosAsignados.setEditTriggers(QtGui.QTableWidget.NoEditTriggers) <NEW_LINE> self.tableWidgetEmpleadosSinAsig... | Constructor | 625941ec377c676e912726aa |
def p_declaration_1(t): <NEW_LINE> <INDENT> pass | declaration : declaration_specifiers init_declarator_list SEMI | 625941ece76e3b2f99f3ad06 |
@app.route('/') <NEW_LINE> def home(): <NEW_LINE> <INDENT> return render_template('index.html') | This function just responds to the browser ULR
localhost:5000/
:return: the rendered template 'home.html' | 625941ecc4546d3d9de72f3c |
@timeit <NEW_LINE> def insert_new_class(tx_list): <NEW_LINE> <INDENT> test_new = sqlite3.connect('file:ledger_new_class?mode=memory', uri=True, timeout=1) <NEW_LINE> create(test_new, SQL_CREATE) <NEW_LINE> for tx in tx_list: <NEW_LINE> <INDENT> test_new.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?,?,?,?,?)... | Uses a call to a function helper | 625941ec99cbb53fe67930e8 |
def pause(self, *partitions): <NEW_LINE> <INDENT> for partition in partitions: <NEW_LINE> <INDENT> log.debug("Pausing partition %s", partition) <NEW_LINE> self._subscription.pause(partition) | Suspend fetching from the requested partitions.
Future calls to poll() will not return any records from these partitions
until they have been resumed using resume(). Note that this method does
not affect partition subscription. In particular, it does not cause a
group rebalance when automatic assignment is used.
Argu... | 625941ec956e5f7376d7136f |
def render_params(self, source, *args, **kwargs): <NEW_LINE> <INDENT> for idx, arg in enumerate(args[2:]): <NEW_LINE> <INDENT> if isinstance(arg, six.string_types): <NEW_LINE> <INDENT> args[idx] = self.render(arg, source=source) <NEW_LINE> <DEDENT> elif isinstance(arg, (list, tuple)): <NEW_LINE> <INDENT> dest = [] <NEW... | Render all the things!
Apply rendering to all the args and kwargs that were
provided to a task.
Need a better solution to this brute-force copy/paste job. | 625941ec6aa9bd52df0372ab |
@parametrized <NEW_LINE> def matcher(func, from_eft, from_basis, to_eft, to_basis): <NEW_LINE> <INDENT> Matcher(from_eft, from_basis, to_eft, to_basis, func) <NEW_LINE> return func | Decorator for matching functions.
Usage:
```python
@matcher('myEFT_from', 'myBasis_from', 'myEFT_to', 'myBasis_to')
def myFunction(wc_dict_from):
... # do something
return wc_dict_to
``` | 625941ecadb09d7d5db6cc90 |
def render_html(self): <NEW_LINE> <INDENT> collection_json = self.collection.convert_collection_to_json() <NEW_LINE> env = Environment(loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) <NEW_LINE> template = env.get_template('curved_links.html') <NEW_LINE> return template.render(collection_j... | Method to turn an OdooModelCollection into a HTML Page
:return: A string of HTML | 625941ec009cb60464c638b1 |
def _assert_xml_equal_ex(self,xml,ex): <NEW_LINE> <INDENT> ex_xml = self._open_ex(ex).read() <NEW_LINE> self._assert_xml_equal( xml, ex_xml ) | Compare XML supplied with XML from example file ex | 625941ec711fe17d82542863 |
def test_net(save_folder, net, detector, cuda, testset, transform, max_per_image=300, thresh=0.05): <NEW_LINE> <INDENT> num_images = len(testset) <NEW_LINE> num_images = len(testset) <NEW_LINE> num_classes = (21, 81)[testset.name == 'COCOval'] <NEW_LINE> all_boxes = [[[] for _ in range(num_images)] for _ in range(num_c... | Test a Fast R-CNN network on an image database. | 625941ec15fb5d323cde101b |
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, V1EphemeralVolumeSource): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | Returns true if both objects are not equal | 625941ecfbf16365ca6f66d2 |
def get_team_id(self): <NEW_LINE> <INDENT> return self.get_team_info()['id'] | :return The team ID for the Slack being accessed by this scraper. | 625941ec99fddb7c1c9de892 |
@pytest.mark.parametrize('cfg_value', (None, '0.1,0.1')) <NEW_LINE> def test_min_window_size(raw, cfg_value, browser_backend): <NEW_LINE> <INDENT> old_cfg = get_config('MNE_BROWSE_RAW_SIZE') <NEW_LINE> set_config('MNE_BROWSE_RAW_SIZE', cfg_value) <NEW_LINE> fig = raw.plot() <NEW_LINE> atol = 0 if not os.name == 'nt' el... | Test minimum window plot size. | 625941ec31939e2706e4d366 |
def _mean_galprop_fraction(self, **kwargs): <NEW_LINE> <INDENT> if 'table' in list(kwargs.keys()): <NEW_LINE> <INDENT> prim_haloprop = kwargs['table'][self.prim_haloprop_key] <NEW_LINE> <DEDENT> elif 'prim_haloprop' in list(kwargs.keys()): <NEW_LINE> <INDENT> prim_haloprop = kwargs['prim_haloprop'] <NEW_LINE> <DEDENT> ... | Expectation value of the galprop for galaxies living in the input halos.
Parameters
----------
prim_haloprop : array, optional
Array of mass-like variable upon which occupation statistics are based.
If ``prim_haloprop`` is not passed, then ``table`` keyword argument must be passed.
table : object, optional
... | 625941ec6e29344779a62b14 |
def _parse_authentication(url): <NEW_LINE> <INDENT> u = url <NEW_LINE> h = {} <NEW_LINE> if url in _parse_authentication._memoize: <NEW_LINE> <INDENT> u, h = _parse_authentication._memoize[url] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p = urlparse.urlsplit(url, 'http') <NEW_LINE> if p.username and p.password: <NEW... | Parse authentication data from the URL and put it in the `headers` dict. With caching behavior
:param url: URL
:type url: str
:return: (URL without authentication info, headers dict)
:rtype: str, dict | 625941ecac7a0e7691ed45c6 |
def CreateDBInstanceHour(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("CreateDBInstanceHour", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.CreateDBInstanceHou... | 本接口(CreateDBInstanceHour)用于创建按量计费的MongoDB云数据库实例(包括主实例、灾备实例和只读实例),可通过传入实例规格、实例类型、MongoDB版本、购买时长和数量等信息创建云数据库实例。
:param request: 调用CreateDBInstanceHour所需参数的结构体。
:type request: :class:`tencentcloud.mongodb.v20180408.models.CreateDBInstanceHourRequest`
:rtype: :class:`tencentcloud.mongodb.v20180408.models.CreateDBInstanceH... | 625941eca934411ee3751b99 |
def add_buildings(self): <NEW_LINE> <INDENT> current_width = 0 <NEW_LINE> while self.width < SCREEN_WIDTH: <NEW_LINE> <INDENT> width = rand(1,(width-current_width)) <NEW_LINE> max_height = rand(10,self.maxh) <NEW_LINE> <DEDENT> self.buildings.append(building) | Will call add_building until there the buildings fill up the width of the
scroller. | 625941ec30c21e258bdfa9a7 |
@bp.route('/register', methods=('GET', 'POST')) <NEW_LINE> def register(): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> error = None <NEW_LINE> db = get_db() <NEW_LINE> username = request.form['username'] <NEW_LINE> password = request.form['password'] <NEW_LINE> apiKey = request.form['apiKey'] <... | User registration page
:return: | 625941ec67a9b606de4a83ba |
def extract_symbol_from_input(input_message): <NEW_LINE> <INDENT> if "stock" in input_message and '#' in input_message: <NEW_LINE> <INDENT> hashtag_index = input_message.find('#') <NEW_LINE> space_index = input_message[hashtag_index:].find(' ') <NEW_LINE> if space_index == -1: <NEW_LINE> <INDENT> symbol = input_message... | takes user inputted string as input and extracts stock symbol as output or none | 625941ec82261d6c526ab9ab |
def channel_in_internal_test(channel=None): <NEW_LINE> <INDENT> return channel_in(*INTERNAL_TEST_CHANNELS, channel=channel) | Is this a internal test channel?
Args:
channel (str): channel to test (default: [cfg.channel])
Returns:
bool: True if current channel in (alpha, dev) | 625941ec92d797404e304690 |
def getAction(self, gameState): <NEW_LINE> <INDENT> legalMoves = gameState.getLegalActions(0) <NEW_LINE> scores = [] <NEW_LINE> for action in legalMoves: <NEW_LINE> <INDENT> newGameState = gameState.generateSuccessor(0, action) <NEW_LINE> scores.append(self.minmaxValue(newGameState, 1, self.depth)) <NEW_LINE> <DEDENT> ... | Returns the minimax action from the current gameState using self.depth
and self.evaluationFunction.
Here are some method calls that might be useful when implementing minimax.
gameState.getLegalActions(agentIndex):
Returns a list of legal actions for an agent
agentIndex=0 means Pacman, ghosts are >= 1
gameState.g... | 625941ec8e7ae83300e4b4d2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.