code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def importance(self, encodings): <NEW_LINE> <INDENT> importance = [] <NEW_LINE> if self.model_type in ['LogR', 'LinR'] and self.task in ['survival12', 'survival60']: <NEW_LINE> <INDENT> abs_coefficients = np.abs(self.model.model.coef_[0]) <NEW_LINE> i = 0 <NEW_LINE> for column, encoding_size in encodings.items(): <NEW_... | Method that analyzes the importance of input variables for LogR/LinR and MLP* models. | 625941e5283ffb24f3c55d1c |
def _get_info(self, name): <NEW_LINE> <INDENT> self._read_status() <NEW_LINE> ret = None <NEW_LINE> for l in self._page_data.split("\n"): <NEW_LINE> <INDENT> if l.find(name + ": ") == 0: <NEW_LINE> <INDENT> ret = l.split()[-1] <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return ret | Extracts info from status | 625941e5851cf427c661a92a |
def threaded_crawler(seed_url, link_regex=None, delay=0, max_depth=-1, max_urls=-1, user_agent='wswp', proxies=None, num_retries=2, scrape_callback=None, cache=None, max_thread=10): <NEW_LINE> <INDENT> crawl_queue = queue.Queue() <NEW_LINE> crawl_queue.put(seed_url) <NEW_LINE> seen = {seed_url: 0} <NEW_LINE> D = Downlo... | Crawl from the given seed URL following links matched by link_regex
| 625941e5d164cc617578316e |
def azimuthal_integral(spec_2D, Delta, all_kr=False): <NEW_LINE> <INDENT> nd = spec_2D.ndim <NEW_LINE> if nd == 2: <NEW_LINE> <INDENT> spec_2D = spec_2D[None,...] <NEW_LINE> <DEDENT> nl,N,naux = spec_2D.shape <NEW_LINE> k,l,K,kr = get_wavenumber(N,Delta, all_kr) <NEW_LINE> dk = kr[1] - kr[0] <NEW_LINE> spec_1D = np.zer... | Compute the azimuthal integral of a 2D spectra
Parameters
----------
spec_2D: array [(nz,) ny,nx] 2d spectra
Delta: float, grid step
all_kr: bool. if False, only get radial wave number
in the inner circle, if True, gets all wave numbers.
Default is False. You should only use True to check Parseval
Returns
-----... | 625941e51d351010ab855f3a |
def update(self,dt): <NEW_LINE> <INDENT> for z in self.zulus: <NEW_LINE> <INDENT> z.position[0]+= self.vx*dt <NEW_LINE> z.position[1]+= self.vy*dt | do one step for every member this rule has.
| 625941e5a4f1c619b28b044e |
def find_score4(self, l, p): <NEW_LINE> <INDENT> comp_operator = operator.ge if p == 1 else operator.le <NEW_LINE> for r in l: <NEW_LINE> <INDENT> for k, v in itertools.groupby(r): <NEW_LINE> <INDENT> ml = list(v) <NEW_LINE> if comp_operator(sum(ml), p * 4): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> ... | Returns True if the l contains 4 in a row | 625941e5b7558d58953c532a |
def detachFrom(self, *args): <NEW_LINE> <INDENT> return _DataModel.ResponseFIR_detachFrom(self, *args) | detachFrom(ResponseFIR self, PublicObject parent) -> bool | 625941e5e76e3b2f99f3ac24 |
def test_serial_correlation(self, method, lags=None): <NEW_LINE> <INDENT> if method is None: <NEW_LINE> <INDENT> method = 'ljungbox' <NEW_LINE> <DEDENT> if self.standardized_forecasts_error is None: <NEW_LINE> <INDENT> raise ValueError('Cannot compute test statistic when standardized' ' forecast errors have not been co... | Ljung-Box test for no serial correlation of standardized residuals
Null hypothesis is no serial correlation.
Parameters
----------
method : {'ljungbox','boxpierece', None}
The statistical test for serial correlation. If None, an attempt is
made to select an appropriate test.
lags : None, int or array_like
... | 625941e556b00c62f0f14a7b |
def get_workflow_actions(obj): <NEW_LINE> <INDENT> def translate(i): <NEW_LINE> <INDENT> return t(PMF(i + "_transition_title")) <NEW_LINE> <DEDENT> workflow = ploneapi.portal.get_tool("portal_workflow") <NEW_LINE> actions = [{"id": it["id"], "title": translate(it["id"])} for it in workflow.getTransitionsFor(obj)] <NEW_... | Compile a list of possible workflow transitions for this object
| 625941e54f88993c3716c482 |
def load_cubes(filenames, callback, constraints=None): <NEW_LINE> <INDENT> return pp._load_cubes_variable_loader(filenames, callback, FF2PP, constraints=constraints) | Loads cubes from a list of fields files filenames.
Args:
* filenames - list of fields files filenames to load
Kwargs:
* callback - a function which can be passed on to
:func:`iris.io.run_callback`
.. note::
The resultant cubes may not be in the order that they are in the
file (order is not preserved w... | 625941e531939e2706e4d283 |
def __str__(self): <NEW_LINE> <INDENT> s_out="" <NEW_LINE> if isinstance(self._DataBase,MySQLdb.connection): <NEW_LINE> <INDENT> s_out = "Database: " + self._DataBase.get_host_info() + "\n" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s_out = "Database: NOT OPENED \n" <NEW_LINE> <DEDENT> s_out+= "Table : " + self._... | Return string with list of what the geometry currently contains. | 625941e5e1aae11d1e74a0da |
def __init__(self, channel): <NEW_LINE> <INDENT> self.Predict = channel.unary_unary( "/google.cloud.automl.v1.PredictionService/Predict", request_serializer=google_dot_cloud_dot_automl__v1_dot_proto_dot_prediction__service__pb2.PredictRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_automl__v1_dot_... | Constructor.
Args:
channel: A grpc.Channel. | 625941e53346ee7daa2b318e |
def GetPointer(self): <NEW_LINE> <INDENT> return _itkScalarImageKmeansImageFilterPython.itkScalarImageKmeansImageFilterIUL2IUS2_GetPointer(self) | GetPointer(self) -> itkScalarImageKmeansImageFilterIUL2IUS2 | 625941e5796e427e537b09e8 |
def add_alt(self, *args): <NEW_LINE> <INDENT> return _sphinxbase.FsgModel_add_alt(self, *args) | add_alt(FsgModel self, char const * baseword, char const * altword) -> int
Add alternate pronunciation transitions for a word in given FSG. | 625941e5851cf427c661a92b |
def show_map(self): <NEW_LINE> <INDENT> self.dismiss() <NEW_LINE> try: <NEW_LINE> <INDENT> map_intent(geo_uri(self.item.latitude, self.item.longitude, self.item.name)) <NEW_LINE> <DEDENT> except NotImplementedError as e: <NEW_LINE> <INDENT> Alert(title="Show Map", text=str(e)) | Show the map for this place | 625941e57cff6e4e81117da5 |
def auto_disconnect_from_cubes_at_end(self, enable=True): <NEW_LINE> <INDENT> msg = _clad_to_engine_iface.SetShouldAutoDisconnectFromCubesAtEnd(doAutoDisconnect=enable) <NEW_LINE> self.conn.send_msg(msg) | Tell the SDK to auto disconnect from cubes at the end of every SDK program.
This can be used to save cube battery life if you spend a lot of time in
SDK mode but aren't running programs as much (as you're busy writing
them). Call :meth:`connect_to_cubes` to re-connect to the cubes later.
Args:
enable (bool): Tru... | 625941e515fb5d323cde0f34 |
def loss(self, X, y=None): <NEW_LINE> <INDENT> X = X.astype(self.dtype) <NEW_LINE> mode = 'test' if y is None else 'train' <NEW_LINE> if self.dropout_param is not None: <NEW_LINE> <INDENT> self.dropout_param['mode'] = mode <NEW_LINE> <DEDENT> if self.use_batchnorm: <NEW_LINE> <INDENT> for bn_param in self.bn_params: <N... | Compute loss and gradient for the fully-connected net.
Input / output: Same as TwoLayerNet above. | 625941e530bbd722463cc1e7 |
def _command_generic_msg(self, host, result, caption): <NEW_LINE> <INDENT> buf = "%s | %s | rc=%s >>\n" % (host, caption, result.get('rc', -1)) <NEW_LINE> buf += result.get('stdout', '') <NEW_LINE> buf += result.get('stderr', '') <NEW_LINE> buf += result.get('msg', '') <NEW_LINE> return buf + "\n" | output the result of a command run | 625941e523849d37ff7b34ab |
def update_statefile(filename, lastid, lasttime): <NEW_LINE> <INDENT> pfobj = stock.ParameterFile() <NEW_LINE> pfobj.update(dict(lastid=lastid)) <NEW_LINE> pfobj.update(dict(lasttime=lasttime)) <NEW_LINE> with open(filename, "w", encoding="utf8") as mypffile: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> mypffile.write(... | update time and id in statefile | 625941e52eb69b55b151ccd4 |
def isDeepBlue(fname): <NEW_LINE> <INDENT> if fname.endswith(".wig"): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if fname.endswith(".wiggle"): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if fname.endswith(".bedgraph"): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if fname.startswith("http") or f... | Returns true if the file ends in .wig, .wiggle, or .bedgraph, since these indicate a file on the deepBlue server | 625941e50a366e3fb873ec3d |
def test_compression_update_header_with_reserved(self): <NEW_LINE> <INDENT> def test_set_keyword(hdr, keyword, value): <NEW_LINE> <INDENT> with catch_warnings() as w: <NEW_LINE> <INDENT> hdr[keyword] = value <NEW_LINE> assert len(w) == 1 <NEW_LINE> assert str(w[0].message).startswith( f"Keyword {keyword!r} is reserved"... | Ensure that setting reserved keywords related to the table data
structure on CompImageHDU image headers fails. | 625941e5d53ae8145f87a687 |
def interpolate_bezier(knot1: 'mathutils.Vector', handle1: 'mathutils.Vector', handle2: 'mathutils.Vector', knot2: 'mathutils.Vector', resolution: int) -> list: <NEW_LINE> <INDENT> pass | Interpolate a bezier spline segment.
:param knot1: First bezier spline point.
:type knot1: 'mathutils.Vector'
:param handle1: First bezier spline handle.
:type handle1: 'mathutils.Vector'
:param handle2: Second bezier spline handle.
:type handle2: 'mathutils.Vector'
:param knot2: Second bezier spline point.
:type... | 625941e5a4f1c619b28b044f |
def filter_by_tags(games, taglist, tagfilter): <NEW_LINE> <INDENT> tag_filtered_games = [] <NEW_LINE> for g in games: <NEW_LINE> <INDENT> matches_found = 0 <NEW_LINE> for pattern in taglist: <NEW_LINE> <INDENT> p = '.*'.join([re.escape(x) for x in pattern.split('*')]) <NEW_LINE> p = '^' + p + '$' <NEW_LINE> for t in g.... | Given an iterable of games, returns a list of games
filtered by tags.
If tagfilter is 'all', a game must have all the tags in taglist in order to remain in the list.
If tagfilter is 'any', a game must have one or more of the tags in taglist in order to remain in the list.
Args:
games: iterable of store.Game ... | 625941e55fc7496912cc3d9d |
def t_COMMENTS(t): <NEW_LINE> <INDENT> t.lexer.lineno += 1 | //.*\n | 625941e521a7993f00bc8116 |
def BouncerHTTPRequestHandler(redirect, guestlist): <NEW_LINE> <INDENT> class BouncerHandler(BaseHTTPRequestHandler): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> BaseHTTPRequestHandler.__init__(self, *args, **kwargs) <NEW_LINE> <DEDENT> def do_HEAD(self): <NEW_LINE> <INDENT> self.send_r... | BouncerHTTPRequestHandler returns a BouncerHandler class that acts like
a club bouncer in front of another server. The bouncer will respond to
GET requests by looking up the allowed number of requests in the guestlist
for the User-Agent making the request. If there is at least one guestlist
spot for that UA it will be ... | 625941e5bde94217f368320c |
def adam(x, dx, config=None): <NEW_LINE> <INDENT> if config is None: config = {} <NEW_LINE> config.setdefault('learning_rate', 1e-3) <NEW_LINE> config.setdefault('beta1', 0.9) <NEW_LINE> config.setdefault('beta2', 0.999) <NEW_LINE> config.setdefault('epsilon', 1e-8) <NEW_LINE> config.setdefault('m', np.zeros_like(x)) <... | Uses the Adam update rule, which incorporates moving averages of both the
gradient and its square and a bias correction term.
config format:
- learning_rate: Scalar learning rate.
- beta1: Decay rate for moving average of first moment of gradient.
- beta2: Decay rate for moving average of second moment of gradient.
- ... | 625941e54d74a7450ccd45e4 |
def search_strongly_connected_components(self): <NEW_LINE> <INDENT> self.colour.update({self.node_number: 'grey'}) <NEW_LINE> self.stack.push(self.node_number) <NEW_LINE> for i in self.digraph[self.node_number]: <NEW_LINE> <INDENT> if self.colour.get(i) == 'white': <NEW_LINE> <INDENT> self.node_number = i <NEW_LINE> se... | performs DFS search on given graph in the form [[1,2],[2],[1]] recursively to
find strongly connected components | 625941e5d58c6744b425807d |
def synchronise(func): <NEW_LINE> <INDENT> def inner(request, *args): <NEW_LINE> <INDENT> lock_id = '%s-%s-built-%s' % ( datetime.date.today(), func.func_name, ",".join([str(a) for a in args])) <NEW_LINE> if cache.add(lock_id, 'true', LOCK_EXPIRE): <NEW_LINE> <INDENT> result = func(request, *args) <NEW_LINE> cache.set(... | If task already queued, running, or finished, don't restart. | 625941e5462c4b4f79d1daef |
def thread(self, user, filter): <NEW_LINE> <INDENT> return self.select_related('sender', 'recipient').filter( filter, (models.Q(recipient=user) & models.Q(moderation_status=STATUS_ACCEPTED)) | models.Q(sender=user) | models.Q(multi_conversation__participants=user), ).order_by('sent_at').distinct() | Return message/conversation for display. | 625941e5293b9510aa2c36b1 |
@bp.route("/", methods=["GET"]) <NEW_LINE> def index(): <NEW_LINE> <INDENT> return render_template("nosql/index.jinja") | TODO: DOC | 625941e5956e5f7376d7128b |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941e59f2886367277aca9 |
def distorted_inputs(data_dir, batch_size): <NEW_LINE> <INDENT> filenames = [os.path.join(data_dir, 'data_batch_%d.bin' % i) for i in xrange(1, 5)] <NEW_LINE> for f in filenames: <NEW_LINE> <INDENT> if not tf.gfile.Exists(f): <NEW_LINE> <INDENT> raise ValueError('Failed to find file: ' + f) <NEW_LINE> <DEDENT> <DEDENT>... | Construct distorted input for SETI training using the Reader ops.
Args:
data_dir: Path to the SETI data directory.
batch_size: Number of images per batch.
Returns:
images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.
labels: Labels. 1D tensor of [batch_size] size. | 625941e526068e7796caf105 |
def convert_to_numpy(dataset_dir, dataset_name): <NEW_LINE> <INDENT> dataset = datasets[dataset_name] <NEW_LINE> if not tf.gfile.Exists(dataset_dir): <NEW_LINE> <INDENT> tf.gfile.MakeDirs(dataset_dir) <NEW_LINE> <DEDENT> dataset_utils.download_and_uncompress_tarball(dataset['url'], dataset_dir) <NEW_LINE> images = [] <... | Runs the download and conversion operation.
Args:
dataset_dir: The dataset directory where the dataset is stored.
dataset_name: The dataset name (cifar10 or cifar100) | 625941e5090684286d50f10a |
def del_friendly_name(self, name_id): <NEW_LINE> <INDENT> current = self._read_config() <NEW_LINE> self._delete_value(current, name_id) <NEW_LINE> self._write(self._path, current) | Edit id friendlyname | 625941e56fece00bbac2db63 |
def test_upper_hemisphere_illuminance_weights_Lagarde2016(self): <NEW_LINE> <INDENT> weights = np.array( [ [0.00000000], [1.98673676], [3.89213628], [5.63819129], [7.15341808], [8.37578310], [9.25524257], [9.75579132], [9.85693683], [9.55453819], [8.86097564], [7.80464369], [6.42878872], [4.78973839], [2.95459560], [0.... | Test :func:`colour_hdri.calibration.absolute_luminance.upper_hemisphere_illuminance_weights_Lagarde2016` definition. | 625941e56e29344779a62a2f |
@error.context_aware <NEW_LINE> def run(test, params, env): <NEW_LINE> <INDENT> error.context("Check for an appropriate clocksource on host", logging.info) <NEW_LINE> host_cmd = "cat /sys/devices/system/clocksource/" <NEW_LINE> host_cmd += "clocksource0/current_clocksource" <NEW_LINE> if "tsc" not in utils.system_outpu... | Timer device tscwrite test:
1) Check for an appropriate clocksource on host.
2) Boot the guest.
3) Download and compile the newest msr-tools.
4) Execute cmd in guest.
:param test: QEMU test object.
:param params: Dictionary with test parameters.
:param env: Dictionary with the test environment. | 625941e50c0af96317bb8607 |
def load_data(data_dir): <NEW_LINE> <INDENT> categories = os.listdir(data_dir) <NEW_LINE> category_count = len(categories) <NEW_LINE> X = [] <NEW_LINE> Y = [] <NEW_LINE> for category_id, category in enumerate(categories): <NEW_LINE> <INDENT> data_points = os.listdir(os.path.join(data_dir,category)) <NEW_LINE> for data_... | This function loads all the data. It converts the photos to numpy arrays
and prepares labels for the training | 625941e5dd821e528d63b5c5 |
def is_stationary(self): <NEW_LINE> <INDENT> return np.all([kernel.is_stationary() for kernel in self.kernels]) | Returns whether the kernel is stationary. | 625941e5eab8aa0e5d26df79 |
def fullnnflow(playlist): <NEW_LINE> <INDENT> unsortedlist = playlist.tracks <NEW_LINE> return(nnflow(unsortedlist)) | Flow using nearest neighbor algorithm. Idea is that differences in
attribute values between songs are used to compute a 'distance' between
each song. Creating a playlist with that minimizes the maximum distance
between any two songs is equivalent to the bottlenect traveling salesman
problem (without returning to the or... | 625941e54e696a04525c986d |
def find_in_dict(self, word): <NEW_LINE> <INDENT> raise NotImplementedError | Method checks if there is a given word in freq dict. | 625941e5d268445f265b528e |
def train(model, train_loader, epochs, optimizer, loss_fn, device): <NEW_LINE> <INDENT> for epoch in range(1, epochs + 1): <NEW_LINE> <INDENT> model.train() <NEW_LINE> total_loss = 0 <NEW_LINE> for batch in train_loader: <NEW_LINE> <INDENT> batch_X, batch_y = batch <NEW_LINE> batch_X = batch_X.to(device) <NEW_LINE> bat... | This is the training method that is called by the PyTorch training script. The parameters
passed are as follows:
model - The PyTorch model that we wish to train.
train_loader - The PyTorch DataLoader that should be used during training.
epochs - The total number of epochs to train for.
optimizer - The o... | 625941e5d7e4931a7ee9e33e |
def test_get_school(self): <NEW_LINE> <INDENT> pass | Test case for get_school | 625941e576e4537e8c351a95 |
def do_sleep(self, arg): <NEW_LINE> <INDENT> print('sleep') <NEW_LINE> if self.system == 'Windows': <NEW_LINE> <INDENT> os.system('psshutdown -d') <NEW_LINE> <DEDENT> elif self.system == 'Darwin': <NEW_LINE> <INDENT> os.system('osascript -e \'tell app "System Events" to sleep\'') <NEW_LINE> <DEDENT> else: <NEW_LINE> <I... | Sleep the other computer. Uses os module to run "pmset" on MacOS,
"shutdown" on Windows, and "xset" on Linux. Available for MacOS,
Windows, and Linux. | 625941e5a8ecb033257d34eb |
def stop(self): <NEW_LINE> <INDENT> self._stop_event.set() | Signal the iterator to stop waiting for more data | 625941e58a349b6b435e8592 |
def file_content(filename:str, onfail='') -> str: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(filename) as fd: <NEW_LINE> <INDENT> content = fd.read() <NEW_LINE> <DEDENT> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> content = onfail <NEW_LINE> <DEDENT> return content | Return the content of given filename, or onfail
if filename is not found. | 625941e53c8af77a43ae3bc5 |
def get_tweets(url, keyword, language='all'): <NEW_LINE> <INDENT> if language != 'all': <NEW_LINE> <INDENT> search_params = {'q': keyword, 'result_type': 'recent', 'count': 100, 'lang': language} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> search_params = {'q': keyword, 'result_type': 'recent', 'count': 100} <NEW_LIN... | Request search API to get 100 tweets related to the keyword
Args:
url (str): url of the API, can contain a max_id to request "old" tweet
keyword (str): keyword from the request of the user
language (str, optional): Defaults to 'all'. Wanted language of tweets
Returns:
[type]: [description] | 625941e5097d151d1a223277 |
def primeFactors(num, factors=[]): <NEW_LINE> <INDENT> if num == 1: <NEW_LINE> <INDENT> return factors <NEW_LINE> <DEDENT> i = 2 <NEW_LINE> while True: <NEW_LINE> <INDENT> if num%i==0: <NEW_LINE> <INDENT> return primeFactors(num/i,factors+[i]) <NEW_LINE> <DEDENT> i += 1 | Return a list of all the prime factors of num | 625941e5287bf620b61d3e81 |
def test_setting_provision_state_fails(self): <NEW_LINE> <INDENT> url = self.url + "/111/states/provision" <NEW_LINE> (response, content) = self.successResultOf(json_request( self, self.root, b"PUT", url, body={'target': 'active'})) <NEW_LINE> self.assertEqual(response.code, 404) <NEW_LINE> self.assertTrue('111' in con... | Test ``/nodes/<node-id>/states/provision`` returns a 404 when
the node does not exist | 625941e52c8b7c6e89b35bdd |
def assert_not_attached(f): <NEW_LINE> <INDENT> @wraps(f) <NEW_LINE> def new_f(args, cfg): <NEW_LINE> <INDENT> if cfg.is_attached: <NEW_LINE> <INDENT> raise exceptions.AlreadyAttachedError(cfg) <NEW_LINE> <DEDENT> return f(args, cfg=cfg) <NEW_LINE> <DEDENT> return new_f | Decorator asserting unattached config. | 625941e5d99f1b3c44c679a7 |
def test_storing_null_domain_id_in_project_ref(self): <NEW_LINE> <INDENT> spoiler_project = unit.new_project_ref( domain_id=CONF.identity.default_domain_id) <NEW_LINE> self.resource_api.create_project(spoiler_project['id'], spoiler_project) <NEW_LINE> project = unit.new_project_ref(domain_id=None, is_domain=True) <NEW_... | Test the special storage of domain_id=None in sql resource driver.
The resource driver uses a special value in place of None for domain_id
in the project record. This shouldn't escape the driver. Hence we test
the interface to ensure that you can store a domain_id of None, and
that any special value used inside the dr... | 625941e5d7e4931a7ee9e33f |
def fit(self, X, y): <NEW_LINE> <INDENT> X, y = check_X_y(X, y) <NEW_LINE> super(RandomUnderSampler, self).fit(X, y) <NEW_LINE> return self | Find the class statistics before performing sampling.
Parameters
----------
X : ndarray, shape (n_samples, n_features)
Matrix containing the data to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
-------
self : object,
Return self. | 625941e507f4c71912b118a4 |
def __init__(self, sigma, mean=0, rng = None): <NEW_LINE> <INDENT> if rng is None: <NEW_LINE> <INDENT> self.rng = np.random.RandomState(42) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.rng = rng <NEW_LINE> <DEDENT> self.sigma = sigma <NEW_LINE> self.mean = mean | Log normal prior
Parameters
----------
sigma: float
Specifies the standard deviation of the normal
distribution.
mean: float
Specifies the mean of the normal distribution | 625941e54f88993c3716c483 |
def forward(self, h, context, mask=None): <NEW_LINE> <INDENT> target = self.linear_in(h).unsqueeze(2) <NEW_LINE> attn = torch.bmm(context, target).squeeze(2) <NEW_LINE> if mask is not None: <NEW_LINE> <INDENT> attn.data.masked_fill_(mask, -float('inf')) <NEW_LINE> <DEDENT> attn = self.sm(attn) <NEW_LINE> attn3 = attn.v... | Propagate h through the network.
h: batch x dim
context: batch x seq_len x dim
mask: batch x seq_len indices to be masked | 625941e566673b3332b924b1 |
def iter_reduced( self, ) -> Generator[ReducedPath, None, None]: <NEW_LINE> <INDENT> raw = self.raw_entry <NEW_LINE> if not is_glob(raw): <NEW_LINE> <INDENT> yield ReducedPath(raw, None, self.exclude) <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rel_prio = calc_raw_path_priority(raw) <NEW_LINE> yield... | Generates the reduced paths of this RP according to their net priority.
Priority is defined by these two rules:
- specific beats general
- files beat directories
Yields:
ReducePaths, ordered by their net relative_priority.
suitable for inclusion in order. | 625941e530dc7b7665901d82 |
def send_update_sys_metadata(mn: str, pid: str, metadata_xml: str, client_certificate_path: str): <NEW_LINE> <INDENT> print('updateSysMetadata: ', pid, flush=True) <NEW_LINE> global sent_count <NEW_LINE> sent_count += 1 <NEW_LINE> session = Session() <NEW_LINE> *_, scope, identifier, revision = pid.split('/') <NEW_LINE... | Send a updateSysMetadata request to the member node.
This is not done asynchronously because we need to use PreparedRequest. | 625941e5fff4ab517eb2f85e |
def test_folded_state_all_ids(self): <NEW_LINE> <INDENT> expected_states = { 'NoScore': False, 'High': False, 'Medium': False, 'Low': False, 'None': False, 'ObsStop': False, 'Refused': False } <NEW_LINE> groups = self.wardboard_model._get_acuity_groups( [ 'NoScore', 'High', 'Medium', 'Low', 'None', 'ObsStop', 'Refused'... | Make sure only the medium group is unfolded | 625941e58a43f66fc4b54481 |
def plot_shep21_genes(nb_figure_gff_path,bed_string): <NEW_LINE> <INDENT> plotFolder = utils.formatFolder('%sSHEP21_NOSPIKE/' % (genePlotFolder),True) <NEW_LINE> plot_prefix = 'HG19_NB_FIGURE_GENES' <NEW_LINE> dataDict = pipeline_dfci.loadDataTable(shep21_dataFile) <NEW_LINE> names_list = dataDict.keys() <NEW_LINE> bam... | plots all varieties and iterations of tracks for shep21 data | 625941e57047854f462a1825 |
def main(): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> for event in pygame.event.get(QUIT): <NEW_LINE> <INDENT> pygame.quit() <NEW_LINE> sys.exit() <NEW_LINE> <DEDENT> SURFACE.fill((0,0,0)) <NEW_LINE> pointlist0, pointlist1 = [], [] <NEW_LINE> for theta in range(0,360,72): <NEW_LINE> <INDENT> rad = radians(the... | main routine | 625941e521bff66bcd684d6e |
def shared_range(flt_type, int_type): <NEW_LINE> <INDENT> flt_type = np.dtype(flt_type).type <NEW_LINE> int_type = np.dtype(int_type).type <NEW_LINE> key = (flt_type, int_type) <NEW_LINE> try: <NEW_LINE> <INDENT> return _SHARED_RANGES[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT... | Min and max in float type that are >=min, <=max in integer type
This is not as easy as it sounds, because the float type may not be able to
exactly represent the max or min integer values, so we have to find the
next exactly representable floating point value to do the thresholding.
Parameters
----------
flt_type : d... | 625941e58e71fb1e9831dbc8 |
def test_claroty_is_first(self): <NEW_LINE> <INDENT> CLAROTY_URL = "https://www.claroty.com" <NEW_LINE> google = Google(self.driver) <NEW_LINE> google.search("Claroty") <NEW_LINE> search_results_page = GoogleSearchResults(self.driver) <NEW_LINE> self.assertTrue(url_domain_compare(search_results_page.get_first_result_li... | Make sure that claroty.com is the first result's link | 625941e510dbd63aa1bd2fc2 |
def _sel_mount_spec(self, host_source, cont_dest): <NEW_LINE> <INDENT> for (index, mount) in enumerate(self._container_specjson["mounts"]): <NEW_LINE> <INDENT> if (mount["destination"] == cont_dest and mount["source"] == host_source): <NEW_LINE> <INDENT> return index <NEW_LINE> <DEDENT> <DEDENT> return None | Select mount point | 625941e53317a56b8693a06e |
def factorize(n): <NEW_LINE> <INDENT> if n < 1: <NEW_LINE> <INDENT> raise ValueError("No prime factors for %s" % n) <NEW_LINE> <DEDENT> factors = defaultdict(int) <NEW_LINE> if n == 1: <NEW_LINE> <INDENT> return factors <NEW_LINE> <DEDENT> if factorPath != None: <NEW_LINE> <INDENT> res = subprocess.run(["gfactor", str(... | Factorize an integer.
Args:
n: An integer to factorize.
Returns:
A dict of prime factors (keys) and their exponents (values).
Usage:
>>> factorize(1546)
defaultdict(<class 'int'>, {2: 1, 773: 1}) | 625941e555399d3f05588ad6 |
def test_city_update_at(self): <NEW_LINE> <INDENT> old1 = self.city1.updated_at <NEW_LINE> old2 = self.city2.updated_at <NEW_LINE> self.city1.save() <NEW_LINE> self.city2.save() <NEW_LINE> self.assertNotEqual(old1, self.city1.updated_at) <NEW_LINE> self.assertNotEqual(old2, self.city2.updated_at) | Method to test updated at of user class | 625941e55fc7496912cc3d9e |
def HandleKeyDownEvent(self, event): <NEW_LINE> <INDENT> if self.parent_widget == None: <NEW_LINE> <INDENT> if self.focused_widget != None: <NEW_LINE> <INDENT> self.focused_widget.HandleKeyDownEvent(event) | Handle a KEYDOWN event. In the case of a Container, just pass it on to
the currently focused child widget. | 625941e54c3428357757c746 |
def _get_element(self, **kwargs) -> _html.Element: <NEW_LINE> <INDENT> authorize_url = _router.url('https://oauth.vk.com/authorize', query={ 'client_id': self._app_id, 'scope': ','.join(self.scope), 'redirect_uri': 'https://oauth.vk.com/blank.html', 'display': 'page', 'response_type': 'token', 'v': '5.37', }) <NEW_LINE... | Render widget.
:param **kwargs: | 625941e5956e5f7376d7128c |
def test_shzn_xitongguanli(self): <NEW_LINE> <INDENT> driver = self.driver <NEW_LINE> driver.get(self.base_url) <NEW_LINE> time.sleep(3) <NEW_LINE> driver.find_element_by_xpath("//*[@id='app']/div/div/div[1]/div[2]/ul/li[6]").click() <NEW_LINE> time.sleep(3) <NEW_LINE> driver.find_element_by_xpath("//*[@id='app']/div/d... | 系统管理用例 | 625941e576d4e153a657ef52 |
def get(self, request): <NEW_LINE> <INDENT> role_id = request.query_params.get('role_id', None) <NEW_LINE> try: <NEW_LINE> <INDENT> if role_id: <NEW_LINE> <INDENT> result = get_permission_by_role(role_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = get_all_permission() <NEW_LINE> <DEDENT> <DEDENT> except Exc... | 通过用户角色获取到该角色对应的系统导航栏目
:param request: role_id
:return: | 625941e521a7993f00bc8117 |
def test_matrix_score_error(): <NEW_LINE> <INDENT> with pytest.raises(Exception) as kerr: <NEW_LINE> <INDENT> scoring_matrix.matrix_score("MAAAAG", "MAAAAO", PAM70) <NEW_LINE> <DEDENT> assert ( repr(kerr.value) == "AminoAcidNotFoundError(\"Scoring matrix does not support scoring for: ('G', 'O')\")" or repr(kerr.value) ... | Check if inputting an invalid character raises and error | 625941e5ec188e330fd5abb7 |
def compute_distances_no_loops(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> test = X <NEW_LINE> train = self.X_train <NEW_LINE> num_train = train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> train_sqr = train**2 <NEW_LINE> test_sqr = test**2 <NEW_LINE> tt = test.dot(train.T) ... | Compute the distance between each test point in X and each training point
in self.X_train using no explicit loops.
Input / Output: Same as compute_distances_two_loops | 625941e5925a0f43d254a29b |
def _load_has_relations(self, attrs, resource_name, resource_model, service_context): <NEW_LINE> <INDENT> for reference in resource_model.references: <NEW_LINE> <INDENT> attrs[reference.name] = self._create_reference( reference_model=reference, resource_name=resource_name, service_context=service_context ) <NEW_LINE> <... | Load related resources, which are defined via a ``has``
relationship but conceptually come in two forms:
1. A reference, which is a related resource instance and can be
``None``, such as an EC2 instance's ``vpc``.
2. A subresource, which is a resource constructor that will always
return a resource instance which... | 625941e51f5feb6acb0c4f69 |
def solve(self): <NEW_LINE> <INDENT> raise NotImplementedError("This method needs to be implemented.") | Solves the problem.
Stores the solution internally.
:return: Nothing, everything should be save internally. | 625941e530bbd722463cc1e8 |
def monitor_db_list(request): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> data = json.loads(request.body) <NEW_LINE> url = data['url'] <NEW_LINE> type = data['type'] <NEW_LINE> if type == 'MongoDB': <NEW_LINE> <INDENT> client = pymongo.MongoClient(url) <NEW_LINE> dbs = client.database_names() <... | get monitor db list
:param request: request object
:return: json of db list | 625941e563d6d428bbe44911 |
def convert_x509cert(self, cert_bytes): <NEW_LINE> <INDENT> return x509.load_der_x509_certificate(cert_bytes, default_backend()) | 바이너리 데이터를 x509 인증서로 변환
:param cert_bytes: 인증서 bytes
:return: x509 인증서 | 625941e50c0af96317bb8608 |
def draw_features(self, spec_data, recon_data, feature_vector): <NEW_LINE> <INDENT> if spec_data is not None: <NEW_LINE> <INDENT> plt.figure() <NEW_LINE> plt.axis('off') <NEW_LINE> librosa.display.specshow(spec_data.reshape(128, 256), y_axis='mel', fmax=8000, x_axis='time') <NEW_LINE> plt.show() <NEW_LINE> <DEDENT> if ... | Draw data in parameters.
:param spec_data:
:param recon_data:
:param feature_vector: | 625941e5be7bc26dc91cda18 |
def testFillReceiptLog(self): <NEW_LINE> <INDENT> pass | Test FillReceiptLog | 625941e53eb6a72ae02ec908 |
def GetOperationByNamesDontThrow(self, names): <NEW_LINE> <INDENT> for name in names: <NEW_LINE> <INDENT> op = self.GetOperationByNameDontThrow(name) <NEW_LINE> if op is not None: <NEW_LINE> <INDENT> return op <NEW_LINE> <DEDENT> <DEDENT> return None | Returns an Operation with one of the given names.
Args:
names: Names of Operation to return.
Returns:
The Operation with one of the given names. None if none of the names
corresponds to any operation in the graph. | 625941e560cbc95b062c6964 |
def check_email(email): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> v = validate_email(email) <NEW_LINE> email = v["email"] <NEW_LINE> <DEDENT> except EmailNotValidError: <NEW_LINE> <INDENT> raise AttributeError("email is not valid") | Function to validate email
when saving email to database
:params email | 625941e5a8ecb033257d34ec |
def solve(board, row): <NEW_LINE> <INDENT> if row >= len(board): <NEW_LINE> <INDENT> solution.append(board) <NEW_LINE> printboard(board) <NEW_LINE> print() <NEW_LINE> return <NEW_LINE> <DEDENT> for i in range(len(board)): <NEW_LINE> <INDENT> if isSafe(board, row, i): <NEW_LINE> <INDENT> board[row][i] = 1 <NEW_LINE> sol... | It creates a state space tree and calls the safe function until it receives a
False Boolean and terminates that branch and backtracks to the next
poosible solution branch. | 625941e54a966d76dd551433 |
def get_eigen_values_and_vectors(matrix, num_values): <NEW_LINE> <INDENT> w, v = np.linalg.eig(matrix) <NEW_LINE> eigen_values = w[:num_values] <NEW_LINE> eigen_vectors = v[:,:num_values] <NEW_LINE> return eigen_values, eigen_vectors | Return top n eigen values and corresponding vectors of matrix
Args:
matrix: numpy matrix of shape (m, m)
num_values: number of eigen values and respective vectors to return
Returns:
eigen_values: array of shape (n)
eigen_vectors: array of shape (m, n) | 625941e50fa83653e46573d9 |
def create_filtered_fields_if_missing(pn, keys): <NEW_LINE> <INDENT> pn_new = pn.copy() <NEW_LINE> keys = list(map(str.upper, keys)) <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> if key.lower() not in pn_new.items: <NEW_LINE> <INDENT> pn_new[key.lower()] = pn_new[key] <NEW_LINE> <DEDENT> <DEDENT> return pn_new | Check that lower case key versions of the fields exist. | 625941e563b5f9789fde7506 |
def get_image_preprocessor(self): <NEW_LINE> <INDENT> image_size = self.model.get_image_size() <NEW_LINE> input_data_type = tf.float32 <NEW_LINE> shift_ratio = 0 <NEW_LINE> if self.job_name: <NEW_LINE> <INDENT> assert self.worker_hosts <NEW_LINE> shift_ratio = float(self.task_index) / len(self.worker_hosts) <NEW_LINE> ... | Returns the image preprocessor to used, based on the model.
Returns:
The image preprocessor, or None if synthetic data should be used. | 625941e5283ffb24f3c55d1d |
def get(self, show=True, proxy=None, timeout=0): <NEW_LINE> <INDENT> wikibase = self.params.get('wikibase') <NEW_LINE> if wikibase: <NEW_LINE> <INDENT> self.flags['defer_imageinfo'] = True <NEW_LINE> self.get_wikidata(False, proxy, timeout) <NEW_LINE> self.get_query(False, proxy, timeout) <NEW_LINE> self.get_parse(Fals... | Make Mediawiki, RESTBase, and Wikidata requests for page data
some sequence of:
- get_parse()
- get_query()
- get_restbase()
- get_wikidata() | 625941e5009cb60464c637cf |
def _has_logged_in(): <NEW_LINE> <INDENT> return True | This function returns True iff:
1. Authentication has been completed
2. Authentication is valid.
Currently this is unimplemented pending knowledge of
how the SCS authentication system works. | 625941e5dd821e528d63b5c6 |
def fetch(self): <NEW_LINE> <INDENT> __, __, exit_status = self._git_cmd(self._git_path, 'config remote.origin.fetch %s' % '+refs/heads/*:refs/remotes/origin/*') <NEW_LINE> if exit_status == 0: <NEW_LINE> <INDENT> __, __, exit_status = self._git_cmd(self._git_path, 'fetch --all') <NEW_LINE> <DEDENT> return (False, True... | Calls git fetch to fetch all remote branches
on the call's success. | 625941e5ab23a570cc2505a6 |
def apply_replacements(self, s, replacements): <NEW_LINE> <INDENT> return s | apply the replacements specified to text | 625941e567a9b606de4a82d7 |
def __init__(self, value: bool, read_only: bool): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.read_only = read_only | Initialize the boolean value. | 625941e5656771135c3ebc94 |
def update_draft_media(self, image, video): <NEW_LINE> <INDENT> if self.video and image: <NEW_LINE> <INDENT> self.video = None <NEW_LINE> self.save() <NEW_LINE> <DEDENT> if self.original_image and video: <NEW_LINE> <INDENT> self.original_image = None <NEW_LINE> self.save() | Updates media for `Observation`.
Args:
image(File or None): `original_image` from request.
video(File or None): `video` from request. | 625941e58e05c05ec3eea799 |
def _read_layer_mask_data(fp): <NEW_LINE> <INDENT> size = read_fmt("I", fp)[0] <NEW_LINE> if not size: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> top, left, bottom, right, background_color, flags = read_fmt("4i 2B", fp) <NEW_LINE> flags = MaskFlags( bool(flags & 1), bool(flags & 2), bool(flags & 4), bool(flags... | Reads layer mask or adjustment layer data. | 625941e53cc13d1c6d3c7799 |
def __init__(self, ukb_csvs, db_uri, bgen_sample_file=None, table_prefix='ukb_pheno_', n_columns_per_table=sys.maxsize, loading_n_jobs=-1, tmpdir=tempfile.mkdtemp(prefix='ukbrest'), loading_chunksize=5000, sql_chunksize=None, delete_temp_csv=True): <NEW_LINE> <INDENT> super(Pheno2SQL, self).__init__(db_uri) <NEW_LINE> ... | :param ukb_csvs: files are loaded in the order they are specified
:param db_uri:
:param table_prefix:
:param n_columns_per_table:
:param loading_n_jobs:
:param tmpdir:
:param loading_chunksize: number of lines to read when loading CSV files to the SQL database.
:param sql_chunksize: when an SQL query is submited to get... | 625941e545492302aab5e6e8 |
def _load(self, json): <NEW_LINE> <INDENT> print(json['openapi']) | Load the object based on text. | 625941e5851cf427c661a92c |
def blur(self, grid): <NEW_LINE> <INDENT> center = 1.0 - self.blur_factor <NEW_LINE> corner = self.blur_factor / 12.0 <NEW_LINE> adjacent = self.blur_factor / 6.0 <NEW_LINE> window = [[corner, adjacent, corner], [adjacent, center, adjacent], [corner, adjacent, corner]] <NEW_LINE> new_grid = [[0.0 for _ in range(self.wi... | Performs probability blurring of adjacent cells around center using 3x3 window,
if blur factor is 0 nothing changes | 625941e5283ffb24f3c55d1e |
def get_reg(self): <NEW_LINE> <INDENT> self.__check_data() <NEW_LINE> return [i[9] for i in self._data] | Gets the reg column.
Returns
-------
list
Contains the value for each line for the column. | 625941e556b00c62f0f14a7d |
def add_pairing(self, pairing): <NEW_LINE> <INDENT> self.pairings.append(pairing) <NEW_LINE> print(self.pairings) <NEW_LINE> return self.pairings | Add a food pairing to the instance's pairings list. | 625941e5e76e3b2f99f3ac26 |
def AsDict(self): <NEW_LINE> <INDENT> data = {} <NEW_LINE> if self.created_at: <NEW_LINE> <INDENT> data['created_at'] = self.created_at <NEW_LINE> <DEDENT> if self.favorited: <NEW_LINE> <INDENT> data['favorited'] = self.favorited <NEW_LINE> <DEDENT> if self.favorite_count: <NEW_LINE> <INDENT> data['favorite_count'] = s... | A dict representation of this twitter.Status instance.
The return value uses the same key names as the JSON representation.
Return:
A dict representing this twitter.Status instance | 625941e54f6381625f114e5d |
def _get_structured_grad_output(outputs, grads, body_grad_graph): <NEW_LINE> <INDENT> result = [] <NEW_LINE> outputs_idx = 2 <NEW_LINE> structured_outputs_idx = 2 <NEW_LINE> for g in grads: <NEW_LINE> <INDENT> if g is None: <NEW_LINE> <INDENT> result.append(None) <NEW_LINE> continue <NEW_LINE> <DEDENT> output = body_gr... | Returns the values that should be returned from the while grad function.
Args:
outputs: the raw Tensor outputs of the grad While op.
grads: the input gradients to the gradient function.
body_grad_graph: _WhileBodyGradFuncGraph.
Returns:
A list of gradient values. May include Nones. | 625941e5d99f1b3c44c679a8 |
def get_recipient_document_visibility_with_http_info(self, account_id, envelope_id, recipient_id, **kwargs): <NEW_LINE> <INDENT> all_params = ['account_id', 'envelope_id', 'recipient_id'] <NEW_LINE> all_params.append('callback') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_prelo... | Returns document visibility for the recipients
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_recipient_do... | 625941e531939e2706e4d285 |
def test_message_model(self): <NEW_LINE> <INDENT> m = Message( text="testtesttest", user_id=self.uid ) <NEW_LINE> db.session.add(m) <NEW_LINE> db.session.commit() <NEW_LINE> self.assertEqual(m.text, "testtesttest") <NEW_LINE> self.assertEqual(self.u.messages[0].text, "testtesttest") <NEW_LINE> self.assertEqual(len(self... | Does the basic model work | 625941e55166f23b2e1a557a |
def __init__(self, ratio, weights_init, sparse_axes, sparse_init=None): <NEW_LINE> <INDENT> if sparse_init is None: <NEW_LINE> <INDENT> sparse_init = ZeroInit() <NEW_LINE> <DEDENT> self.ratio = ratio <NEW_LINE> self.weights_init = weights_init <NEW_LINE> self.sparse_axes = sparse_axes <NEW_LINE> self.sparse_init = spar... | original motivation: hard limit the number of non-zero incoming
connection weights to each unit
from "Deep learning via Hessian-free optimization" 2010
ratio: fraction of non-sparse values along the sparse axis
weights_init: initialization scheme to use for non-sparse entries
sparse_axes: axes along which each has ... | 625941e585dfad0860c3b27d |
def node_style_basic(): <NEW_LINE> <INDENT> style = ete3.NodeStyle() <NEW_LINE> style["fgcolor"] = "#000000" <NEW_LINE> style["size"] = 0 <NEW_LINE> style["vt_line_color"] = "#000000" <NEW_LINE> style["hz_line_color"] = "#000000" <NEW_LINE> style["vt_line_width"] = 1 <NEW_LINE> style["hz_line_width"] = 1 <NEW_LINE> sty... | It generates a NodeStyle
:return: ETE3 NodeStyle Object | 625941e57cff6e4e81117da6 |
def testsecs(self): <NEW_LINE> <INDENT> self.assertEqual(len(self.data.etsecs), self.number) <NEW_LINE> lowestEtrans = self.data.etsecs[1] <NEW_LINE> sumofsec = sum([z for (x, y, z) in lowestEtrans]) <NEW_LINE> self.assertInside(sumofsec, 1.0, 0.16) | Is the sum of etsecs close to 1? | 625941e5e1aae11d1e74a0dc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.