function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def _sync_group_initial(
self,
resource_group_name: str,
lab_name: str,
**kwargs: Any | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def begin_sync_group(
self,
resource_group_name: str,
lab_name: str,
**kwargs: Any | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {}) | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def __init__(self, json_data):
self.messages = [NexmoMessage(data) for data in json_data['messages']]
self.message_count = len(self.messages)
self.total_price = sum(msg.message_price for msg in self.messages)
self.remaining_balance = min(msg.remaining_balance for msg in self.messages) | thibault/libnexmo | [
1,
3,
1,
1,
1415285478
] |
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 4 | aurarad/auroracoin | [
33,
27,
33,
8,
1458336048
] |
def setUpModule():
make_data_files(BAM_DATADIR)
make_data_files(TABIX_DATADIR) | pysam-developers/pysam | [
639,
249,
639,
248,
1391632690
] |
def testCount(self):
nread = _compile_test.testCountBAM(
pysam.Samfile(self.input_filename))
self.assertEqual(nread, 3270) | pysam-developers/pysam | [
639,
249,
639,
248,
1391632690
] |
def testCount(self):
nread = _compile_test.testCountGTF(
pysam.Tabixfile(self.input_filename))
self.assertEqual(nread, 237) | pysam-developers/pysam | [
639,
249,
639,
248,
1391632690
] |
def read_as(cls, message):
body = cls()
body.ParseFromString(message.payload)
return body | madedotcom/photon-pump | [
49,
10,
49,
30,
1493299344
] |
def event_appeared(
commit_position=1,
prepare_position=1,
event_number=10,
event_id=None,
type="some-event",
data=None,
stream="stream-123", | madedotcom/photon-pump | [
49,
10,
49,
30,
1493299344
] |
def __init__(self, stream=None):
self.result = msg.ReadStreamResult.Success
self.next_event_number = 10
self.last_event_number = 9
self.is_end_of_stream = False
self.last_commit_position = 8
self.stream = stream or "some-stream"
self.events = [] | madedotcom/photon-pump | [
49,
10,
49,
30,
1493299344
] |
def with_next_event_number(self, num):
self.next_event_number = num
return self | madedotcom/photon-pump | [
49,
10,
49,
30,
1493299344
] |
def with_event(
self,
event_number=10,
event_id=None,
type="some-event",
data=None,
link_event_number=None, | madedotcom/photon-pump | [
49,
10,
49,
30,
1493299344
] |
def build(self):
response = proto.ReadStreamEventsCompleted()
response.result = self.result
response.next_event_number = self.next_event_number
response.last_event_number = self.last_event_number
response.is_end_of_stream = self.is_end_of_stream
response.last_commit_position = self.last_commit_position
response.events.extend(self.events)
return (
msg.TcpCommand.ReadStreamEventsForwardCompleted,
response.SerializeToString(),
) | madedotcom/photon-pump | [
49,
10,
49,
30,
1493299344
] |
def test_to_matrix():
x = np.ones((4, 2))
mat = to_matrix(x)
assert mat.numRows == 4
assert mat.numCols == 2 | maxpumperla/elephas | [
1562,
311,
1562,
7,
1439467759
] |
def test_from_vector():
x = np.ones((3,))
vector = to_vector(x)
assert len(vector) == 3 | maxpumperla/elephas | [
1562,
311,
1562,
7,
1439467759
] |
def toDict(self):
raise NotImplementedError() | szredinger/graph-constr-group-testing | [
1,
1,
1,
1,
1377597643
] |
def toDict(self):
return {} | szredinger/graph-constr-group-testing | [
1,
1,
1,
1,
1377597643
] |
def __init__(self, rendererMapping):
self._renderers = rendererMapping or {}
for k, v in self._renderers.iteritems():
if v is None:
self._renderers[k] = lambda x: x.toDict()
self.results = []
self.headers = set({}) | szredinger/graph-constr-group-testing | [
1,
1,
1,
1,
1377597643
] |
def _add_headers(self, rendered):
for k in rendered:
self.headers.add(k) | szredinger/graph-constr-group-testing | [
1,
1,
1,
1,
1377597643
] |
def _join(self, *args):
return ".".join(args) | szredinger/graph-constr-group-testing | [
1,
1,
1,
1,
1377597643
] |
def __init__(self):
self.variable_dict = {} | szredinger/graph-constr-group-testing | [
1,
1,
1,
1,
1377597643
] |
def get_var(self, var):
return self.variable_dict[var] | szredinger/graph-constr-group-testing | [
1,
1,
1,
1,
1377597643
] |
def toDict(self):
return self.variable_dict | szredinger/graph-constr-group-testing | [
1,
1,
1,
1,
1377597643
] |
def __init__(self, problem_description, tester, *args, **kwargs):
raise NotImplementedError() | szredinger/graph-constr-group-testing | [
1,
1,
1,
1,
1377597643
] |
def __init__(self, problem_description, tester, *args, **kwargs):
"""
:param problem_description: graph constrained combinatorial problem description
:type problem_description: base_types.Problem
:param tester: tester object which will test all paths
:type tester: base_types.PathTester
"""
self.problem_description = problem_description
self.graph = self.problem_description.problem_graph.graph
self.source = self.problem_description.problem_graph.source
self.sink = self.problem_description.problem_graph.sink
self.tester = tester | szredinger/graph-constr-group-testing | [
1,
1,
1,
1,
1377597643
] |
def volatile(
service: str = typer.Argument(
...,
help="Service name",
shell_complete=Application.autocomplete_allservice,
),
command: str = typer.Argument(
"bash", help="UNIX command to be executed on selected running service"
),
user: str = typer.Option(
None,
"--user",
"-u",
help="User existing in selected service",
show_default=False,
), | rapydo/do | [
11,
3,
11,
11,
1495096286
] |
def __init__(self, directory):
"""
Arguments:
directory - Directory of documents to be searched.
"""
self.corpus = os.listdir(directory)
self.text = {}
for f in self.corpus:
f = os.path.join(directory,f)
with open(f) as doc:
info = doc.read()
self.text[f] = info | Jverma/InfoR | [
10,
4,
10,
1,
1408408278
] |
def word_freq(self, wordlist):
"""
Build a dictionary of words with the frequencies of their occurance in the document.
Arguments:
document : A list of all the words in a document.
Returns:
A dictionary containing all the words in the document with their frequencies. | Jverma/InfoR | [
10,
4,
10,
1,
1408408278
] |
def vocabalury(self):
"""
All the words in the corpus.
Returns:
A list of all the words in the corpus.
"""
allWords = []
allDocs = self.text
for d in allDocs.keys():
d = allDocs[d]
docWords = self.words(d)
allWords.extend(docWords)
return allWords | Jverma/InfoR | [
10,
4,
10,
1,
1408408278
] |
def docScore(self, document, query, k, b):
"""
Compute the log odds ratio of the document being relevant to the query.
Arguments: | Jverma/InfoR | [
10,
4,
10,
1,
1408408278
] |
def ranking(self, query, k, b):
"""
Ranking of the documents based on their relevance to the query.
Arguments:
query: The search query
Returns:
A dictionary of all the documents in the corpus with their corresponding relevance odds ratio.
"""
if (k != None):
k = k
else:
k = 0
if (b != None):
b = b
else:
b = 0
documents = self.text
rankingDict = defaultdict(float)
for d in documents.keys():
docText = documents[d]
score = self.docScore(docText, query, k, b)
rankingDict[d] = score
return rankingDict | Jverma/InfoR | [
10,
4,
10,
1,
1408408278
] |
def prepare_related(self):
return self.prefetch_related('concepts') | adaptive-learning/proso-apps | [
1,
8,
1,
33,
1409148971
] |
def to_json(self, nested=False):
data = {
"id": self.pk,
"object_type": "tag",
"type": self.type,
"value": self.value,
"lang": self.lang,
"type_name": self.type_name,
"value_name": self.value_name,
}
if not nested:
data["concepts"] = [concept.to_json(nested=True) for concept in self.concepts.all()]
return data | adaptive-learning/proso-apps | [
1,
8,
1,
33,
1409148971
] |
def prepare_related(self):
return self.prefetch_related('tags', 'actions') | adaptive-learning/proso-apps | [
1,
8,
1,
33,
1409148971
] |
def get_concept_item_mapping(self, concepts=None, lang=None):
"""
Get mapping of concepts to items belonging to concept.
Args:
concepts (list of Concept): Defaults to None meaning all concepts
lang (str): language of concepts, if None use language of concepts
Returns:
dict: concept (int) -> list of item ids (int)
"""
if concepts is None:
concepts = self.filter(active=True)
if lang is not None:
concepts = concepts.filter(lang=lang)
if lang is None:
languages = set([concept.lang for concept in concepts])
if len(languages) > 1:
raise Exception('Concepts has multiple languages')
lang = list(languages)[0]
item_lists = Item.objects.filter_all_reachable_leaves_many([json.loads(concept.query)
for concept in concepts], lang)
return dict(zip([c.pk for c in concepts], item_lists)) | adaptive-learning/proso-apps | [
1,
8,
1,
33,
1409148971
] |
def get_item_concept_mapping(self, lang):
""" Get mapping of items_ids to concepts containing these items
Args:
lang (str): language of concepts
Returns:
dict: item (int) -> set of concepts (int)
"""
concepts = self.filter(active=True, lang=lang)
return group_keys_by_value_lists(Concept.objects.get_concept_item_mapping(concepts, lang)) | adaptive-learning/proso-apps | [
1,
8,
1,
33,
1409148971
] |
def has_time_expired(self, cache_time, last_answer_time, lower_bound, expiration_factor):
cache_timedelta = cache_time - last_answer_time
if cache_timedelta > timedelta(days=365):
return False
if cache_timedelta < timedelta(hours=lower_bound):
return False
return cache_timedelta < expiration_factor * (datetime.now() - cache_time) | adaptive-learning/proso-apps | [
1,
8,
1,
33,
1409148971
] |
def to_json(self, nested=False):
data = {
"id": self.pk,
"object_type": "concept",
"identifier": self.identifier,
"name": self.name,
"query": self.query,
"lang": self.lang,
}
if not nested:
data["tags"] = [tag.to_json(nested=True) for tag in self.tags.all()]
data["actions"] = [action.to_json(nested=True) for action in self.actions.all()]
return data | adaptive-learning/proso-apps | [
1,
8,
1,
33,
1409148971
] |
def create_identifier(query):
"""
Crete identifier of concept
Args:
query (str): query defining concept
Returns:
str: identifier of length 20
"""
return sha1(query.encode()).hexdigest()[:20] | adaptive-learning/proso-apps | [
1,
8,
1,
33,
1409148971
] |
def __repr__(self):
return "{}-{}".format(self.identifier, self.lang) | adaptive-learning/proso-apps | [
1,
8,
1,
33,
1409148971
] |
def prepare_related(self):
return self.select_related('concept') | adaptive-learning/proso-apps | [
1,
8,
1,
33,
1409148971
] |
def to_json(self, nested=False):
data = {
"id": self.pk,
"object_type": "action",
"identifier": self.identifier,
"name": self.name,
"url": self.url,
}
if not nested:
data["concept"] = self.concept.to_json(nested=True)
return data | adaptive-learning/proso-apps | [
1,
8,
1,
33,
1409148971
] |
def prepare_related(self):
return self.select_related('concept') | adaptive-learning/proso-apps | [
1,
8,
1,
33,
1409148971
] |
def get_user_stats(self, users, lang=None, concepts=None, since=None, recalculate=True):
"""
Finds all UserStats of given concepts and users.
Recompute UserStats if necessary
Args:
users (Optional[list of users] or [user]): list of primary keys of user or users
Defaults to None meaning all users.
lang (string): use only concepts witch the lang. Defaults to None meaning all languages.
concepts (Optional[list of concepts]): list of primary keys of concepts or concepts
Defaults to None meaning all concepts.
Returns:
dict: user_id -> dict (concept_identifier - > (stat_name -> value)) -- for more users
dict: concept_identifier - > (stat_name -> value) -- for one user
"""
only_one_user = False
if not isinstance(users, list):
users = [users]
only_one_user = True
if recalculate:
if lang is None:
raise ValueError('Recalculation without lang is not supported.')
time_start = time_lib()
concepts_to_recalculate = Concept.objects.get_concepts_to_recalculate(users, lang, concepts)
LOGGER.debug("user_stats - getting identifying concepts to recalculate: %ss", (time_lib() - time_start))
time_start = time_lib()
self.recalculate_concepts(concepts_to_recalculate, lang)
LOGGER.debug("user_stats - recalculating concepts: %ss", (time_lib() - time_start))
qs = self.prepare_related().filter(user__in=users, concept__active=True)
if concepts is not None:
qs = qs.filter(concept__in=concepts)
if lang is not None:
qs = qs.filter(concept__lang=lang)
if since is not None:
qs = qs.filter(time__gte=since)
data = defaultdict(lambda: defaultdict(lambda: {}))
for user_stat in qs:
data[user_stat.user_id][user_stat.concept.identifier][user_stat.stat] = user_stat.value
if only_one_user:
return data[users[0].pk if type(users[0]) == User else users[0]]
return data | adaptive-learning/proso-apps | [
1,
8,
1,
33,
1409148971
] |
def __str__(self):
return "{} - {}: {}".format(self.stat, self.concept, self.value) | adaptive-learning/proso-apps | [
1,
8,
1,
33,
1409148971
] |
def socket(self):
"The socket for this connection" | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def encode(self, msg):
"""Encode a message for transmission."""
return msg.encode(self.transmit_encoding) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def __init__(self, reactor):
super().__init__(reactor)
self.features = features.FeatureSet() | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def connect(
self,
server,
port,
nickname,
password=None,
username=None,
ircname=None,
connect_factory=connection.Factory(), | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def reconnect(self):
"""
Reconnect with the last arguments passed to self.connect()
"""
self.connect(*self._saved_connect.args, **self._saved_connect.kwargs) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def get_server_name(self):
"""Get the (real) server name.
This method returns the (real) server name, or, more
specifically, what the server calls itself.
"""
return self.real_server_name or "" | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def as_nick(self, name):
"""
Set the nick for the duration of the context.
"""
orig = self.get_nickname()
self.nick(name)
try:
yield orig
finally:
self.nick(orig) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def _process_line(self, line):
event = Event("all_raw_messages", self.get_server_name(), None, [line])
self._handle_event(event)
grp = _rfc_1459_command_regexp.match(line).group
source = NickMask.from_group(grp("prefix"))
command = self._command_from_group(grp("command"))
arguments = message.Arguments.from_group(grp('argument'))
tags = message.Tag.from_group(grp('tags'))
if source and not self.real_server_name:
self.real_server_name = source
if command == "nick":
if source.nick == self.real_nickname:
self.real_nickname = arguments[0]
elif command == "welcome":
# Record the nickname in case the client changed nick
# in a nicknameinuse callback.
self.real_nickname = arguments[0]
elif command == "featurelist":
self.features.load(arguments)
handler = (
self._handle_message
if command in ["privmsg", "notice"]
else self._handle_other
)
handler(arguments, command, source, tags) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def _handle_other(self, arguments, command, source, tags):
target = None
if command == "quit":
arguments = [arguments[0]]
elif command == "ping":
target = arguments[0]
else:
target = arguments[0] if arguments else None
arguments = arguments[1:]
if command == "mode":
if not is_channel(target):
command = "umode"
log.debug(
"command: %s, source: %s, target: %s, " "arguments: %s, tags: %s",
command,
source,
target,
arguments,
tags,
)
event = Event(command, source, target, arguments, tags)
self._handle_event(event) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def _command_from_group(group):
command = group.lower()
# Translate numerics into more readable strings.
return events.numeric.get(command, command) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def is_connected(self):
"""Return connection status.
Returns true if connected, otherwise false.
"""
return self.connected | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def remove_global_handler(self, *args):
"""Remove global handler.
See documentation for IRC.remove_global_handler.
"""
self.reactor.remove_global_handler(*args) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def admin(self, server=""):
"""Send an ADMIN command."""
self.send_items('ADMIN', server) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def _multi_parameter(args):
"""
According to the spec::
If more than one capability is named, the RFC1459 designated
sentinel (:) for a multi-parameter argument must be present.
It's not obvious where the sentinel should be present or if it
must be omitted for a single parameter, so follow convention and
only include the sentinel prefixed to the first parameter if more
than one parameter is present.
"""
if len(args) > 1:
return (':' + args[0],) + args[1:]
return args | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def ctcp(self, ctcptype, target, parameter=""):
"""Send a CTCP command."""
ctcptype = ctcptype.upper()
tmpl = "\001{ctcptype} {parameter}\001" if parameter else "\001{ctcptype}\001"
self.privmsg(target, tmpl.format(**vars())) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def disconnect(self, message=""):
"""Hang up the connection.
Arguments:
message -- Quit message.
"""
try:
del self.connected
except AttributeError:
return
self.quit(message)
try:
self.socket.shutdown(socket.SHUT_WR)
self.socket.close()
except socket.error:
pass
del self.socket
self._handle_event(Event("disconnect", self.server, "", [message])) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def info(self, server=""):
"""Send an INFO command."""
self.send_items('INFO', server) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def ison(self, nicks):
"""Send an ISON command.
Arguments:
nicks -- List of nicks.
"""
self.send_items('ISON', *tuple(nicks)) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def kick(self, channel, nick, comment=""):
"""Send a KICK command."""
self.send_items('KICK', channel, nick, comment and ':' + comment) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def list(self, channels=None, server=""):
"""Send a LIST command."""
self.send_items('LIST', ','.join(always_iterable(channels)), server) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def mode(self, target, command):
"""Send a MODE command."""
self.send_items('MODE', target, command) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def names(self, channels=None):
"""Send a NAMES command."""
self.send_items('NAMES', ','.join(always_iterable(channels))) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def notice(self, target, text):
"""Send a NOTICE command."""
# Should limit len(text) here!
self.send_items('NOTICE', target, ':' + text) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def part(self, channels, message=""):
"""Send a PART command."""
self.send_items('PART', ','.join(always_iterable(channels)), message) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def ping(self, target, target2=""):
"""Send a PING command."""
self.send_items('PING', target, target2) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def privmsg(self, target, text):
"""Send a PRIVMSG command."""
self.send_items('PRIVMSG', target, ':' + text) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def quit(self, message=""):
"""Send a QUIT command."""
# Note that many IRC servers don't use your QUIT message
# unless you've been connected for at least 5 minutes!
self.send_items('QUIT', message and ':' + message) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def send_items(self, *items):
"""
Send all non-empty items, separated by spaces.
"""
self.send_raw(' '.join(filter(None, items))) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def squit(self, server, comment=""):
"""Send an SQUIT command."""
self.send_items('SQUIT', server, comment and ':' + comment) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def time(self, server=""):
"""Send a TIME command."""
self.send_items('TIME', server) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def trace(self, target=""):
"""Send a TRACE command."""
self.send_items('TRACE', target) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def userhost(self, nicks):
"""Send a USERHOST command."""
self.send_items('USERHOST', ",".join(nicks)) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def version(self, server=""):
"""Send a VERSION command."""
self.send_items('VERSION', server) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def who(self, target="", op=""):
"""Send a WHO command."""
self.send_items('WHO', target, op and 'o') | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def whowas(self, nick, max="", server=""):
"""Send a WHOWAS command."""
self.send_items('WHOWAS', nick, max, server) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def set_keepalive(self, interval):
"""
Set a keepalive to occur every `interval` on this `ServerConnection`.
:param interval: `int` in seconds, or `datetime.timedelta`
"""
pinger = functools.partial(self.ping, 'keep-alive')
self.reactor.scheduler.execute_every(period=interval, func=pinger) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def __lt__(self, other):
"when sorting prioritized handlers, only use the priority"
return self.priority < other.priority | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def __do_nothing(*args, **kwargs):
pass | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def server(self):
"""Creates and returns a ServerConnection object."""
conn = self.connection_class(self)
with self.mutex:
self.connections.append(conn)
return conn | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def process_timeout(self):
"""Called when a timeout notification is due.
See documentation for Reactor.__init__.
"""
with self.mutex:
self.scheduler.run_pending() | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def sockets(self):
with self.mutex:
return [
conn.socket
for conn in self.connections
if conn is not None and conn.socket is not None
] | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def process_forever(self, timeout=0.2):
"""Run an infinite loop, processing data from connections.
This method repeatedly calls process_once.
Arguments:
timeout -- Parameter to pass to process_once.
"""
# This loop should specifically *not* be mutex-locked.
# Otherwise no other thread would ever be able to change
# the shared state of a Reactor object running this function.
log.debug("process_forever(timeout=%s)", timeout)
one = functools.partial(self.process_once, timeout=timeout)
consume(repeatfunc(one)) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def add_global_handler(self, event, handler, priority=0):
"""Adds a global handler function for a specific event type.
Arguments:
event -- Event type (a string). Check the values of
numeric_events for possible event types.
handler -- Callback function taking 'connection' and 'event'
parameters.
priority -- A number (the lower number, the higher priority).
The handler function is called whenever the specified event is
triggered in any of the connections. See documentation for
the Event class.
The handler functions are called in priority order (lowest
number is highest priority). If a handler function returns
"NO MORE", no more handlers will be called.
"""
handler = PrioritizedHandler(priority, handler)
with self.mutex:
event_handlers = self.handlers.setdefault(event, [])
bisect.insort(event_handlers, handler) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def dcc(self, dcctype="chat"):
"""Creates and returns a DCCConnection object.
Arguments:
dcctype -- "chat" for DCC CHAT connections or "raw" for
DCC SEND (or other DCC types). If "chat",
incoming data will be split in newline-separated
chunks. If "raw", incoming data is not touched.
"""
with self.mutex:
conn = DCCConnection(self, dcctype)
self.connections.append(conn)
return conn | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def _remove_connection(self, connection):
"""[Internal]"""
with self.mutex:
self.connections.remove(connection)
self._on_disconnect(connection.socket) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def __init__(self, reactor, dcctype):
super().__init__(reactor)
self.dcctype = dcctype | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def listen(self, addr=None):
"""Wait for a connection/reconnection from a DCC peer.
Returns the DCCConnection object.
The local IP address and port are available as
self.localaddress and self.localport. After connection from a
peer, the peer address and port are available as
self.peeraddress and self.peerport.
"""
self.buffer = buffer.LineBuffer()
self.handlers = {}
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.passive = True
default_addr = socket.gethostbyname(socket.gethostname()), 0
try:
self.socket.bind(addr or default_addr)
self.localaddress, self.localport = self.socket.getsockname()
self.socket.listen(10)
except socket.error as x:
raise DCCConnectionError("Couldn't bind socket: %s" % x)
return self | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def process_data(self):
"""[Internal]"""
if self.passive and not self.connected:
conn, (self.peeraddress, self.peerport) = self.socket.accept()
self.socket.close()
self.socket = conn
self.connected = True
log.debug("DCC connection from %s:%d", self.peeraddress, self.peerport)
self.reactor._handle_event(
self, Event("dcc_connect", self.peeraddress, None, None)
)
return
try:
new_data = self.socket.recv(2**14)
except socket.error:
# The server hung up.
self.disconnect("Connection reset by peer")
return
if not new_data:
# Read nothing: connection must be down.
self.disconnect("Connection reset by peer")
return
if self.dcctype == "chat":
self.buffer.feed(new_data)
chunks = list(self.buffer)
if len(self.buffer) > 2**14:
# Bad peer! Naughty peer!
log.info(
"Received >16k from a peer without a newline; " "disconnecting."
)
self.disconnect()
return
else:
chunks = [new_data]
command = "dccmsg"
prefix = self.peeraddress
target = None
for chunk in chunks:
log.debug("FROM PEER: %s", chunk)
arguments = [chunk]
log.debug(
"command: %s, source: %s, target: %s, arguments: %s",
command,
prefix,
target,
arguments,
)
event = Event(command, prefix, target, arguments)
self.reactor._handle_event(self, event) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def send_bytes(self, bytes):
"""
Send data to DCC peer.
"""
try:
self.socket.send(bytes)
log.debug("TO PEER: %r\n", bytes)
except socket.error:
self.disconnect("Connection reset by peer.") | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def __init__(self):
self.reactor = self.reactor_class()
self.connection = self.reactor.server()
self.dcc_connections = []
self.reactor.add_global_handler("all_events", self._dispatcher, -10)
self.reactor.add_global_handler("dcc_disconnect", self._dcc_disconnect, -10) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def do_nothing(connection, event):
return None | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def _dcc_disconnect(self, connection, event):
self.dcc_connections.remove(connection) | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def dcc(self, *args, **kwargs):
"""Create and associate a new DCCConnection object.
Use the returned object to listen for or connect to
a DCC peer.
"""
dcc = self.reactor.dcc(*args, **kwargs)
self.dcc_connections.append(dcc)
return dcc | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
def dcc_listen(self, dcctype="chat"):
"""Listen for connections from a DCC peer.
Returns a DCCConnection instance.
"""
warnings.warn("Use self.dcc(type).listen()", DeprecationWarning)
return self.dcc(dcctype).listen() | jaraco/irc | [
355,
81,
355,
24,
1448029842
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.