Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|> return data[:-2]
def purge(self):
self._buffer.seek(0)
self._buffer.truncate()
self.bytes_written = 0
self.bytes_read = 0
def close(self):
try:
self.purge()
self._buffer.close()
except:
# i... | 'EXECABORT': ExecAbortError, |
Based on the snippet: <|code_start|>
def purge(self):
self._buffer.seek(0)
self._buffer.truncate()
self.bytes_written = 0
self.bytes_read = 0
def close(self):
try:
self.purge()
self._buffer.close()
except:
# issue #633 suggests... | 'LOADING': BusyLoadingError, |
Using the snippet: <|code_start|> def purge(self):
self._buffer.seek(0)
self._buffer.truncate()
self.bytes_written = 0
self.bytes_read = 0
def close(self):
try:
self.purge()
self._buffer.close()
except:
# issue #633 suggests the... | 'NOSCRIPT': NoScriptError, |
Here is a snippet: <|code_start|> self._buffer.seek(0)
self._buffer.truncate()
self.bytes_written = 0
self.bytes_read = 0
def close(self):
try:
self.purge()
self._buffer.close()
except:
# issue #633 suggests the purge/close somehow ... | 'READONLY': ReadOnlyError, |
Given snippet: <|code_start|> pass
self._buffer = None
self._sock = None
class BaseParser:
"""Plain Python parsing class"""
EXCEPTION_CLASSES = {
'ERR': {
'max number of clients reached': ConnectionError
},
'EXECABORT': ExecAbortError,
'L... | exception_class = exception_class.get(response, ResponseError) |
Given the following code snippet before the placeholder: <|code_start|>
def on_connect(self, connection):
"""Called when the stream connects"""
self._stream = connection._reader
self._buffer = SocketBuffer(self._stream, self._read_size)
if connection.decode_responses:
sel... | raise InvalidResponse("Protocol Error: %s, %s" % |
Given the following code snippet before the placeholder: <|code_start|> self._buffer.truncate()
self.bytes_written = 0
self.bytes_read = 0
def close(self):
try:
self.purge()
self._buffer.close()
except:
# issue #633 suggests the purge/close... | 'ASK': AskError, |
Given the code snippet: <|code_start|> self.bytes_read = 0
def close(self):
try:
self.purge()
self._buffer.close()
except:
# issue #633 suggests the purge/close somehow raised a
# BadFileDescriptor error. Perhaps the client ran out of
... | 'MOVED': MovedError, |
Given the code snippet: <|code_start|> self.bytes_written = 0
self.bytes_read = 0
def close(self):
try:
self.purge()
self._buffer.close()
except:
# issue #633 suggests the purge/close somehow raised a
# BadFileDescriptor error. Perhaps ... | 'TRYAGAIN': TryAgainError, |
Given snippet: <|code_start|>
def close(self):
try:
self.purge()
self._buffer.close()
except:
# issue #633 suggests the purge/close somehow raised a
# BadFileDescriptor error. Perhaps the client ran out of
# memory or something else? It's p... | 'CLUSTERDOWN': ClusterDownError, |
Using the snippet: <|code_start|> def close(self):
try:
self.purge()
self._buffer.close()
except:
# issue #633 suggests the purge/close somehow raised a
# BadFileDescriptor error. Perhaps the client ran out of
# memory or something else? It'... | 'CROSSSLOT': ClusterCrossSlotError, |
Given the code snippet: <|code_start|>
try:
HIREDIS_AVAILABLE = True
except ImportError:
HIREDIS_AVAILABLE = False
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.comp... | SYM_STAR = b('*') |
Given snippet: <|code_start|> if not self.is_connected:
await self.connect()
return self._parser.can_read()
async def connect(self):
try:
await self._connect()
except aredis.compat.CancelledError:
raise
except Exception as exc:
... | if nativestr(await self.read_response()) != 'OK': |
Given the following code snippet before the placeholder: <|code_start|>
try:
HIREDIS_AVAILABLE = True
except ImportError:
HIREDIS_AVAILABLE = False
SYM_STAR = b('*')
SYM_DOLLAR = b('$')
SYM_CRLF = b('\r\n')
SYM_LF = b('\n')
SYM_EMPTY = b('')
async def exec_with_timeout(coroutine, timeout, *, loop=None):
... | if LOOP_DEPRECATED: |
Continue the code snippet: <|code_start|> string_keys_to_dict(
'BITCOUNT BITPOS DECRBY GETBIT INCRBY '
'STRLEN SETBIT', int
),
{
'INCRBYFLOAT': float,
'MSET': bool_ok,
'SET': lambda r: r and nativestr(r) == 'OK',
}
)
asy... | raise RedisError("Both start and end must be specified") |
Continue the code snippet: <|code_start|> return await self.execute_command('SETNX', name, value)
async def setrange(self, name, offset, value):
"""
Overwrite bytes in the value of ``name`` starting at ``offset`` with
``value``. If ``offset`` plus the length of ``value`` exceeds the
... | 'BITOP': NodeFlag.BLOCKED |
Based on the snippet: <|code_start|> self._command_stack.extend(['INCRBY', type, offset, increment])
return self
def overflow(self, type='SAT'):
"""
fine-tune the behavior of the increment or decrement overflow,
have no effect unless used before `incrby`
three types a... | 'SET': lambda r: r and nativestr(r) == 'OK', |
Continue the code snippet: <|code_start|> """
# An alias for ``incr()``, because it is already implemented
# as INCRBY redis command.
return await self.incr(name, amount)
async def incrbyfloat(self, name, amount=1.0):
"""
Increments the value at key ``name`` by float... | for pair in iteritems(kwargs): |
Here is a snippet: <|code_start|> return await self.execute_command('GETSET', name, value)
async def incr(self, name, amount=1):
"""
Increments the value of ``key`` by ``amount``. If no key exists,
the value will be initialized as ``amount``
"""
return await self.exe... | args = list_or_args(keys, args) |
Continue the code snippet: <|code_start|> def get(self, type, offset):
"""
Returns the specified bit field.
"""
self._command_stack.extend(['GET', type, offset])
return self
def incrby(self, type, offset, increment):
"""
Increments or decrements (if a nega... | RESPONSE_CALLBACKS = dict_merge( |
Here is a snippet: <|code_start|> """
self._command_stack.extend(['INCRBY', type, offset, increment])
return self
def overflow(self, type='SAT'):
"""
fine-tune the behavior of the increment or decrement overflow,
have no effect unless used before `incrby`
thre... | 'MSET': bool_ok, |
Predict the next line after this snippet: <|code_start|> """
Returns the specified bit field.
"""
self._command_stack.extend(['GET', type, offset])
return self
def incrby(self, type, offset, increment):
"""
Increments or decrements (if a negative increment is ... | string_keys_to_dict( |
Predict the next line for this snippet: <|code_start|>"""Internal messages used by mailbox processors. Do not import or use.
"""
TSource = TypeVar("TSource")
TOther = TypeVar("TOther")
Key = NewType("Key", int)
class Msg(SupportsMatch[TSource], ABC):
"""Message base class."""
@dataclass
<|code_end|>
with t... | class SourceMsg(Msg[Notification[TSource]], SupportsMatch[TSource]): |
Given snippet: <|code_start|>@dataclass
class OtherMsg(Msg[Notification[TOther]], SupportsMatch[TOther]):
value: Notification[TOther]
def __match__(self, pattern: Any) -> Iterable[Notification[TOther]]:
origin: Any = get_origin(pattern)
try:
if isinstance(self, origin or pattern):
... | class InnerObservableMsg(Msg[AsyncObservable[TSource]], SupportsMatch[AsyncObservable[TSource]]): |
Continue the code snippet: <|code_start|>
class MyException(Exception):
pass
@pytest.yield_fixture() # type:ignore
def event_loop() -> Generator[Any, Any, Any]:
<|code_end|>
. Use current file imports:
import asyncio
import aioreactive as rx
import pytest
from typing import Any, Generator
from aioreactive.tes... | loop = VirtualTimeEventLoop() |
Given the following code snippet before the placeholder: <|code_start|>
await message_loop(running=True)
agent = MailboxProcessor.start(worker)
async def asend(value: TSource) -> None:
agent.post(OnNext(value))
async def athrow(ex: Exception) -> None:
agent.post(OnError(ex))
... | if isinstance(cmd, DisposableMsg): |
Given the code snippet: <|code_start|> return AsyncAnonymousObserver(asend, athrow, aclose)
def auto_detach_observer(
obv: AsyncObserver[TSource],
) -> Tuple[AsyncObserver[TSource], Callable[[Awaitable[AsyncDisposable]], Awaitable[AsyncDisposable]]]:
cts = CancellationTokenSource()
token = cts.token
... | agent.post(DisposeMsg) |
Predict the next line for this snippet: <|code_start|> await disposable.dispose_async()
await msg.accept_observer(obv)
running = False
else:
await disposable.dispose_async()
await obv.aclose()
... | async def worker(inbox: MailboxProcessor[Msg[TSource]]): |
Given the following code snippet before the placeholder: <|code_start|>
async def athrow(self, error: Exception) -> None:
await self._fn(OnError(error))
async def aclose(self) -> None:
await self._fn(OnCompleted)
def noop() -> AsyncObserver[Any]:
return AsyncAnonymousObserver(anoop, anoop... | if msg.kind == MsgKind.ON_NEXT: |
Using the snippet: <|code_start|>
def __init__(
self,
asend: Callable[[TSource], Awaitable[None]] = anoop,
athrow: Callable[[Exception], Awaitable[None]] = anoop,
aclose: Callable[[], Awaitable[None]] = anoop,
) -> None:
super().__init__()
assert iscoroutinefuncti... | def __init__(self, fn: Callable[[Notification[TSource]], Awaitable[None]]) -> None: |
Based on the snippet: <|code_start|>
assert iscoroutinefunction(athrow)
self._athrow = athrow
assert iscoroutinefunction(aclose)
self._aclose = aclose
async def asend(self, value: TSource) -> None:
await self._asend(value)
async def athrow(self, error: Exception) -> No... | await self._fn(OnCompleted) |
Based on the snippet: <|code_start|> super().__init__()
assert iscoroutinefunction(asend)
self._asend = asend
assert iscoroutinefunction(athrow)
self._athrow = athrow
assert iscoroutinefunction(aclose)
self._aclose = aclose
async def asend(self, value: TSour... | await self._fn(OnError(error)) |
Here is a snippet: <|code_start|> athrow: Callable[[Exception], Awaitable[None]] = anoop,
aclose: Callable[[], Awaitable[None]] = anoop,
) -> None:
super().__init__()
assert iscoroutinefunction(asend)
self._asend = asend
assert iscoroutinefunction(athrow)
self... | await self._fn(OnNext(value)) |
Given the code snippet: <|code_start|>
log = logging.getLogger(__name__)
TSource = TypeVar("TSource")
class AsyncIteratorObserver(AsyncObserver[TSource], AsyncIterable[TSource], AsyncDisposable):
"""An async observer that might be iterated asynchronously."""
<|code_end|>
, generate the next line using the imp... | def __init__(self, source: AsyncObservable[TSource]) -> None: |
Given snippet: <|code_start|> self._pull.set_result(True)
# Wake up any awaiters
for awaiter in self._awaiters[:1]:
awaiter.set_result(True)
return value
async def dispose_async(self) -> None:
if self._subscription is not None:
await self._subscriptio... | asend: Callable[[TSource], Awaitable[None]] = anoop, |
Predict the next line after this snippet: <|code_start|>
TSource = TypeVar("TSource")
log = logging.getLogger(__name__)
def canceller() -> Tuple[AsyncDisposable, CancellationToken]:
cts = CancellationTokenSource()
async def cancel() -> None:
log.debug("cancller, cancelling!")
cts.cancel()
... | return AsyncAnonymousObservable(subscribe) |
Given the code snippet: <|code_start|>
TSource = TypeVar("TSource")
log = logging.getLogger(__name__)
def canceller() -> Tuple[AsyncDisposable, CancellationToken]:
cts = CancellationTokenSource()
async def cancel() -> None:
log.debug("cancller, cancelling!")
cts.cancel()
return AsyncD... | def create(subscribe: Callable[[AsyncObserver[TSource]], Awaitable[AsyncDisposable]]) -> AsyncObservable[TSource]: |
Based on the snippet: <|code_start|>log = logging.getLogger(__name__)
def canceller() -> Tuple[AsyncDisposable, CancellationToken]:
cts = CancellationTokenSource()
async def cancel() -> None:
log.debug("cancller, cancelling!")
cts.cancel()
return AsyncDisposable.create(cancel), cts.token... | safe_obv = safe_observer(aobv, disposable) |
Continue the code snippet: <|code_start|>
TSource = TypeVar("TSource")
log = logging.getLogger(__name__)
def canceller() -> Tuple[AsyncDisposable, CancellationToken]:
cts = CancellationTokenSource()
async def cancel() -> None:
log.debug("cancller, cancelling!")
cts.cancel()
return Asy... | def create(subscribe: Callable[[AsyncObserver[TSource]], Awaitable[AsyncDisposable]]) -> AsyncObservable[TSource]: |
Given snippet: <|code_start|>
TSource = TypeVar("TSource")
log = logging.getLogger(__name__)
def noop(*args: Any, **kw: Any) -> None:
"""No operation. Returns nothing"""
pass
async def anoop(value: Optional[Any] = None):
"""Async no operation. Returns nothing"""
pass
<|code_end|>
, continue by p... | class NoopObserver(AsyncObserver[TSource]): |
Predict the next line for this snippet: <|code_start|>
log = logging.getLogger(__name__)
TSource = TypeVar("TSource")
async def run(
<|code_end|>
with the help of current file imports:
import asyncio
import logging
from typing import Awaitable, Callable, Optional, TypeVar
from expression.system.disposable import... | source: AsyncObservable[TSource], observer: Optional[AsyncAwaitableObserver[TSource]] = None, timeout: int = 2 |
Predict the next line after this snippet: <|code_start|>
log = logging.getLogger(__name__)
TSource = TypeVar("TSource")
async def run(
<|code_end|>
using the current file's imports:
import asyncio
import logging
from typing import Awaitable, Callable, Optional, TypeVar
from expression.system.disposable import As... | source: AsyncObservable[TSource], observer: Optional[AsyncAwaitableObserver[TSource]] = None, timeout: int = 2 |
Here is a snippet: <|code_start|>
log = logging.getLogger(__name__)
TSource = TypeVar("TSource")
async def run(
source: AsyncObservable[TSource], observer: Optional[AsyncAwaitableObserver[TSource]] = None, timeout: int = 2
) -> TSource:
"""Run the source with the given observer.
Similar to `subscribe_... | obv: AsyncObserver[TSource] = observer or AsyncAwaitableObserver() |
Continue the code snippet: <|code_start|>
Uses a custom subscribe method.
"""
def __init__(self, subscribe: Callable[[AsyncObserver[TSource]], Awaitable[AsyncDisposable]]) -> None:
self._subscribe = subscribe
async def subscribe_async(self, observer: AsyncObserver[TSource]) -> AsyncDisposable:... | return AsyncIteratorObserver(self) |
Here is a snippet: <|code_start|>
TSource = TypeVar("TSource")
TResult = TypeVar("TResult")
TOther = TypeVar("TOther")
TError = TypeVar("TError")
T1 = TypeVar("T1")
T2 = TypeVar("T2")
log = logging.getLogger(__name__)
<|code_end|>
. Write the next line using the current file imports:
import logging
from typing im... | class AsyncAnonymousObservable(AsyncObservable[TSource]): |
Predict the next line after this snippet: <|code_start|>
TSource = TypeVar("TSource")
TResult = TypeVar("TResult")
TOther = TypeVar("TOther")
TError = TypeVar("TError")
T1 = TypeVar("T1")
T2 = TypeVar("T2")
log = logging.getLogger(__name__)
class AsyncAnonymousObservable(AsyncObservable[TSource]):
"""An anony... | def __init__(self, subscribe: Callable[[AsyncObserver[TSource]], Awaitable[AsyncDisposable]]) -> None: |
Predict the next line after this snippet: <|code_start|>
TSource = TypeVar("TSource")
TMessage = TypeVar("TMessage")
class MsgKind(Enum):
ON_NEXT = 1
ON_ERROR = 2
ON_COMPLETED = 3
class Notification(Generic[TSource], ABC):
"""Represents a message to a mailbox processor."""
def __init__(self, ... | async def accept_observer(self, obv: AsyncObserver[TSource]) -> None: |
Based on the snippet: <|code_start|>
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
@pytest.yield_fixture() # type: ignore
def event_loop():
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
import logging
import aioreactive as rx
import pytest
from... | loop = VirtualTimeEventLoop() |
Here is a snippet: <|code_start|>
TSource = TypeVar("TSource")
def to_async_iterable(source: AsyncObservable[TSource]) -> AsyncIterable[TSource]:
"""Convert async observable to async iterable.
Args:
count: The number of elements to skip before returning the
remaining values.
Returns... | return AsyncIterableObservable(source) |
Here is a snippet: <|code_start|> pass
# for use in policy match element reducing
elif item == 'source_zones':
return self.src_zones
elif item == 'destination_zones':
return self.dst_zones
elif item == 'source_addresses':
return set(flatten... | for a in value if is_ipv4(a)] |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
class BasePolicy(BaseObject):
Action = enum('ALLOW', 'DENY', 'REJECT', 'DROP')
Logging = enum('START', 'END')
<|code_end|>
. Use current file imports:
(from orangengine.utils import is_ipv4, enum, bidict, flatten
from orangengine.models.base impo... | ActionMap = bidict({ |
Based on the snippet: <|code_start|> 'name': self.name,
'source_zones': self.src_zones,
'source_addresses': s_addrs,
'destination_zones': self.dst_zones,
'destination_addresses': d_addrs,
'services': services,
'action': self.ActionMap[se... | return set(flatten([a.value for a in self.src_addresses])) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class JuniperSRXService(BaseService):
def __init__(self, name, protocol=None, port=None):
super(JuniperSRXService, self).__init__(name, protocol, port)
def to_xml(self):
"""Map service objects to juniper SRX config tree elements
... | if isinstance(port, BasePortRange): |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class JuniperSRXService(BaseService):
def __init__(self, name, protocol=None, port=None):
super(JuniperSRXService, self).__init__(name, protocol, port)
def to_xml(self):
"""Map service objects to juniper SRX config tree elements
... | return create_element('destination-port', text=port) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""
juniper driver specific utility functions
"""
# --- begin xml generation functions
def create_new_address(a_value):
if isinstance(a_value, list):
raise ValueError("Creating new address groups is not currently supported")
address_ele... | if is_ipv4(a_value): |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class JuniperSRXServiceGroup(BaseServiceGroup):
def __init__(self, name):
super(JuniperSRXServiceGroup, self).__init__(name)
def to_xml(self):
"""Map service group objects to juniper SRX config tree elements
"""
<|code_e... | servicegroup_element = create_element('application-set') |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
class JuniperSRXAddressGroup(BaseAddressGroup):
def __init__(self, name):
super(JuniperSRXAddressGroup, self).__init__(name)
def to_xml(self):
"""Map address group objects to juniper SRX config tree elements
... | if isinstance(a, BaseAddress): |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
class JuniperSRXAddressGroup(BaseAddressGroup):
def __init__(self, name):
super(JuniperSRXAddressGroup, self).__init__(name)
def to_xml(self):
"""Map address group objects to juniper SRX config tree elements
"""
<|code_end|>
... | addressgroup_element = create_element('address-set') |
Given the following code snippet before the placeholder: <|code_start|> IdentTypes.ICMP6: 'ident-by-icmp6-type',
None: None,
})
WellKnownServiceMap = bidict({
('tcp', 80): 'web-browsing',
('tcp', 443): 'ssl',
('tcp', 22): 'ssh',
('udp', 123): 'ntp',
('tcp'... | self.services.append(BaseService(name="{0}-{1}".format(self.name, port_element), |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
class PaloAltoAddress(BaseAddress):
"""Palo Alto Address
Inherits from BaseAddress and provides access to the underlying pandevice object.
Also provides and mapper for the type field.
"""
<|code_end|>
. Use current file imports:
from... | TypeMap = bidict({ |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
class JuniperSRXAddress(BaseAddress):
def __init__(self, name, value, a_type):
super(JuniperSRXAddress, self).__init__(name, value, a_type)
def to_xml(self):
"""Map address objects to juniper SRX config tree elements
"... | address_element = create_element('address') |
Based on the snippet: <|code_start|> ----------
X : None
currently unused, left for scikit compatibility
y : scipy.sparse
label space of shape :code:`(n_samples, n_labels)`
Returns
-------
arrray of arrays of label indexes (numpy.ndarray)
... | _membership_to_list_of_communities( |
Given snippet: <|code_start|> predictions = classifier.predict(X_test)
"""
def __init__(self, clusterer=None, pass_input_space=False):
super(MatrixLabelSpaceClusterer, self).__init__()
self.clusterer = clusterer
self.pass_input_space = pass_input_space
def fit_predict(self,... | return np.array(_membership_to_list_of_communities(result, 1 + max(result))) |
Given the code snippet: <|code_start|>
class BalancedKMeansClustererTest(ClassifierBaseTest):
def test_actually_works_on_proper_params(self):
for X, y in self.get_multilabel_data_for_tests('sparse'):
assert sp.issparse(y)
<|code_end|>
, generate the next line using the imports in ... | balanced = balancedkmeans.BalancedKMeansClusterer(k=3, it=50) |
Given snippet: <|code_start|>
def get_matrix_clusterers(cluster_count=3):
base_clusterers = [KMeans(cluster_count)]
for base_clusterer in base_clusterers:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import scipy.sparse as sp
from sklearn.cluster impo... | yield MatrixLabelSpaceClusterer(base_clusterer, False) |
Based on the snippet: <|code_start|>
def get_matrix_clusterers(cluster_count=3):
base_clusterers = [KMeans(cluster_count)]
for base_clusterer in base_clusterers:
yield MatrixLabelSpaceClusterer(base_clusterer, False)
<|code_end|>
, predict the immediate next line with the help of imports:
import num... | class MatrixLabelSpaceClustererTests(ClassifierBaseTest): |
Continue the code snippet: <|code_start|>
def get_fixed_clusterers():
cluster_cases = [
# non-overlapping
[[1,2], [0, 3, 4]],
# overlapping
[[1,2,3], [0,3,4]]
]
for clusters in cluster_cases:
clusters = np.array(clusters)
<|code_end|>
. Use current file imports:
im... | yield clusters, FixedLabelSpaceClusterer(clusters=clusters) |
Based on the snippet: <|code_start|>
def get_fixed_clusterers():
cluster_cases = [
# non-overlapping
[[1,2], [0, 3, 4]],
# overlapping
[[1,2,3], [0,3,4]]
]
for clusters in cluster_cases:
clusters = np.array(clusters)
yield clusters, FixedLabelSpaceClusterer(... | class FixedLabelSpaceClustererTests(ClassifierBaseTest): |
Continue the code snippet: <|code_start|>
Parameters
----------
X : array-like or sparse matrix
An input feature matrix of shape :code:`(n_samples, n_features)`
sparse_format: str
Requested format of returned scipy.sparse matrix, if sparse is returned
enfo... | return get_matrix_in_format(X, sparse_format) |
Predict the next line after this snippet: <|code_start|> Requested format of returned scipy.sparse matrix, if sparse is returned
enforce_sparse : bool
Ignore require_dense and enforce sparsity, useful internally
Returns
-------
array-like or sparse matrix
... | return matrix_creation_function_for_format(sparse_format)(X) |
Using the snippet: <|code_start|> ----------
X : currently unused, left for scikit compatibility
y : scipy.sparse
label space of shape :code:`(n_samples, n_labels)`
Returns
-------
array of arrays
numpy array of arrays of label indexes, where each ... | distances.append(_euclidean_distance(v, Centers[i])) |
Given snippet: <|code_start|> Centers =[]
y = y.todense()
for i in range(0, self.k):
auxVector = y[:, random.randint(0, number_of_labels-1)]
Centers.append(np.asarray(auxVector))
#Now we have the clusters created and we need to make each label its corresponding clu... | Centers = _recalculateCenters(np.asarray(y), balancedCluster, self.k) |
Given the following code snippet before the placeholder: <|code_start|> -------
array of arrays
numpy array of arrays of label indexes, where each sub-array
represents labels that are in a separate community
"""
number_of_labels = y.shape[1]
#Assign a label... | numberOfAparitions = _countNumberOfAparitions(balancedCluster, minIndex) |
Predict the next line after this snippet: <|code_start|> if include_self_edges and (normalize_self_edges not in [True, False]):
raise ValueError("Decision whether to normalize self edges needs to be a boolean")
if normalize_self_edges and not include_self_edges:
raise ValueError(... | label_data = get_matrix_in_format(y, 'lil') |
Based on the snippet: <|code_start|> def test_ensure_input_format_returns_sparse_from_sparse_if_required(self):
classifier = ProblemTransformationBase(require_dense=False)
X = sp.csr_matrix(np.zeros((2, 3)))
ensured_X = classifier._ensure_input_format(X)
self.assertTrue(sp.issparse(... | for sparse_format in SPARSE_MATRIX_FORMATS: |
Here is a snippet: <|code_start|> else:
self.assertEqual(y[row][column], y_ensured[row * stride + column])
def dense_and_dense_matrices_are_the_same(self, X, ensured_X):
self.assertEqual(len(X), len(ensured_X))
for row in range(len(X)):
self.assertEqua... | classifier = ProblemTransformationBase( |
Given the following code snippet before the placeholder: <|code_start|>
SPARSE_MATRIX_FORMATS = ["bsr", "coo", "csc", "csr", "dia", "dok", "lil"]
class UtilsTest(unittest.TestCase):
def test_if_get_matrix_ensures_type(self):
matrix = sp.csr_matrix([])
for sparse_format in SPARSE_MATRIX_FORMATS:
... | new_matrix = get_matrix_in_format(matrix, sparse_format) |
Using the snippet: <|code_start|>
SPARSE_MATRIX_FORMATS = ["bsr", "coo", "csc", "csr", "dia", "dok", "lil"]
class UtilsTest(unittest.TestCase):
def test_if_get_matrix_ensures_type(self):
matrix = sp.csr_matrix([])
for sparse_format in SPARSE_MATRIX_FORMATS:
new_matrix = get_matrix_in... | new_matrix = matrix_creation_function_for_format( |
Based on the snippet: <|code_start|> overlap=self.allow_overlap
)
return self._detect_communities()
def _detect_communities(self):
if self.nested:
lowest_level = self.model_.get_levels()[0]
else:
lowest_level = self.model_
number_o... | class GraphToolLabelGraphClusterer(LabelGraphClustererBase): |
Using the snippet: <|code_start|> deg_corr=self.use_degree_correlation,
overlap=self.allow_overlap,
state_args=dict(recs=[weights],
rec_types=[self.weight_model])
)
else:
self.model_ = self._model_fit_function... | return _membership_to_list_of_communities(membership_vector, number_of_communities) |
Given snippet: <|code_start|> self.model_ = self._model_fit_function()(
graph,
deg_corr=self.use_degree_correlation,
overlap=self.allow_overlap,
state_args=dict(recs=[weights],
rec_types=[self.weight_model])
... | return _overlapping_membership_to_list_of_communities(membership_vector, number_of_communities) |
Based on the snippet: <|code_start|> :type path: list or None
:param path:
optional list of path where the module or package should be
searched (use sys.path if nothing or None is given)
:type context_file: str or None
:param context_file:
context file to consider, necessary if the ide... | return spec.ModuleSpec(name='os.path', location=os.path.__file__, module_type=imp.PY_SOURCE) |
Using the snippet: <|code_start|>def check(filenames, select=None, ignore=None, ignore_decorators=None):
"""Generate docstring errors that exist in `filenames` iterable.
By default, the PEP-257 convention is checked. To specifically define the
set of error codes to check for, supply either `select` or `ign... | raise IllegalConfiguration('Cannot pass both select and ignore. ' |
Based on the snippet: <|code_start|> @property
def checks(self):
all = [this_check for this_check in vars(type(self)).values()
if hasattr(this_check, '_check_for')]
return sorted(all, key=lambda this_check: not this_check._terminal)
@check_for(Definition, terminal=True)
de... | Package: violations.D104} |
Predict the next line for this snippet: <|code_start|> definition=definition)
yield error
if this_check._terminal:
terminate = True
break
i... | codes = {Module: violations.D100, |
Here is a snippet: <|code_start|> yield error
if this_check._terminal:
terminate = True
break
if terminate:
break
@property
def checks(self):
all = ... | Class: violations.D101, |
Given the following code snippet before the placeholder: <|code_start|> if this_check._terminal:
terminate = True
break
if terminate:
break
@property
def checks(self):
all = [t... | NestedClass: violations.D106, |
Based on the snippet: <|code_start|> skipping_all = (definition.skipped_error_codes == 'all')
decorator_skip = ignore_decorators is not None and any(
len(ignore_decorators.findall(dec.name)) > 0
for dec in definition.decorators)
... | @check_for(Definition, terminal=True) |
Given snippet: <|code_start|> <generator object check at 0x...>
>>> check(['pydocstyle.py'], select=['D100'])
<generator object check at 0x...>
>>> check(['pydocstyle.py'], ignore=conventions.pep257 - {'D100'})
<generator object check at 0x...>
"""
if select is not None and ignore is not N... | except (EnvironmentError, AllError, ParseError) as error: |
Here is a snippet: <|code_start|> terminate = True
break
if terminate:
break
@property
def checks(self):
all = [this_check for this_check in vars(type(self)).values()
if hasattr(this_check,... | Method: (lambda: violations.D105() if definition.is_magic |
Continue the code snippet: <|code_start|> break
@property
def checks(self):
all = [this_check for this_check in vars(type(self)).values()
if hasattr(this_check, '_check_for')]
return sorted(all, key=lambda this_check: not this_check._terminal)
@check_for(D... | Function: violations.D103, |
Here is a snippet: <|code_start|>
@property
def checks(self):
all = [this_check for this_check in vars(type(self)).values()
if hasattr(this_check, '_check_for')]
return sorted(all, key=lambda this_check: not this_check._terminal)
@check_for(Definition, terminal=True)
def ... | NestedFunction: violations.D103, |
Predict the next line for this snippet: <|code_start|> 'original_index',
'is_last_section'))
# First - create a list of possible contexts. Note that the
# `following_linex` member is until the e... | parse = Parser() |
Continue the code snippet: <|code_start|> f._terminal = terminal
return f
return decorator
class ConventionChecker(object):
"""Checker for PEP 257 and numpy conventions.
D10x: Missing docstrings
D20x: Whitespace issues
D30x: Docstring formatting
D40x: Docstring content issues
... | module = parse(StringIO(source), filename) |
Predict the next line for this snippet: <|code_start|> <generator object check at 0x...>
>>> check(['pydocstyle.py'], select=['D100'])
<generator object check at 0x...>
>>> check(['pydocstyle.py'], ignore=conventions.pep257 - {'D100'})
<generator object check at 0x...>
"""
if select is not... | except (EnvironmentError, AllError, ParseError) as error: |
Predict the next line after this snippet: <|code_start|>
Note that ignored error code refer to the entire set of possible
error codes, which is larger than just the PEP-257 convention. To your
convenience, you may use `pydocstyle.violations.conventions.pep257` as
a base set to add or remove errors from.... | log.info('Checking file %s.', filename) |
Given the code snippet: <|code_start|> error.set_context(explanation=explanation,
definition=definition)
yield error
if this_check._terminal:
terminate = True
... | docstring and is_blank(ast.literal_eval(docstring))): |
Given the following code snippet before the placeholder: <|code_start|> def _suspected_as_section(_line):
result = self._get_leading_words(_line.lower())
return result in lower_section_names
# Finding our suspects.
suspected_section_indices = [i for i, line in enumerate(l... | for a, b in pairwise(contexts, None): |
Here is a snippet: <|code_start|>VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
class AllError(Exception):
"""Raised when there is a problem with __all__ when parsing."""
def __init__(self, message):
"""Initialize the error with a more specific message."""
Exception.__init__(
... | self.log = log |
Using the snippet: <|code_start|> self.code = code
self.short_desc = short_desc
self.context = context
self.parameters = parameters
self.definition = None
self.explanation = None
def set_context(self, definition, explanation):
"""Set the source code context fo... | lines_stripped = list(reversed(list(dropwhile(is_blank, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.