repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
johnbywater/eventsourcing
eventsourcing/infrastructure/base.py
AbstractSequencedItemRecordManager.get_item
def get_item(self, sequence_id, position): """ Gets sequenced item from the datastore. """ return self.from_record(self.get_record(sequence_id, position))
python
def get_item(self, sequence_id, position): """ Gets sequenced item from the datastore. """ return self.from_record(self.get_record(sequence_id, position))
[ "def", "get_item", "(", "self", ",", "sequence_id", ",", "position", ")", ":", "return", "self", ".", "from_record", "(", "self", ".", "get_record", "(", "sequence_id", ",", "position", ")", ")" ]
Gets sequenced item from the datastore.
[ "Gets", "sequenced", "item", "from", "the", "datastore", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/infrastructure/base.py#L55-L59
train
228,700
johnbywater/eventsourcing
eventsourcing/infrastructure/base.py
AbstractSequencedItemRecordManager.get_items
def get_items(self, sequence_id, gt=None, gte=None, lt=None, lte=None, limit=None, query_ascending=True, results_ascending=True): """ Returns sequenced item generator. """ records = self.get_records( sequence_id=sequence_id, gt=gt, gte=gte, lt=lt, lte=lte, limit=limit, query_ascending=query_ascending, results_ascending=results_ascending, ) for item in map(self.from_record, records): yield item
python
def get_items(self, sequence_id, gt=None, gte=None, lt=None, lte=None, limit=None, query_ascending=True, results_ascending=True): """ Returns sequenced item generator. """ records = self.get_records( sequence_id=sequence_id, gt=gt, gte=gte, lt=lt, lte=lte, limit=limit, query_ascending=query_ascending, results_ascending=results_ascending, ) for item in map(self.from_record, records): yield item
[ "def", "get_items", "(", "self", ",", "sequence_id", ",", "gt", "=", "None", ",", "gte", "=", "None", ",", "lt", "=", "None", ",", "lte", "=", "None", ",", "limit", "=", "None", ",", "query_ascending", "=", "True", ",", "results_ascending", "=", "Tru...
Returns sequenced item generator.
[ "Returns", "sequenced", "item", "generator", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/infrastructure/base.py#L67-L84
train
228,701
johnbywater/eventsourcing
eventsourcing/infrastructure/base.py
AbstractSequencedItemRecordManager.to_record
def to_record(self, sequenced_item): """ Constructs a record object from given sequenced item object. """ kwargs = self.get_field_kwargs(sequenced_item) # Supply application_name, if needed. if hasattr(self.record_class, 'application_name'): kwargs['application_name'] = self.application_name # Supply pipeline_id, if needed. if hasattr(self.record_class, 'pipeline_id'): kwargs['pipeline_id'] = self.pipeline_id return self.record_class(**kwargs)
python
def to_record(self, sequenced_item): """ Constructs a record object from given sequenced item object. """ kwargs = self.get_field_kwargs(sequenced_item) # Supply application_name, if needed. if hasattr(self.record_class, 'application_name'): kwargs['application_name'] = self.application_name # Supply pipeline_id, if needed. if hasattr(self.record_class, 'pipeline_id'): kwargs['pipeline_id'] = self.pipeline_id return self.record_class(**kwargs)
[ "def", "to_record", "(", "self", ",", "sequenced_item", ")", ":", "kwargs", "=", "self", ".", "get_field_kwargs", "(", "sequenced_item", ")", "# Supply application_name, if needed.", "if", "hasattr", "(", "self", ".", "record_class", ",", "'application_name'", ")", ...
Constructs a record object from given sequenced item object.
[ "Constructs", "a", "record", "object", "from", "given", "sequenced", "item", "object", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/infrastructure/base.py#L99-L110
train
228,702
johnbywater/eventsourcing
eventsourcing/infrastructure/base.py
AbstractSequencedItemRecordManager.from_record
def from_record(self, record): """ Constructs and returns a sequenced item object, from given ORM object. """ kwargs = self.get_field_kwargs(record) return self.sequenced_item_class(**kwargs)
python
def from_record(self, record): """ Constructs and returns a sequenced item object, from given ORM object. """ kwargs = self.get_field_kwargs(record) return self.sequenced_item_class(**kwargs)
[ "def", "from_record", "(", "self", ",", "record", ")", ":", "kwargs", "=", "self", ".", "get_field_kwargs", "(", "record", ")", "return", "self", ".", "sequenced_item_class", "(", "*", "*", "kwargs", ")" ]
Constructs and returns a sequenced item object, from given ORM object.
[ "Constructs", "and", "returns", "a", "sequenced", "item", "object", "from", "given", "ORM", "object", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/infrastructure/base.py#L112-L117
train
228,703
johnbywater/eventsourcing
eventsourcing/infrastructure/base.py
ACIDRecordManager.get_pipeline_and_notification_id
def get_pipeline_and_notification_id(self, sequence_id, position): """ Returns pipeline ID and notification ID for event at given position in given sequence. """ # Todo: Optimise query by selecting only two columns, pipeline_id and id (notification ID)? record = self.get_record(sequence_id, position) notification_id = getattr(record, self.notification_id_name) return record.pipeline_id, notification_id
python
def get_pipeline_and_notification_id(self, sequence_id, position): """ Returns pipeline ID and notification ID for event at given position in given sequence. """ # Todo: Optimise query by selecting only two columns, pipeline_id and id (notification ID)? record = self.get_record(sequence_id, position) notification_id = getattr(record, self.notification_id_name) return record.pipeline_id, notification_id
[ "def", "get_pipeline_and_notification_id", "(", "self", ",", "sequence_id", ",", "position", ")", ":", "# Todo: Optimise query by selecting only two columns, pipeline_id and id (notification ID)?", "record", "=", "self", ".", "get_record", "(", "sequence_id", ",", "position", ...
Returns pipeline ID and notification ID for event at given position in given sequence.
[ "Returns", "pipeline", "ID", "and", "notification", "ID", "for", "event", "at", "given", "position", "in", "given", "sequence", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/infrastructure/base.py#L194-L202
train
228,704
johnbywater/eventsourcing
eventsourcing/infrastructure/base.py
SQLRecordManager.insert_select_max
def insert_select_max(self): """ SQL statement that inserts records with contiguous IDs, by selecting max ID from indexed table records. """ if self._insert_select_max is None: if hasattr(self.record_class, 'application_name'): # Todo: Maybe make it support application_name without pipeline_id? assert hasattr(self.record_class, 'pipeline_id'), self.record_class tmpl = self._insert_select_max_tmpl + self._where_application_name_tmpl else: tmpl = self._insert_select_max_tmpl self._insert_select_max = self._prepare_insert( tmpl=tmpl, record_class=self.record_class, field_names=list(self.field_names), ) return self._insert_select_max
python
def insert_select_max(self): """ SQL statement that inserts records with contiguous IDs, by selecting max ID from indexed table records. """ if self._insert_select_max is None: if hasattr(self.record_class, 'application_name'): # Todo: Maybe make it support application_name without pipeline_id? assert hasattr(self.record_class, 'pipeline_id'), self.record_class tmpl = self._insert_select_max_tmpl + self._where_application_name_tmpl else: tmpl = self._insert_select_max_tmpl self._insert_select_max = self._prepare_insert( tmpl=tmpl, record_class=self.record_class, field_names=list(self.field_names), ) return self._insert_select_max
[ "def", "insert_select_max", "(", "self", ")", ":", "if", "self", ".", "_insert_select_max", "is", "None", ":", "if", "hasattr", "(", "self", ".", "record_class", ",", "'application_name'", ")", ":", "# Todo: Maybe make it support application_name without pipeline_id?", ...
SQL statement that inserts records with contiguous IDs, by selecting max ID from indexed table records.
[ "SQL", "statement", "that", "inserts", "records", "with", "contiguous", "IDs", "by", "selecting", "max", "ID", "from", "indexed", "table", "records", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/infrastructure/base.py#L236-L253
train
228,705
johnbywater/eventsourcing
eventsourcing/infrastructure/base.py
SQLRecordManager.insert_values
def insert_values(self): """ SQL statement that inserts records without ID. """ if self._insert_values is None: self._insert_values = self._prepare_insert( tmpl=self._insert_values_tmpl, placeholder_for_id=True, record_class=self.record_class, field_names=self.field_names, ) return self._insert_values
python
def insert_values(self): """ SQL statement that inserts records without ID. """ if self._insert_values is None: self._insert_values = self._prepare_insert( tmpl=self._insert_values_tmpl, placeholder_for_id=True, record_class=self.record_class, field_names=self.field_names, ) return self._insert_values
[ "def", "insert_values", "(", "self", ")", ":", "if", "self", ".", "_insert_values", "is", "None", ":", "self", ".", "_insert_values", "=", "self", ".", "_prepare_insert", "(", "tmpl", "=", "self", ".", "_insert_values_tmpl", ",", "placeholder_for_id", "=", "...
SQL statement that inserts records without ID.
[ "SQL", "statement", "that", "inserts", "records", "without", "ID", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/infrastructure/base.py#L270-L281
train
228,706
johnbywater/eventsourcing
eventsourcing/infrastructure/base.py
SQLRecordManager.insert_tracking_record
def insert_tracking_record(self): """ SQL statement that inserts tracking records. """ if self._insert_tracking_record is None: self._insert_tracking_record = self._prepare_insert( tmpl=self._insert_values_tmpl, placeholder_for_id=True, record_class=self.tracking_record_class, field_names=self.tracking_record_field_names, ) return self._insert_tracking_record
python
def insert_tracking_record(self): """ SQL statement that inserts tracking records. """ if self._insert_tracking_record is None: self._insert_tracking_record = self._prepare_insert( tmpl=self._insert_values_tmpl, placeholder_for_id=True, record_class=self.tracking_record_class, field_names=self.tracking_record_field_names, ) return self._insert_tracking_record
[ "def", "insert_tracking_record", "(", "self", ")", ":", "if", "self", ".", "_insert_tracking_record", "is", "None", ":", "self", ".", "_insert_tracking_record", "=", "self", ".", "_prepare_insert", "(", "tmpl", "=", "self", ".", "_insert_values_tmpl", ",", "plac...
SQL statement that inserts tracking records.
[ "SQL", "statement", "that", "inserts", "tracking", "records", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/infrastructure/base.py#L284-L295
train
228,707
johnbywater/eventsourcing
eventsourcing/contrib/paxos/application.py
PaxosAggregate.start
def start(cls, originator_id, quorum_size, network_uid): """ Factory method that returns a new Paxos aggregate. """ assert isinstance(quorum_size, int), "Not an integer: {}".format(quorum_size) return cls.__create__( event_class=cls.Started, originator_id=originator_id, quorum_size=quorum_size, network_uid=network_uid )
python
def start(cls, originator_id, quorum_size, network_uid): """ Factory method that returns a new Paxos aggregate. """ assert isinstance(quorum_size, int), "Not an integer: {}".format(quorum_size) return cls.__create__( event_class=cls.Started, originator_id=originator_id, quorum_size=quorum_size, network_uid=network_uid )
[ "def", "start", "(", "cls", ",", "originator_id", ",", "quorum_size", ",", "network_uid", ")", ":", "assert", "isinstance", "(", "quorum_size", ",", "int", ")", ",", "\"Not an integer: {}\"", ".", "format", "(", "quorum_size", ")", "return", "cls", ".", "__c...
Factory method that returns a new Paxos aggregate.
[ "Factory", "method", "that", "returns", "a", "new", "Paxos", "aggregate", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/contrib/paxos/application.py#L105-L115
train
228,708
johnbywater/eventsourcing
eventsourcing/contrib/paxos/application.py
PaxosAggregate.propose_value
def propose_value(self, value, assume_leader=False): """ Proposes a value to the network. """ if value is None: raise ValueError("Not allowed to propose value None") paxos = self.paxos_instance paxos.leader = assume_leader msg = paxos.propose_value(value) if msg is None: msg = paxos.prepare() self.setattrs_from_paxos(paxos) self.announce(msg) return msg
python
def propose_value(self, value, assume_leader=False): """ Proposes a value to the network. """ if value is None: raise ValueError("Not allowed to propose value None") paxos = self.paxos_instance paxos.leader = assume_leader msg = paxos.propose_value(value) if msg is None: msg = paxos.prepare() self.setattrs_from_paxos(paxos) self.announce(msg) return msg
[ "def", "propose_value", "(", "self", ",", "value", ",", "assume_leader", "=", "False", ")", ":", "if", "value", "is", "None", ":", "raise", "ValueError", "(", "\"Not allowed to propose value None\"", ")", "paxos", "=", "self", ".", "paxos_instance", "paxos", "...
Proposes a value to the network.
[ "Proposes", "a", "value", "to", "the", "network", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/contrib/paxos/application.py#L117-L130
train
228,709
johnbywater/eventsourcing
eventsourcing/contrib/paxos/application.py
PaxosAggregate.receive_message
def receive_message(self, msg): """ Responds to messages from other participants. """ if isinstance(msg, Resolution): return paxos = self.paxos_instance while msg: if isinstance(msg, Resolution): self.print_if_verbose("{} resolved value {}".format(self.network_uid, msg.value)) break else: self.print_if_verbose("{} <- {} <- {}".format(self.network_uid, msg.__class__.__name__, msg.from_uid)) msg = paxos.receive(msg) # Todo: Make it optional not to announce resolution (without which it's hard to see final value). do_announce_resolution = True if msg and (do_announce_resolution or not isinstance(msg, Resolution)): self.announce(msg) self.setattrs_from_paxos(paxos)
python
def receive_message(self, msg): """ Responds to messages from other participants. """ if isinstance(msg, Resolution): return paxos = self.paxos_instance while msg: if isinstance(msg, Resolution): self.print_if_verbose("{} resolved value {}".format(self.network_uid, msg.value)) break else: self.print_if_verbose("{} <- {} <- {}".format(self.network_uid, msg.__class__.__name__, msg.from_uid)) msg = paxos.receive(msg) # Todo: Make it optional not to announce resolution (without which it's hard to see final value). do_announce_resolution = True if msg and (do_announce_resolution or not isinstance(msg, Resolution)): self.announce(msg) self.setattrs_from_paxos(paxos)
[ "def", "receive_message", "(", "self", ",", "msg", ")", ":", "if", "isinstance", "(", "msg", ",", "Resolution", ")", ":", "return", "paxos", "=", "self", ".", "paxos_instance", "while", "msg", ":", "if", "isinstance", "(", "msg", ",", "Resolution", ")", ...
Responds to messages from other participants.
[ "Responds", "to", "messages", "from", "other", "participants", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/contrib/paxos/application.py#L132-L151
train
228,710
johnbywater/eventsourcing
eventsourcing/contrib/paxos/application.py
PaxosAggregate.announce
def announce(self, msg): """ Announces a Paxos message. """ self.print_if_verbose("{} -> {}".format(self.network_uid, msg.__class__.__name__)) self.__trigger_event__( event_class=self.MessageAnnounced, msg=msg, )
python
def announce(self, msg): """ Announces a Paxos message. """ self.print_if_verbose("{} -> {}".format(self.network_uid, msg.__class__.__name__)) self.__trigger_event__( event_class=self.MessageAnnounced, msg=msg, )
[ "def", "announce", "(", "self", ",", "msg", ")", ":", "self", ".", "print_if_verbose", "(", "\"{} -> {}\"", ".", "format", "(", "self", ".", "network_uid", ",", "msg", ".", "__class__", ".", "__name__", ")", ")", "self", ".", "__trigger_event__", "(", "e...
Announces a Paxos message.
[ "Announces", "a", "Paxos", "message", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/contrib/paxos/application.py#L153-L161
train
228,711
johnbywater/eventsourcing
eventsourcing/contrib/paxos/application.py
PaxosAggregate.setattrs_from_paxos
def setattrs_from_paxos(self, paxos): """ Registers changes of attribute value on Paxos instance. """ changes = {} for name in self.paxos_variables: paxos_value = getattr(paxos, name) if paxos_value != getattr(self, name, None): self.print_if_verbose("{} {}: {}".format(self.network_uid, name, paxos_value)) changes[name] = paxos_value setattr(self, name, paxos_value) if changes: self.__trigger_event__( event_class=self.AttributesChanged, changes=changes )
python
def setattrs_from_paxos(self, paxos): """ Registers changes of attribute value on Paxos instance. """ changes = {} for name in self.paxos_variables: paxos_value = getattr(paxos, name) if paxos_value != getattr(self, name, None): self.print_if_verbose("{} {}: {}".format(self.network_uid, name, paxos_value)) changes[name] = paxos_value setattr(self, name, paxos_value) if changes: self.__trigger_event__( event_class=self.AttributesChanged, changes=changes )
[ "def", "setattrs_from_paxos", "(", "self", ",", "paxos", ")", ":", "changes", "=", "{", "}", "for", "name", "in", "self", ".", "paxos_variables", ":", "paxos_value", "=", "getattr", "(", "paxos", ",", "name", ")", "if", "paxos_value", "!=", "getattr", "(...
Registers changes of attribute value on Paxos instance.
[ "Registers", "changes", "of", "attribute", "value", "on", "Paxos", "instance", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/contrib/paxos/application.py#L163-L178
train
228,712
johnbywater/eventsourcing
eventsourcing/contrib/paxos/application.py
PaxosProcess.propose_value
def propose_value(self, key, value, assume_leader=False): """ Starts new Paxos aggregate and proposes a value for a key. Decorated with retry in case of notification log conflict or operational error. """ assert isinstance(key, UUID) paxos_aggregate = PaxosAggregate.start( originator_id=key, quorum_size=self.quorum_size, network_uid=self.name ) msg = paxos_aggregate.propose_value(value, assume_leader=assume_leader) while msg: msg = paxos_aggregate.receive_message(msg) new_events = paxos_aggregate.__batch_pending_events__() self.record_process_event(ProcessEvent(new_events)) self.repository.take_snapshot(paxos_aggregate.id) self.publish_prompt() return paxos_aggregate
python
def propose_value(self, key, value, assume_leader=False): """ Starts new Paxos aggregate and proposes a value for a key. Decorated with retry in case of notification log conflict or operational error. """ assert isinstance(key, UUID) paxos_aggregate = PaxosAggregate.start( originator_id=key, quorum_size=self.quorum_size, network_uid=self.name ) msg = paxos_aggregate.propose_value(value, assume_leader=assume_leader) while msg: msg = paxos_aggregate.receive_message(msg) new_events = paxos_aggregate.__batch_pending_events__() self.record_process_event(ProcessEvent(new_events)) self.repository.take_snapshot(paxos_aggregate.id) self.publish_prompt() return paxos_aggregate
[ "def", "propose_value", "(", "self", ",", "key", ",", "value", ",", "assume_leader", "=", "False", ")", ":", "assert", "isinstance", "(", "key", ",", "UUID", ")", "paxos_aggregate", "=", "PaxosAggregate", ".", "start", "(", "originator_id", "=", "key", ","...
Starts new Paxos aggregate and proposes a value for a key. Decorated with retry in case of notification log conflict or operational error.
[ "Starts", "new", "Paxos", "aggregate", "and", "proposes", "a", "value", "for", "a", "key", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/contrib/paxos/application.py#L203-L223
train
228,713
johnbywater/eventsourcing
eventsourcing/contrib/paxos/composable.py
MessageHandler.receive
def receive(self, msg): ''' Message dispatching function. This function accepts any PaxosMessage subclass and calls the appropriate handler function ''' handler = getattr(self, 'receive_' + msg.__class__.__name__.lower(), None) if handler is None: raise InvalidMessageError('Receiving class does not support messages of type: ' + msg.__class__.__name__) return handler(msg)
python
def receive(self, msg): ''' Message dispatching function. This function accepts any PaxosMessage subclass and calls the appropriate handler function ''' handler = getattr(self, 'receive_' + msg.__class__.__name__.lower(), None) if handler is None: raise InvalidMessageError('Receiving class does not support messages of type: ' + msg.__class__.__name__) return handler(msg)
[ "def", "receive", "(", "self", ",", "msg", ")", ":", "handler", "=", "getattr", "(", "self", ",", "'receive_'", "+", "msg", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", ",", "None", ")", "if", "handler", "is", "None", ":", "raise", "I...
Message dispatching function. This function accepts any PaxosMessage subclass and calls the appropriate handler function
[ "Message", "dispatching", "function", ".", "This", "function", "accepts", "any", "PaxosMessage", "subclass", "and", "calls", "the", "appropriate", "handler", "function" ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/contrib/paxos/composable.py#L176-L184
train
228,714
johnbywater/eventsourcing
eventsourcing/contrib/paxos/composable.py
Proposer.propose_value
def propose_value(self, value): ''' Sets the proposal value for this node iff this node is not already aware of a previous proposal value. If the node additionally believes itself to be the current leader, an Accept message will be returned ''' if self.proposed_value is None: self.proposed_value = value if self.leader: self.current_accept_msg = Accept(self.network_uid, self.proposal_id, value) return self.current_accept_msg
python
def propose_value(self, value): ''' Sets the proposal value for this node iff this node is not already aware of a previous proposal value. If the node additionally believes itself to be the current leader, an Accept message will be returned ''' if self.proposed_value is None: self.proposed_value = value if self.leader: self.current_accept_msg = Accept(self.network_uid, self.proposal_id, value) return self.current_accept_msg
[ "def", "propose_value", "(", "self", ",", "value", ")", ":", "if", "self", ".", "proposed_value", "is", "None", ":", "self", ".", "proposed_value", "=", "value", "if", "self", ".", "leader", ":", "self", ".", "current_accept_msg", "=", "Accept", "(", "se...
Sets the proposal value for this node iff this node is not already aware of a previous proposal value. If the node additionally believes itself to be the current leader, an Accept message will be returned
[ "Sets", "the", "proposal", "value", "for", "this", "node", "iff", "this", "node", "is", "not", "already", "aware", "of", "a", "previous", "proposal", "value", ".", "If", "the", "node", "additionally", "believes", "itself", "to", "be", "the", "current", "le...
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/contrib/paxos/composable.py#L210-L221
train
228,715
johnbywater/eventsourcing
eventsourcing/contrib/paxos/composable.py
Proposer.prepare
def prepare(self): ''' Returns a new Prepare message with a proposal id higher than that of any observed proposals. A side effect of this method is to clear the leader flag if it is currently set. ''' self.leader = False self.promises_received = set() self.nacks_received = set() self.proposal_id = ProposalID(self.highest_proposal_id.number + 1, self.network_uid) self.highest_proposal_id = self.proposal_id self.current_prepare_msg = Prepare(self.network_uid, self.proposal_id) return self.current_prepare_msg
python
def prepare(self): ''' Returns a new Prepare message with a proposal id higher than that of any observed proposals. A side effect of this method is to clear the leader flag if it is currently set. ''' self.leader = False self.promises_received = set() self.nacks_received = set() self.proposal_id = ProposalID(self.highest_proposal_id.number + 1, self.network_uid) self.highest_proposal_id = self.proposal_id self.current_prepare_msg = Prepare(self.network_uid, self.proposal_id) return self.current_prepare_msg
[ "def", "prepare", "(", "self", ")", ":", "self", ".", "leader", "=", "False", "self", ".", "promises_received", "=", "set", "(", ")", "self", ".", "nacks_received", "=", "set", "(", ")", "self", ".", "proposal_id", "=", "ProposalID", "(", "self", ".", ...
Returns a new Prepare message with a proposal id higher than that of any observed proposals. A side effect of this method is to clear the leader flag if it is currently set.
[ "Returns", "a", "new", "Prepare", "message", "with", "a", "proposal", "id", "higher", "than", "that", "of", "any", "observed", "proposals", ".", "A", "side", "effect", "of", "this", "method", "is", "to", "clear", "the", "leader", "flag", "if", "it", "is"...
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/contrib/paxos/composable.py#L223-L237
train
228,716
johnbywater/eventsourcing
eventsourcing/contrib/paxos/composable.py
Proposer.receive_nack
def receive_nack(self, msg): ''' Returns a new Prepare message if the number of Nacks received reaches a quorum. ''' self.observe_proposal(msg.promised_proposal_id) if msg.proposal_id == self.proposal_id and self.nacks_received is not None: self.nacks_received.add(msg.from_uid) if len(self.nacks_received) == self.quorum_size: return self.prepare()
python
def receive_nack(self, msg): ''' Returns a new Prepare message if the number of Nacks received reaches a quorum. ''' self.observe_proposal(msg.promised_proposal_id) if msg.proposal_id == self.proposal_id and self.nacks_received is not None: self.nacks_received.add(msg.from_uid) if len(self.nacks_received) == self.quorum_size: return self.prepare()
[ "def", "receive_nack", "(", "self", ",", "msg", ")", ":", "self", ".", "observe_proposal", "(", "msg", ".", "promised_proposal_id", ")", "if", "msg", ".", "proposal_id", "==", "self", ".", "proposal_id", "and", "self", ".", "nacks_received", "is", "not", "...
Returns a new Prepare message if the number of Nacks received reaches a quorum.
[ "Returns", "a", "new", "Prepare", "message", "if", "the", "number", "of", "Nacks", "received", "reaches", "a", "quorum", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/contrib/paxos/composable.py#L251-L262
train
228,717
johnbywater/eventsourcing
eventsourcing/contrib/paxos/composable.py
Proposer.receive_promise
def receive_promise(self, msg): ''' Returns an Accept messages if a quorum of Promise messages is achieved ''' self.observe_proposal(msg.proposal_id) if not self.leader and msg.proposal_id == self.proposal_id and msg.from_uid not in self.promises_received: self.promises_received.add(msg.from_uid) if self.highest_accepted_id is None or msg.last_accepted_id > self.highest_accepted_id: self.highest_accepted_id = msg.last_accepted_id if msg.last_accepted_value is not None: self.proposed_value = msg.last_accepted_value if len(self.promises_received) == self.quorum_size: self.leader = True if self.proposed_value is not None: self.current_accept_msg = Accept(self.network_uid, self.proposal_id, self.proposed_value) return self.current_accept_msg
python
def receive_promise(self, msg): ''' Returns an Accept messages if a quorum of Promise messages is achieved ''' self.observe_proposal(msg.proposal_id) if not self.leader and msg.proposal_id == self.proposal_id and msg.from_uid not in self.promises_received: self.promises_received.add(msg.from_uid) if self.highest_accepted_id is None or msg.last_accepted_id > self.highest_accepted_id: self.highest_accepted_id = msg.last_accepted_id if msg.last_accepted_value is not None: self.proposed_value = msg.last_accepted_value if len(self.promises_received) == self.quorum_size: self.leader = True if self.proposed_value is not None: self.current_accept_msg = Accept(self.network_uid, self.proposal_id, self.proposed_value) return self.current_accept_msg
[ "def", "receive_promise", "(", "self", ",", "msg", ")", ":", "self", ".", "observe_proposal", "(", "msg", ".", "proposal_id", ")", "if", "not", "self", ".", "leader", "and", "msg", ".", "proposal_id", "==", "self", ".", "proposal_id", "and", "msg", ".", ...
Returns an Accept messages if a quorum of Promise messages is achieved
[ "Returns", "an", "Accept", "messages", "if", "a", "quorum", "of", "Promise", "messages", "is", "achieved" ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/contrib/paxos/composable.py#L264-L284
train
228,718
johnbywater/eventsourcing
eventsourcing/contrib/paxos/composable.py
Acceptor.receive_prepare
def receive_prepare(self, msg): ''' Returns either a Promise or a Nack in response. The Acceptor's state must be persisted to disk prior to transmitting the Promise message. ''' if self.promised_id is None or msg.proposal_id >= self.promised_id: self.promised_id = msg.proposal_id return Promise(self.network_uid, msg.from_uid, self.promised_id, self.accepted_id, self.accepted_value) else: return Nack(self.network_uid, msg.from_uid, msg.proposal_id, self.promised_id)
python
def receive_prepare(self, msg): ''' Returns either a Promise or a Nack in response. The Acceptor's state must be persisted to disk prior to transmitting the Promise message. ''' if self.promised_id is None or msg.proposal_id >= self.promised_id: self.promised_id = msg.proposal_id return Promise(self.network_uid, msg.from_uid, self.promised_id, self.accepted_id, self.accepted_value) else: return Nack(self.network_uid, msg.from_uid, msg.proposal_id, self.promised_id)
[ "def", "receive_prepare", "(", "self", ",", "msg", ")", ":", "if", "self", ".", "promised_id", "is", "None", "or", "msg", ".", "proposal_id", ">=", "self", ".", "promised_id", ":", "self", ".", "promised_id", "=", "msg", ".", "proposal_id", "return", "Pr...
Returns either a Promise or a Nack in response. The Acceptor's state must be persisted to disk prior to transmitting the Promise message.
[ "Returns", "either", "a", "Promise", "or", "a", "Nack", "in", "response", ".", "The", "Acceptor", "s", "state", "must", "be", "persisted", "to", "disk", "prior", "to", "transmitting", "the", "Promise", "message", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/contrib/paxos/composable.py#L310-L319
train
228,719
johnbywater/eventsourcing
eventsourcing/contrib/paxos/composable.py
Acceptor.receive_accept
def receive_accept(self, msg): ''' Returns either an Accepted or Nack message in response. The Acceptor's state must be persisted to disk prior to transmitting the Accepted message. ''' if self.promised_id is None or msg.proposal_id >= self.promised_id: self.promised_id = msg.proposal_id self.accepted_id = msg.proposal_id self.accepted_value = msg.proposal_value return Accepted(self.network_uid, msg.proposal_id, msg.proposal_value) else: return Nack(self.network_uid, msg.from_uid, msg.proposal_id, self.promised_id)
python
def receive_accept(self, msg): ''' Returns either an Accepted or Nack message in response. The Acceptor's state must be persisted to disk prior to transmitting the Accepted message. ''' if self.promised_id is None or msg.proposal_id >= self.promised_id: self.promised_id = msg.proposal_id self.accepted_id = msg.proposal_id self.accepted_value = msg.proposal_value return Accepted(self.network_uid, msg.proposal_id, msg.proposal_value) else: return Nack(self.network_uid, msg.from_uid, msg.proposal_id, self.promised_id)
[ "def", "receive_accept", "(", "self", ",", "msg", ")", ":", "if", "self", ".", "promised_id", "is", "None", "or", "msg", ".", "proposal_id", ">=", "self", ".", "promised_id", ":", "self", ".", "promised_id", "=", "msg", ".", "proposal_id", "self", ".", ...
Returns either an Accepted or Nack message in response. The Acceptor's state must be persisted to disk prior to transmitting the Accepted message.
[ "Returns", "either", "an", "Accepted", "or", "Nack", "message", "in", "response", ".", "The", "Acceptor", "s", "state", "must", "be", "persisted", "to", "disk", "prior", "to", "transmitting", "the", "Accepted", "message", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/contrib/paxos/composable.py#L321-L332
train
228,720
johnbywater/eventsourcing
eventsourcing/contrib/paxos/composable.py
Learner.receive_accepted
def receive_accepted(self, msg): ''' Called when an Accepted message is received from an acceptor. Once the final value is determined, the return value of this method will be a Resolution message containing the consentual value. Subsequent calls after the resolution is chosen will continue to add new Acceptors to the final_acceptors set and return Resolution messages. ''' if self.final_value is not None: if msg.proposal_id >= self.final_proposal_id and msg.proposal_value == self.final_value: self.final_acceptors.add(msg.from_uid) return Resolution(self.network_uid, self.final_value) last_pn = self.acceptors.get(msg.from_uid) if last_pn is not None and msg.proposal_id <= last_pn: return # Old message self.acceptors[msg.from_uid] = msg.proposal_id if last_pn is not None: # String proposal_key, need string keys for JSON. proposal_key = str(last_pn) ps = self.proposals[proposal_key] ps.retain_count -= 1 ps.acceptors.remove(msg.from_uid) if ps.retain_count == 0: del self.proposals[proposal_key] # String proposal_key, need string keys for JSON. proposal_key = str(msg.proposal_id) if not proposal_key in self.proposals: self.proposals[proposal_key] = ProposalStatus(msg.proposal_value) ps = self.proposals[proposal_key] assert msg.proposal_value == ps.value, 'Value mismatch for single proposal!' ps.accept_count += 1 ps.retain_count += 1 ps.acceptors.add(msg.from_uid) if ps.accept_count == self.quorum_size: self.final_proposal_id = msg.proposal_id self.final_value = msg.proposal_value self.final_acceptors = ps.acceptors self.proposals = None self.acceptors = None return Resolution(self.network_uid, self.final_value)
python
def receive_accepted(self, msg): ''' Called when an Accepted message is received from an acceptor. Once the final value is determined, the return value of this method will be a Resolution message containing the consentual value. Subsequent calls after the resolution is chosen will continue to add new Acceptors to the final_acceptors set and return Resolution messages. ''' if self.final_value is not None: if msg.proposal_id >= self.final_proposal_id and msg.proposal_value == self.final_value: self.final_acceptors.add(msg.from_uid) return Resolution(self.network_uid, self.final_value) last_pn = self.acceptors.get(msg.from_uid) if last_pn is not None and msg.proposal_id <= last_pn: return # Old message self.acceptors[msg.from_uid] = msg.proposal_id if last_pn is not None: # String proposal_key, need string keys for JSON. proposal_key = str(last_pn) ps = self.proposals[proposal_key] ps.retain_count -= 1 ps.acceptors.remove(msg.from_uid) if ps.retain_count == 0: del self.proposals[proposal_key] # String proposal_key, need string keys for JSON. proposal_key = str(msg.proposal_id) if not proposal_key in self.proposals: self.proposals[proposal_key] = ProposalStatus(msg.proposal_value) ps = self.proposals[proposal_key] assert msg.proposal_value == ps.value, 'Value mismatch for single proposal!' ps.accept_count += 1 ps.retain_count += 1 ps.acceptors.add(msg.from_uid) if ps.accept_count == self.quorum_size: self.final_proposal_id = msg.proposal_id self.final_value = msg.proposal_value self.final_acceptors = ps.acceptors self.proposals = None self.acceptors = None return Resolution(self.network_uid, self.final_value)
[ "def", "receive_accepted", "(", "self", ",", "msg", ")", ":", "if", "self", ".", "final_value", "is", "not", "None", ":", "if", "msg", ".", "proposal_id", ">=", "self", ".", "final_proposal_id", "and", "msg", ".", "proposal_value", "==", "self", ".", "fi...
Called when an Accepted message is received from an acceptor. Once the final value is determined, the return value of this method will be a Resolution message containing the consentual value. Subsequent calls after the resolution is chosen will continue to add new Acceptors to the final_acceptors set and return Resolution messages.
[ "Called", "when", "an", "Accepted", "message", "is", "received", "from", "an", "acceptor", ".", "Once", "the", "final", "value", "is", "determined", "the", "return", "value", "of", "this", "method", "will", "be", "a", "Resolution", "message", "containing", "...
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/contrib/paxos/composable.py#L360-L408
train
228,721
johnbywater/eventsourcing
eventsourcing/utils/topic.py
resolve_topic
def resolve_topic(topic): """Return class described by given topic. Args: topic: A string describing a class. Returns: A class. Raises: TopicResolutionError: If there is no such class. """ try: module_name, _, class_name = topic.partition('#') module = importlib.import_module(module_name) except ImportError as e: raise TopicResolutionError("{}: {}".format(topic, e)) try: cls = resolve_attr(module, class_name) except AttributeError as e: raise TopicResolutionError("{}: {}".format(topic, e)) return cls
python
def resolve_topic(topic): """Return class described by given topic. Args: topic: A string describing a class. Returns: A class. Raises: TopicResolutionError: If there is no such class. """ try: module_name, _, class_name = topic.partition('#') module = importlib.import_module(module_name) except ImportError as e: raise TopicResolutionError("{}: {}".format(topic, e)) try: cls = resolve_attr(module, class_name) except AttributeError as e: raise TopicResolutionError("{}: {}".format(topic, e)) return cls
[ "def", "resolve_topic", "(", "topic", ")", ":", "try", ":", "module_name", ",", "_", ",", "class_name", "=", "topic", ".", "partition", "(", "'#'", ")", "module", "=", "importlib", ".", "import_module", "(", "module_name", ")", "except", "ImportError", "as...
Return class described by given topic. Args: topic: A string describing a class. Returns: A class. Raises: TopicResolutionError: If there is no such class.
[ "Return", "class", "described", "by", "given", "topic", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/utils/topic.py#L18-L39
train
228,722
johnbywater/eventsourcing
eventsourcing/utils/topic.py
resolve_attr
def resolve_attr(obj, path): """A recursive version of getattr for navigating dotted paths. Args: obj: An object for which we want to retrieve a nested attribute. path: A dot separated string containing zero or more attribute names. Returns: The attribute referred to by obj.a1.a2.a3... Raises: AttributeError: If there is no such attribute. """ if not path: return obj head, _, tail = path.partition('.') head_obj = getattr(obj, head) return resolve_attr(head_obj, tail)
python
def resolve_attr(obj, path): """A recursive version of getattr for navigating dotted paths. Args: obj: An object for which we want to retrieve a nested attribute. path: A dot separated string containing zero or more attribute names. Returns: The attribute referred to by obj.a1.a2.a3... Raises: AttributeError: If there is no such attribute. """ if not path: return obj head, _, tail = path.partition('.') head_obj = getattr(obj, head) return resolve_attr(head_obj, tail)
[ "def", "resolve_attr", "(", "obj", ",", "path", ")", ":", "if", "not", "path", ":", "return", "obj", "head", ",", "_", ",", "tail", "=", "path", ".", "partition", "(", "'.'", ")", "head_obj", "=", "getattr", "(", "obj", ",", "head", ")", "return", ...
A recursive version of getattr for navigating dotted paths. Args: obj: An object for which we want to retrieve a nested attribute. path: A dot separated string containing zero or more attribute names. Returns: The attribute referred to by obj.a1.a2.a3... Raises: AttributeError: If there is no such attribute.
[ "A", "recursive", "version", "of", "getattr", "for", "navigating", "dotted", "paths", "." ]
de2c22c653fdccf2f5ee96faea74453ff1847e42
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/utils/topic.py#L42-L59
train
228,723
openeventdata/mordecai
mordecai/utilities.py
make_skip_list
def make_skip_list(cts): """ Return hand-defined list of place names to skip and not attempt to geolocate. If users would like to exclude country names, this would be the function to do it with. """ # maybe make these non-country searches but don't discard, at least for # some (esp. bodies of water) special_terms = ["Europe", "West", "the West", "South Pacific", "Gulf of Mexico", "Atlantic", "the Black Sea", "Black Sea", "North America", "Mideast", "Middle East", "the Middle East", "Asia", "the Caucasus", "Africa", "Central Asia", "Balkans", "Eastern Europe", "Arctic", "Ottoman Empire", "Asia-Pacific", "East Asia", "Horn of Africa", "Americas", "North Africa", "the Strait of Hormuz", "Mediterranean", "East", "North", "South", "Latin America", "Southeast Asia", "Western Pacific", "South Asia", "Persian Gulf", "Central Europe", "Western Hemisphere", "Western Europe", "European Union (E.U.)", "EU", "European Union", "E.U.", "Asia-Pacific", "Europe", "Caribbean", "US", "U.S.", "Persian Gulf", "West Africa", "North", "East", "South", "West", "Western Countries" ] # Some words are recurring spacy problems... spacy_problems = ["Kurd", "Qur'an"] #skip_list = list(cts.keys()) + special_terms skip_list = special_terms + spacy_problems skip_list = set(skip_list) return skip_list
python
def make_skip_list(cts): """ Return hand-defined list of place names to skip and not attempt to geolocate. If users would like to exclude country names, this would be the function to do it with. """ # maybe make these non-country searches but don't discard, at least for # some (esp. bodies of water) special_terms = ["Europe", "West", "the West", "South Pacific", "Gulf of Mexico", "Atlantic", "the Black Sea", "Black Sea", "North America", "Mideast", "Middle East", "the Middle East", "Asia", "the Caucasus", "Africa", "Central Asia", "Balkans", "Eastern Europe", "Arctic", "Ottoman Empire", "Asia-Pacific", "East Asia", "Horn of Africa", "Americas", "North Africa", "the Strait of Hormuz", "Mediterranean", "East", "North", "South", "Latin America", "Southeast Asia", "Western Pacific", "South Asia", "Persian Gulf", "Central Europe", "Western Hemisphere", "Western Europe", "European Union (E.U.)", "EU", "European Union", "E.U.", "Asia-Pacific", "Europe", "Caribbean", "US", "U.S.", "Persian Gulf", "West Africa", "North", "East", "South", "West", "Western Countries" ] # Some words are recurring spacy problems... spacy_problems = ["Kurd", "Qur'an"] #skip_list = list(cts.keys()) + special_terms skip_list = special_terms + spacy_problems skip_list = set(skip_list) return skip_list
[ "def", "make_skip_list", "(", "cts", ")", ":", "# maybe make these non-country searches but don't discard, at least for", "# some (esp. bodies of water)", "special_terms", "=", "[", "\"Europe\"", ",", "\"West\"", ",", "\"the West\"", ",", "\"South Pacific\"", ",", "\"Gulf of Me...
Return hand-defined list of place names to skip and not attempt to geolocate. If users would like to exclude country names, this would be the function to do it with.
[ "Return", "hand", "-", "defined", "list", "of", "place", "names", "to", "skip", "and", "not", "attempt", "to", "geolocate", ".", "If", "users", "would", "like", "to", "exclude", "country", "names", "this", "would", "be", "the", "function", "to", "do", "i...
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/utilities.py#L138-L164
train
228,724
openeventdata/mordecai
mordecai/utilities.py
country_list_nlp
def country_list_nlp(cts): """NLP countries so we can use for vector comparisons""" ct_nlp = [] for i in cts.keys(): nlped = nlp(i) ct_nlp.append(nlped) return ct_nlp
python
def country_list_nlp(cts): """NLP countries so we can use for vector comparisons""" ct_nlp = [] for i in cts.keys(): nlped = nlp(i) ct_nlp.append(nlped) return ct_nlp
[ "def", "country_list_nlp", "(", "cts", ")", ":", "ct_nlp", "=", "[", "]", "for", "i", "in", "cts", ".", "keys", "(", ")", ":", "nlped", "=", "nlp", "(", "i", ")", "ct_nlp", ".", "append", "(", "nlped", ")", "return", "ct_nlp" ]
NLP countries so we can use for vector comparisons
[ "NLP", "countries", "so", "we", "can", "use", "for", "vector", "comparisons" ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/utilities.py#L167-L173
train
228,725
openeventdata/mordecai
mordecai/utilities.py
make_country_nationality_list
def make_country_nationality_list(cts, ct_file): """Combine list of countries and list of nationalities""" countries = pd.read_csv(ct_file) nationality = dict(zip(countries.nationality,countries.alpha_3_code)) both_codes = {**nationality, **cts} return both_codes
python
def make_country_nationality_list(cts, ct_file): """Combine list of countries and list of nationalities""" countries = pd.read_csv(ct_file) nationality = dict(zip(countries.nationality,countries.alpha_3_code)) both_codes = {**nationality, **cts} return both_codes
[ "def", "make_country_nationality_list", "(", "cts", ",", "ct_file", ")", ":", "countries", "=", "pd", ".", "read_csv", "(", "ct_file", ")", "nationality", "=", "dict", "(", "zip", "(", "countries", ".", "nationality", ",", "countries", ".", "alpha_3_code", "...
Combine list of countries and list of nationalities
[ "Combine", "list", "of", "countries", "and", "list", "of", "nationalities" ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/utilities.py#L176-L181
train
228,726
openeventdata/mordecai
mordecai/utilities.py
structure_results
def structure_results(res): """Format Elasticsearch result as Python dictionary""" out = {'hits': {'hits': []}} keys = [u'admin1_code', u'admin2_code', u'admin3_code', u'admin4_code', u'alternativenames', u'asciiname', u'cc2', u'coordinates', u'country_code2', u'country_code3', u'dem', u'elevation', u'feature_class', u'feature_code', u'geonameid', u'modification_date', u'name', u'population', u'timezone'] for i in res: i_out = {} for k in keys: i_out[k] = i[k] out['hits']['hits'].append(i_out) return out
python
def structure_results(res): """Format Elasticsearch result as Python dictionary""" out = {'hits': {'hits': []}} keys = [u'admin1_code', u'admin2_code', u'admin3_code', u'admin4_code', u'alternativenames', u'asciiname', u'cc2', u'coordinates', u'country_code2', u'country_code3', u'dem', u'elevation', u'feature_class', u'feature_code', u'geonameid', u'modification_date', u'name', u'population', u'timezone'] for i in res: i_out = {} for k in keys: i_out[k] = i[k] out['hits']['hits'].append(i_out) return out
[ "def", "structure_results", "(", "res", ")", ":", "out", "=", "{", "'hits'", ":", "{", "'hits'", ":", "[", "]", "}", "}", "keys", "=", "[", "u'admin1_code'", ",", "u'admin2_code'", ",", "u'admin3_code'", ",", "u'admin4_code'", ",", "u'alternativenames'", "...
Format Elasticsearch result as Python dictionary
[ "Format", "Elasticsearch", "result", "as", "Python", "dictionary" ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/utilities.py#L218-L231
train
228,727
openeventdata/mordecai
mordecai/utilities.py
setup_es
def setup_es(hosts, port, use_ssl=False, auth=None): """ Setup an Elasticsearch connection Parameters ---------- hosts: list Hostnames / IP addresses for elasticsearch cluster port: string Port for elasticsearch cluster use_ssl: boolean Whether to use SSL for the elasticsearch connection auth: tuple (username, password) to use with HTTP auth Returns ------- es_conn: an elasticsearch_dsl Search connection object. """ kwargs = dict( hosts=hosts or ['localhost'], port=port or 9200, use_ssl=use_ssl, ) if auth: kwargs.update(http_auth=auth) CLIENT = Elasticsearch(**kwargs) S = Search(using=CLIENT, index="geonames") return S
python
def setup_es(hosts, port, use_ssl=False, auth=None): """ Setup an Elasticsearch connection Parameters ---------- hosts: list Hostnames / IP addresses for elasticsearch cluster port: string Port for elasticsearch cluster use_ssl: boolean Whether to use SSL for the elasticsearch connection auth: tuple (username, password) to use with HTTP auth Returns ------- es_conn: an elasticsearch_dsl Search connection object. """ kwargs = dict( hosts=hosts or ['localhost'], port=port or 9200, use_ssl=use_ssl, ) if auth: kwargs.update(http_auth=auth) CLIENT = Elasticsearch(**kwargs) S = Search(using=CLIENT, index="geonames") return S
[ "def", "setup_es", "(", "hosts", ",", "port", ",", "use_ssl", "=", "False", ",", "auth", "=", "None", ")", ":", "kwargs", "=", "dict", "(", "hosts", "=", "hosts", "or", "[", "'localhost'", "]", ",", "port", "=", "port", "or", "9200", ",", "use_ssl"...
Setup an Elasticsearch connection Parameters ---------- hosts: list Hostnames / IP addresses for elasticsearch cluster port: string Port for elasticsearch cluster use_ssl: boolean Whether to use SSL for the elasticsearch connection auth: tuple (username, password) to use with HTTP auth Returns ------- es_conn: an elasticsearch_dsl Search connection object.
[ "Setup", "an", "Elasticsearch", "connection" ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/utilities.py#L233-L261
train
228,728
openeventdata/mordecai
mordecai/geoparse.py
Geoparser._feature_country_mentions
def _feature_country_mentions(self, doc): """ Given a document, count how many times different country names and adjectives are mentioned. These are features used in the country picking phase. Parameters --------- doc: a spaCy nlp'ed piece of text Returns ------- countries: dict the top two countries (ISO code) and their frequency of mentions. """ c_list = [] for i in doc.ents: try: country = self._both_codes[i.text] c_list.append(country) except KeyError: pass count = Counter(c_list).most_common() try: top, top_count = count[0] except: top = "" top_count = 0 try: two, two_count = count[1] except: two = "" two_count = 0 countries = (top, top_count, two, two_count) return countries
python
def _feature_country_mentions(self, doc): """ Given a document, count how many times different country names and adjectives are mentioned. These are features used in the country picking phase. Parameters --------- doc: a spaCy nlp'ed piece of text Returns ------- countries: dict the top two countries (ISO code) and their frequency of mentions. """ c_list = [] for i in doc.ents: try: country = self._both_codes[i.text] c_list.append(country) except KeyError: pass count = Counter(c_list).most_common() try: top, top_count = count[0] except: top = "" top_count = 0 try: two, two_count = count[1] except: two = "" two_count = 0 countries = (top, top_count, two, two_count) return countries
[ "def", "_feature_country_mentions", "(", "self", ",", "doc", ")", ":", "c_list", "=", "[", "]", "for", "i", "in", "doc", ".", "ents", ":", "try", ":", "country", "=", "self", ".", "_both_codes", "[", "i", ".", "text", "]", "c_list", ".", "append", ...
Given a document, count how many times different country names and adjectives are mentioned. These are features used in the country picking phase. Parameters --------- doc: a spaCy nlp'ed piece of text Returns ------- countries: dict the top two countries (ISO code) and their frequency of mentions.
[ "Given", "a", "document", "count", "how", "many", "times", "different", "country", "names", "and", "adjectives", "are", "mentioned", ".", "These", "are", "features", "used", "in", "the", "country", "picking", "phase", "." ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L78-L112
train
228,729
openeventdata/mordecai
mordecai/geoparse.py
Geoparser.clean_entity
def clean_entity(self, ent): """ Strip out extra words that often get picked up by spaCy's NER. To do: preserve info about what got stripped out to help with ES/Geonames resolution later. Parameters --------- ent: a spaCy named entity Span Returns ------- new_ent: a spaCy Span, with extra words stripped out. """ dump_list = ['province', 'the', 'area', 'airport', 'district', 'square', 'town', 'village', 'prison', "river", "valley", "provincial", "prison", "region", "municipality", "state", "territory", "of", "in", "county", "central"] # maybe have 'city'? Works differently in different countries # also, "District of Columbia". Might need to use cap/no cap keep_positions = [] for word in ent: if word.text.lower() not in dump_list: keep_positions.append(word.i) keep_positions = np.asarray(keep_positions) try: new_ent = ent.doc[keep_positions.min():keep_positions.max() + 1] # can't set directly #new_ent.label_.__set__(ent.label_) except ValueError: new_ent = ent return new_ent
python
def clean_entity(self, ent): """ Strip out extra words that often get picked up by spaCy's NER. To do: preserve info about what got stripped out to help with ES/Geonames resolution later. Parameters --------- ent: a spaCy named entity Span Returns ------- new_ent: a spaCy Span, with extra words stripped out. """ dump_list = ['province', 'the', 'area', 'airport', 'district', 'square', 'town', 'village', 'prison', "river", "valley", "provincial", "prison", "region", "municipality", "state", "territory", "of", "in", "county", "central"] # maybe have 'city'? Works differently in different countries # also, "District of Columbia". Might need to use cap/no cap keep_positions = [] for word in ent: if word.text.lower() not in dump_list: keep_positions.append(word.i) keep_positions = np.asarray(keep_positions) try: new_ent = ent.doc[keep_positions.min():keep_positions.max() + 1] # can't set directly #new_ent.label_.__set__(ent.label_) except ValueError: new_ent = ent return new_ent
[ "def", "clean_entity", "(", "self", ",", "ent", ")", ":", "dump_list", "=", "[", "'province'", ",", "'the'", ",", "'area'", ",", "'airport'", ",", "'district'", ",", "'square'", ",", "'town'", ",", "'village'", ",", "'prison'", ",", "\"river\"", ",", "\"...
Strip out extra words that often get picked up by spaCy's NER. To do: preserve info about what got stripped out to help with ES/Geonames resolution later. Parameters --------- ent: a spaCy named entity Span Returns ------- new_ent: a spaCy Span, with extra words stripped out.
[ "Strip", "out", "extra", "words", "that", "often", "get", "picked", "up", "by", "spaCy", "s", "NER", "." ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L115-L149
train
228,730
openeventdata/mordecai
mordecai/geoparse.py
Geoparser._feature_most_alternative
def _feature_most_alternative(self, results, full_results=False): """ Find the placename with the most alternative names and return its country. More alternative names are a rough measure of importance. Paramaters ---------- results: dict output of `query_geonames` Returns ------- most_alt: str ISO code of country of place with most alternative names, or empty string if none """ try: alt_names = [len(i['alternativenames']) for i in results['hits']['hits']] most_alt = results['hits']['hits'][np.array(alt_names).argmax()] if full_results: return most_alt else: return most_alt['country_code3'] except (IndexError, ValueError, TypeError): return ""
python
def _feature_most_alternative(self, results, full_results=False): """ Find the placename with the most alternative names and return its country. More alternative names are a rough measure of importance. Paramaters ---------- results: dict output of `query_geonames` Returns ------- most_alt: str ISO code of country of place with most alternative names, or empty string if none """ try: alt_names = [len(i['alternativenames']) for i in results['hits']['hits']] most_alt = results['hits']['hits'][np.array(alt_names).argmax()] if full_results: return most_alt else: return most_alt['country_code3'] except (IndexError, ValueError, TypeError): return ""
[ "def", "_feature_most_alternative", "(", "self", ",", "results", ",", "full_results", "=", "False", ")", ":", "try", ":", "alt_names", "=", "[", "len", "(", "i", "[", "'alternativenames'", "]", ")", "for", "i", "in", "results", "[", "'hits'", "]", "[", ...
Find the placename with the most alternative names and return its country. More alternative names are a rough measure of importance. Paramaters ---------- results: dict output of `query_geonames` Returns ------- most_alt: str ISO code of country of place with most alternative names, or empty string if none
[ "Find", "the", "placename", "with", "the", "most", "alternative", "names", "and", "return", "its", "country", ".", "More", "alternative", "names", "are", "a", "rough", "measure", "of", "importance", "." ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L176-L200
train
228,731
openeventdata/mordecai
mordecai/geoparse.py
Geoparser._feature_most_population
def _feature_most_population(self, results): """ Find the placename with the largest population and return its country. More population is a rough measure of importance. Paramaters ---------- results: dict output of `query_geonames` Returns ------- most_pop: str ISO code of country of place with largest population, or empty string if none """ try: populations = [i['population'] for i in results['hits']['hits']] most_pop = results['hits']['hits'][np.array(populations).astype("int").argmax()] return most_pop['country_code3'] except Exception as e: return ""
python
def _feature_most_population(self, results): """ Find the placename with the largest population and return its country. More population is a rough measure of importance. Paramaters ---------- results: dict output of `query_geonames` Returns ------- most_pop: str ISO code of country of place with largest population, or empty string if none """ try: populations = [i['population'] for i in results['hits']['hits']] most_pop = results['hits']['hits'][np.array(populations).astype("int").argmax()] return most_pop['country_code3'] except Exception as e: return ""
[ "def", "_feature_most_population", "(", "self", ",", "results", ")", ":", "try", ":", "populations", "=", "[", "i", "[", "'population'", "]", "for", "i", "in", "results", "[", "'hits'", "]", "[", "'hits'", "]", "]", "most_pop", "=", "results", "[", "'h...
Find the placename with the largest population and return its country. More population is a rough measure of importance. Paramaters ---------- results: dict output of `query_geonames` Returns ------- most_pop: str ISO code of country of place with largest population, or empty string if none
[ "Find", "the", "placename", "with", "the", "largest", "population", "and", "return", "its", "country", ".", "More", "population", "is", "a", "rough", "measure", "of", "importance", "." ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L203-L225
train
228,732
openeventdata/mordecai
mordecai/geoparse.py
Geoparser._feature_word_embedding
def _feature_word_embedding(self, text): """ Given a word, guess the appropriate country by word vector. Parameters --------- text: str the text to extract locations from. Returns ------- country_picking: dict The top two countries (ISO codes) and two measures confidence for the first choice. """ try: simils = np.dot(self._prebuilt_vec, text.vector) except Exception as e: #print("Vector problem, ", Exception, e) return {"country_1" : "", "confid_a" : 0, "confid_b" : 0, "country_2" : ""} ranks = simils.argsort()[::-1] confid = simils.max() confid2 = simils[ranks[0]] - simils[ranks[1]] if confid == 0 or confid2 == 0: return "" country_code = self._cts[str(self._ct_nlp[ranks[0]])] country_picking = {"country_1" : country_code, "confid_a" : confid, "confid_b" : confid2, "country_2" : self._cts[str(self._ct_nlp[ranks[1]])]} return country_picking
python
def _feature_word_embedding(self, text): """ Given a word, guess the appropriate country by word vector. Parameters --------- text: str the text to extract locations from. Returns ------- country_picking: dict The top two countries (ISO codes) and two measures confidence for the first choice. """ try: simils = np.dot(self._prebuilt_vec, text.vector) except Exception as e: #print("Vector problem, ", Exception, e) return {"country_1" : "", "confid_a" : 0, "confid_b" : 0, "country_2" : ""} ranks = simils.argsort()[::-1] confid = simils.max() confid2 = simils[ranks[0]] - simils[ranks[1]] if confid == 0 or confid2 == 0: return "" country_code = self._cts[str(self._ct_nlp[ranks[0]])] country_picking = {"country_1" : country_code, "confid_a" : confid, "confid_b" : confid2, "country_2" : self._cts[str(self._ct_nlp[ranks[1]])]} return country_picking
[ "def", "_feature_word_embedding", "(", "self", ",", "text", ")", ":", "try", ":", "simils", "=", "np", ".", "dot", "(", "self", ".", "_prebuilt_vec", ",", "text", ".", "vector", ")", "except", "Exception", "as", "e", ":", "#print(\"Vector problem, \", Except...
Given a word, guess the appropriate country by word vector. Parameters --------- text: str the text to extract locations from. Returns ------- country_picking: dict The top two countries (ISO codes) and two measures confidence for the first choice.
[ "Given", "a", "word", "guess", "the", "appropriate", "country", "by", "word", "vector", "." ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L228-L261
train
228,733
openeventdata/mordecai
mordecai/geoparse.py
Geoparser._feature_first_back
def _feature_first_back(self, results): """ Get the country of the first two results back from geonames. Parameters ----------- results: dict elasticsearch results Returns ------- top: tuple first and second results' country name (ISO) """ try: first_back = results['hits']['hits'][0]['country_code3'] except (TypeError, IndexError): # usually occurs if no Geonames result first_back = "" try: second_back = results['hits']['hits'][1]['country_code3'] except (TypeError, IndexError): second_back = "" top = (first_back, second_back) return top
python
def _feature_first_back(self, results): """ Get the country of the first two results back from geonames. Parameters ----------- results: dict elasticsearch results Returns ------- top: tuple first and second results' country name (ISO) """ try: first_back = results['hits']['hits'][0]['country_code3'] except (TypeError, IndexError): # usually occurs if no Geonames result first_back = "" try: second_back = results['hits']['hits'][1]['country_code3'] except (TypeError, IndexError): second_back = "" top = (first_back, second_back) return top
[ "def", "_feature_first_back", "(", "self", ",", "results", ")", ":", "try", ":", "first_back", "=", "results", "[", "'hits'", "]", "[", "'hits'", "]", "[", "0", "]", "[", "'country_code3'", "]", "except", "(", "TypeError", ",", "IndexError", ")", ":", ...
Get the country of the first two results back from geonames. Parameters ----------- results: dict elasticsearch results Returns ------- top: tuple first and second results' country name (ISO)
[ "Get", "the", "country", "of", "the", "first", "two", "results", "back", "from", "geonames", "." ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L264-L288
train
228,734
openeventdata/mordecai
mordecai/geoparse.py
Geoparser.is_country
def is_country(self, text): """Check if a piece of text is in the list of countries""" ct_list = self._just_cts.keys() if text in ct_list: return True else: return False
python
def is_country(self, text): """Check if a piece of text is in the list of countries""" ct_list = self._just_cts.keys() if text in ct_list: return True else: return False
[ "def", "is_country", "(", "self", ",", "text", ")", ":", "ct_list", "=", "self", ".", "_just_cts", ".", "keys", "(", ")", "if", "text", "in", "ct_list", ":", "return", "True", "else", ":", "return", "False" ]
Check if a piece of text is in the list of countries
[ "Check", "if", "a", "piece", "of", "text", "is", "in", "the", "list", "of", "countries" ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L291-L297
train
228,735
openeventdata/mordecai
mordecai/geoparse.py
Geoparser.query_geonames
def query_geonames(self, placename): """ Wrap search parameters into an elasticsearch query to the geonames index and return results. Parameters --------- conn: an elasticsearch Search conn, like the one returned by `setup_es()` placename: str the placename text extracted by NER system Returns ------- out: The raw results of the elasticsearch query """ # first first, try for country name if self.is_country(placename): q = {"multi_match": {"query": placename, "fields": ['name', 'asciiname', 'alternativenames'], "type" : "phrase"}} res = self.conn.filter("term", feature_code='PCLI').query(q)[0:5].execute() # always 5 else: # second, try for an exact phrase match q = {"multi_match": {"query": placename, "fields": ['name^5', 'asciiname^5', 'alternativenames'], "type" : "phrase"}} res = self.conn.query(q)[0:50].execute() # if no results, use some fuzziness, but still require all terms to be present. # Fuzzy is not allowed in "phrase" searches. if res.hits.total == 0: # tried wrapping this in a {"constant_score" : {"query": ... but made it worse q = {"multi_match": {"query": placename, "fields": ['name', 'asciiname', 'alternativenames'], "fuzziness" : 1, "operator": "and" } } res = self.conn.query(q)[0:50].execute() es_result = utilities.structure_results(res) return es_result
python
def query_geonames(self, placename): """ Wrap search parameters into an elasticsearch query to the geonames index and return results. Parameters --------- conn: an elasticsearch Search conn, like the one returned by `setup_es()` placename: str the placename text extracted by NER system Returns ------- out: The raw results of the elasticsearch query """ # first first, try for country name if self.is_country(placename): q = {"multi_match": {"query": placename, "fields": ['name', 'asciiname', 'alternativenames'], "type" : "phrase"}} res = self.conn.filter("term", feature_code='PCLI').query(q)[0:5].execute() # always 5 else: # second, try for an exact phrase match q = {"multi_match": {"query": placename, "fields": ['name^5', 'asciiname^5', 'alternativenames'], "type" : "phrase"}} res = self.conn.query(q)[0:50].execute() # if no results, use some fuzziness, but still require all terms to be present. # Fuzzy is not allowed in "phrase" searches. if res.hits.total == 0: # tried wrapping this in a {"constant_score" : {"query": ... but made it worse q = {"multi_match": {"query": placename, "fields": ['name', 'asciiname', 'alternativenames'], "fuzziness" : 1, "operator": "and" } } res = self.conn.query(q)[0:50].execute() es_result = utilities.structure_results(res) return es_result
[ "def", "query_geonames", "(", "self", ",", "placename", ")", ":", "# first first, try for country name", "if", "self", ".", "is_country", "(", "placename", ")", ":", "q", "=", "{", "\"multi_match\"", ":", "{", "\"query\"", ":", "placename", ",", "\"fields\"", ...
Wrap search parameters into an elasticsearch query to the geonames index and return results. Parameters --------- conn: an elasticsearch Search conn, like the one returned by `setup_es()` placename: str the placename text extracted by NER system Returns ------- out: The raw results of the elasticsearch query
[ "Wrap", "search", "parameters", "into", "an", "elasticsearch", "query", "to", "the", "geonames", "index", "and", "return", "results", "." ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L301-L341
train
228,736
openeventdata/mordecai
mordecai/geoparse.py
Geoparser.query_geonames_country
def query_geonames_country(self, placename, country): """ Like query_geonames, but this time limited to a specified country. """ # first, try for an exact phrase match q = {"multi_match": {"query": placename, "fields": ['name^5', 'asciiname^5', 'alternativenames'], "type": "phrase"}} res = self.conn.filter("term", country_code3=country).query(q)[0:50].execute() # if no results, use some fuzziness, but still require all terms to be present. # Fuzzy is not allowed in "phrase" searches. if res.hits.total == 0: # tried wrapping this in a {"constant_score" : {"query": ... but made it worse q = {"multi_match": {"query": placename, "fields": ['name', 'asciiname', 'alternativenames'], "fuzziness": 1, "operator": "and"}} res = self.conn.filter("term", country_code3=country).query(q)[0:50].execute() out = utilities.structure_results(res) return out
python
def query_geonames_country(self, placename, country): """ Like query_geonames, but this time limited to a specified country. """ # first, try for an exact phrase match q = {"multi_match": {"query": placename, "fields": ['name^5', 'asciiname^5', 'alternativenames'], "type": "phrase"}} res = self.conn.filter("term", country_code3=country).query(q)[0:50].execute() # if no results, use some fuzziness, but still require all terms to be present. # Fuzzy is not allowed in "phrase" searches. if res.hits.total == 0: # tried wrapping this in a {"constant_score" : {"query": ... but made it worse q = {"multi_match": {"query": placename, "fields": ['name', 'asciiname', 'alternativenames'], "fuzziness": 1, "operator": "and"}} res = self.conn.filter("term", country_code3=country).query(q)[0:50].execute() out = utilities.structure_results(res) return out
[ "def", "query_geonames_country", "(", "self", ",", "placename", ",", "country", ")", ":", "# first, try for an exact phrase match", "q", "=", "{", "\"multi_match\"", ":", "{", "\"query\"", ":", "placename", ",", "\"fields\"", ":", "[", "'name^5'", ",", "'asciiname...
Like query_geonames, but this time limited to a specified country.
[ "Like", "query_geonames", "but", "this", "time", "limited", "to", "a", "specified", "country", "." ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L345-L365
train
228,737
openeventdata/mordecai
mordecai/geoparse.py
Geoparser.make_country_matrix
def make_country_matrix(self, loc): """ Create features for all possible country labels, return as matrix for keras. Parameters ---------- loc: dict one entry from the list of locations and features that come out of make_country_features Returns -------- keras_inputs: dict with two keys, "label" and "matrix" """ top = loc['features']['ct_mention'] top_count = loc['features']['ctm_count1'] two = loc['features']['ct_mention2'] two_count = loc['features']['ctm_count2'] word_vec = loc['features']['word_vec'] first_back = loc['features']['first_back'] most_alt = loc['features']['most_alt'] most_pop = loc['features']['most_pop'] possible_labels = set([top, two, word_vec, first_back, most_alt, most_pop]) possible_labels = [i for i in possible_labels if i] X_mat = [] for label in possible_labels: inputs = np.array([word_vec, first_back, most_alt, most_pop]) x = inputs == label x = np.asarray((x * 2) - 1) # convert to -1, 1 # get missing values exists = inputs != "" exists = np.asarray((exists * 2) - 1) counts = np.asarray([top_count, two_count]) # cludgy, should be up with "inputs" right = np.asarray([top, two]) == label right = right * 2 - 1 right[counts == 0] = 0 # get correct values features = np.concatenate([x, exists, counts, right]) X_mat.append(np.asarray(features)) keras_inputs = {"labels": possible_labels, "matrix" : np.asmatrix(X_mat)} return keras_inputs
python
def make_country_matrix(self, loc): """ Create features for all possible country labels, return as matrix for keras. Parameters ---------- loc: dict one entry from the list of locations and features that come out of make_country_features Returns -------- keras_inputs: dict with two keys, "label" and "matrix" """ top = loc['features']['ct_mention'] top_count = loc['features']['ctm_count1'] two = loc['features']['ct_mention2'] two_count = loc['features']['ctm_count2'] word_vec = loc['features']['word_vec'] first_back = loc['features']['first_back'] most_alt = loc['features']['most_alt'] most_pop = loc['features']['most_pop'] possible_labels = set([top, two, word_vec, first_back, most_alt, most_pop]) possible_labels = [i for i in possible_labels if i] X_mat = [] for label in possible_labels: inputs = np.array([word_vec, first_back, most_alt, most_pop]) x = inputs == label x = np.asarray((x * 2) - 1) # convert to -1, 1 # get missing values exists = inputs != "" exists = np.asarray((exists * 2) - 1) counts = np.asarray([top_count, two_count]) # cludgy, should be up with "inputs" right = np.asarray([top, two]) == label right = right * 2 - 1 right[counts == 0] = 0 # get correct values features = np.concatenate([x, exists, counts, right]) X_mat.append(np.asarray(features)) keras_inputs = {"labels": possible_labels, "matrix" : np.asmatrix(X_mat)} return keras_inputs
[ "def", "make_country_matrix", "(", "self", ",", "loc", ")", ":", "top", "=", "loc", "[", "'features'", "]", "[", "'ct_mention'", "]", "top_count", "=", "loc", "[", "'features'", "]", "[", "'ctm_count1'", "]", "two", "=", "loc", "[", "'features'", "]", ...
Create features for all possible country labels, return as matrix for keras. Parameters ---------- loc: dict one entry from the list of locations and features that come out of make_country_features Returns -------- keras_inputs: dict with two keys, "label" and "matrix"
[ "Create", "features", "for", "all", "possible", "country", "labels", "return", "as", "matrix", "for", "keras", "." ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L595-L643
train
228,738
openeventdata/mordecai
mordecai/geoparse.py
Geoparser.infer_country
def infer_country(self, doc): """NLP a doc, find its entities, get their features, and return the model's country guess for each. Maybe use a better name. Parameters ----------- doc: str or spaCy the document to country-resolve the entities in Returns ------- proced: list of dict the feature output of "make_country_features" updated with the model's estimated country for each entity. E.g.: {'all_confidence': array([ 0.95783567, 0.03769876, 0.00454875], dtype=float32), 'all_countries': array(['SYR', 'USA', 'JAM'], dtype='<U3'), 'country_conf': 0.95783567, 'country_predicted': 'SYR', 'features': {'ct_mention': '', 'ct_mention2': '', 'ctm_count1': 0, 'ctm_count2': 0, 'first_back': 'JAM', 'maj_vote': 'SYR', 'most_alt': 'USA', 'most_pop': 'SYR', 'word_vec': 'SYR', 'wv_confid': '29.3188'}, 'label': 'Syria', 'spans': [{'end': 26, 'start': 20}], 'text': "There's fighting in Aleppo and Homs.", 'word': 'Aleppo'} """ if not hasattr(doc, "ents"): doc = nlp(doc) proced = self.make_country_features(doc, require_maj=False) if not proced: pass # logging! #print("Nothing came back from make_country_features") feat_list = [] #proced = self.ent_list_to_matrix(proced) for loc in proced: feat = self.make_country_matrix(loc) #labels = loc['labels'] feat_list.append(feat) #try: # for each potential country... for n, i in enumerate(feat_list): labels = i['labels'] try: prediction = self.country_model.predict(i['matrix']).transpose()[0] ranks = prediction.argsort()[::-1] labels = np.asarray(labels)[ranks] prediction = prediction[ranks] except ValueError: prediction = np.array([0]) labels = np.array([""]) loc['country_predicted'] = labels[0] loc['country_conf'] = prediction[0] loc['all_countries'] = labels loc['all_confidence'] = prediction return proced
python
def infer_country(self, doc): """NLP a doc, find its entities, get their features, and return the model's country guess for each. Maybe use a better name. Parameters ----------- doc: str or spaCy the document to country-resolve the entities in Returns ------- proced: list of dict the feature output of "make_country_features" updated with the model's estimated country for each entity. E.g.: {'all_confidence': array([ 0.95783567, 0.03769876, 0.00454875], dtype=float32), 'all_countries': array(['SYR', 'USA', 'JAM'], dtype='<U3'), 'country_conf': 0.95783567, 'country_predicted': 'SYR', 'features': {'ct_mention': '', 'ct_mention2': '', 'ctm_count1': 0, 'ctm_count2': 0, 'first_back': 'JAM', 'maj_vote': 'SYR', 'most_alt': 'USA', 'most_pop': 'SYR', 'word_vec': 'SYR', 'wv_confid': '29.3188'}, 'label': 'Syria', 'spans': [{'end': 26, 'start': 20}], 'text': "There's fighting in Aleppo and Homs.", 'word': 'Aleppo'} """ if not hasattr(doc, "ents"): doc = nlp(doc) proced = self.make_country_features(doc, require_maj=False) if not proced: pass # logging! #print("Nothing came back from make_country_features") feat_list = [] #proced = self.ent_list_to_matrix(proced) for loc in proced: feat = self.make_country_matrix(loc) #labels = loc['labels'] feat_list.append(feat) #try: # for each potential country... for n, i in enumerate(feat_list): labels = i['labels'] try: prediction = self.country_model.predict(i['matrix']).transpose()[0] ranks = prediction.argsort()[::-1] labels = np.asarray(labels)[ranks] prediction = prediction[ranks] except ValueError: prediction = np.array([0]) labels = np.array([""]) loc['country_predicted'] = labels[0] loc['country_conf'] = prediction[0] loc['all_countries'] = labels loc['all_confidence'] = prediction return proced
[ "def", "infer_country", "(", "self", ",", "doc", ")", ":", "if", "not", "hasattr", "(", "doc", ",", "\"ents\"", ")", ":", "doc", "=", "nlp", "(", "doc", ")", "proced", "=", "self", ".", "make_country_features", "(", "doc", ",", "require_maj", "=", "F...
NLP a doc, find its entities, get their features, and return the model's country guess for each. Maybe use a better name. Parameters ----------- doc: str or spaCy the document to country-resolve the entities in Returns ------- proced: list of dict the feature output of "make_country_features" updated with the model's estimated country for each entity. E.g.: {'all_confidence': array([ 0.95783567, 0.03769876, 0.00454875], dtype=float32), 'all_countries': array(['SYR', 'USA', 'JAM'], dtype='<U3'), 'country_conf': 0.95783567, 'country_predicted': 'SYR', 'features': {'ct_mention': '', 'ct_mention2': '', 'ctm_count1': 0, 'ctm_count2': 0, 'first_back': 'JAM', 'maj_vote': 'SYR', 'most_alt': 'USA', 'most_pop': 'SYR', 'word_vec': 'SYR', 'wv_confid': '29.3188'}, 'label': 'Syria', 'spans': [{'end': 26, 'start': 20}], 'text': "There's fighting in Aleppo and Homs.", 'word': 'Aleppo'}
[ "NLP", "a", "doc", "find", "its", "entities", "get", "their", "features", "and", "return", "the", "model", "s", "country", "guess", "for", "each", ".", "Maybe", "use", "a", "better", "name", "." ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L647-L714
train
228,739
openeventdata/mordecai
mordecai/geoparse.py
Geoparser.get_admin1
def get_admin1(self, country_code2, admin1_code): """ Convert a geonames admin1 code to the associated place name. Parameters --------- country_code2: string The two character country code admin1_code: string The admin1 code to be converted. (Admin1 is the highest subnational political unit, state/region/provice/etc. admin1_dict: dictionary The dictionary containing the country code + admin1 code as keys and the admin1 names as values. Returns ------ admin1_name: string The admin1 name. If none is found, return "NA". """ lookup_key = ".".join([country_code2, admin1_code]) try: admin1_name = self._admin1_dict[lookup_key] return admin1_name except KeyError: #print("No admin code found for country {} and code {}".format(country_code2, admin1_code)) return "NA"
python
def get_admin1(self, country_code2, admin1_code): """ Convert a geonames admin1 code to the associated place name. Parameters --------- country_code2: string The two character country code admin1_code: string The admin1 code to be converted. (Admin1 is the highest subnational political unit, state/region/provice/etc. admin1_dict: dictionary The dictionary containing the country code + admin1 code as keys and the admin1 names as values. Returns ------ admin1_name: string The admin1 name. If none is found, return "NA". """ lookup_key = ".".join([country_code2, admin1_code]) try: admin1_name = self._admin1_dict[lookup_key] return admin1_name except KeyError: #print("No admin code found for country {} and code {}".format(country_code2, admin1_code)) return "NA"
[ "def", "get_admin1", "(", "self", ",", "country_code2", ",", "admin1_code", ")", ":", "lookup_key", "=", "\".\"", ".", "join", "(", "[", "country_code2", ",", "admin1_code", "]", ")", "try", ":", "admin1_name", "=", "self", ".", "_admin1_dict", "[", "looku...
Convert a geonames admin1 code to the associated place name. Parameters --------- country_code2: string The two character country code admin1_code: string The admin1 code to be converted. (Admin1 is the highest subnational political unit, state/region/provice/etc. admin1_dict: dictionary The dictionary containing the country code + admin1 code as keys and the admin1 names as values. Returns ------ admin1_name: string The admin1 name. If none is found, return "NA".
[ "Convert", "a", "geonames", "admin1", "code", "to", "the", "associated", "place", "name", "." ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L716-L742
train
228,740
openeventdata/mordecai
mordecai/geoparse.py
Geoparser.ranker
def ranker(self, X, meta): """ Sort the place features list by the score of its relevance. """ # total score is just a sum of each row total_score = X.sum(axis=1).transpose() total_score = np.squeeze(np.asarray(total_score)) # matrix to array ranks = total_score.argsort() ranks = ranks[::-1] # sort the list of dicts according to ranks sorted_meta = [meta[r] for r in ranks] sorted_X = X[ranks] return (sorted_X, sorted_meta)
python
def ranker(self, X, meta): """ Sort the place features list by the score of its relevance. """ # total score is just a sum of each row total_score = X.sum(axis=1).transpose() total_score = np.squeeze(np.asarray(total_score)) # matrix to array ranks = total_score.argsort() ranks = ranks[::-1] # sort the list of dicts according to ranks sorted_meta = [meta[r] for r in ranks] sorted_X = X[ranks] return (sorted_X, sorted_meta)
[ "def", "ranker", "(", "self", ",", "X", ",", "meta", ")", ":", "# total score is just a sum of each row", "total_score", "=", "X", ".", "sum", "(", "axis", "=", "1", ")", ".", "transpose", "(", ")", "total_score", "=", "np", ".", "squeeze", "(", "np", ...
Sort the place features list by the score of its relevance.
[ "Sort", "the", "place", "features", "list", "by", "the", "score", "of", "its", "relevance", "." ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L819-L831
train
228,741
openeventdata/mordecai
mordecai/geoparse.py
Geoparser.format_for_prodigy
def format_for_prodigy(self, X, meta, placename, return_feature_subset=False): """ Given a feature matrix, geonames data, and the original query, construct a prodigy task. Make meta nicely readable: "A town in Germany" Parameters ---------- X: matrix vector of features for ranking. Output of features_for_rank() meta: list of dictionaries other place information. Output of features_for_rank(). Used to provide information like "city in Germany" to the coding task. placename: str The extracted place name from text Returns -------- task_list: list of dicts Tasks ready to be written to JSONL and use in Prodigy. Each potential match includes a text description to the annotator can pick the right one. """ all_tasks = [] sorted_X, sorted_meta = self.ranker(X, meta) sorted_meta = sorted_meta[:4] sorted_X = sorted_X[:4] for n, i in enumerate(sorted_meta): feature_code = i['feature_code'] try: fc = self._code_to_text[feature_code] except KeyError: fc = '' text = ''.join(['"', i['place_name'], '"', ", a ", fc, " in ", i['country_code3'], ", id: ", i['geonameid']]) d = {"id" : n + 1, "text" : text} all_tasks.append(d) if return_feature_subset: return (all_tasks, sorted_meta, sorted_X) else: return all_tasks
python
def format_for_prodigy(self, X, meta, placename, return_feature_subset=False): """ Given a feature matrix, geonames data, and the original query, construct a prodigy task. Make meta nicely readable: "A town in Germany" Parameters ---------- X: matrix vector of features for ranking. Output of features_for_rank() meta: list of dictionaries other place information. Output of features_for_rank(). Used to provide information like "city in Germany" to the coding task. placename: str The extracted place name from text Returns -------- task_list: list of dicts Tasks ready to be written to JSONL and use in Prodigy. Each potential match includes a text description to the annotator can pick the right one. """ all_tasks = [] sorted_X, sorted_meta = self.ranker(X, meta) sorted_meta = sorted_meta[:4] sorted_X = sorted_X[:4] for n, i in enumerate(sorted_meta): feature_code = i['feature_code'] try: fc = self._code_to_text[feature_code] except KeyError: fc = '' text = ''.join(['"', i['place_name'], '"', ", a ", fc, " in ", i['country_code3'], ", id: ", i['geonameid']]) d = {"id" : n + 1, "text" : text} all_tasks.append(d) if return_feature_subset: return (all_tasks, sorted_meta, sorted_X) else: return all_tasks
[ "def", "format_for_prodigy", "(", "self", ",", "X", ",", "meta", ",", "placename", ",", "return_feature_subset", "=", "False", ")", ":", "all_tasks", "=", "[", "]", "sorted_X", ",", "sorted_meta", "=", "self", ".", "ranker", "(", "X", ",", "meta", ")", ...
Given a feature matrix, geonames data, and the original query, construct a prodigy task. Make meta nicely readable: "A town in Germany" Parameters ---------- X: matrix vector of features for ranking. Output of features_for_rank() meta: list of dictionaries other place information. Output of features_for_rank(). Used to provide information like "city in Germany" to the coding task. placename: str The extracted place name from text Returns -------- task_list: list of dicts Tasks ready to be written to JSONL and use in Prodigy. Each potential match includes a text description to the annotator can pick the right one.
[ "Given", "a", "feature", "matrix", "geonames", "data", "and", "the", "original", "query", "construct", "a", "prodigy", "task", "." ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L833-L880
train
228,742
openeventdata/mordecai
mordecai/geoparse.py
Geoparser.format_geonames
def format_geonames(self, entry, searchterm=None): """ Pull out just the fields we want from a geonames entry To do: - switch to model picking Parameters ----------- res : dict ES/geonames result searchterm : str (not implemented). Needed for better results picking Returns -------- new_res : dict containing selected fields from selected geonames entry """ try: lat, lon = entry['coordinates'].split(",") new_res = {"admin1" : self.get_admin1(entry['country_code2'], entry['admin1_code']), "lat" : lat, "lon" : lon, "country_code3" : entry["country_code3"], "geonameid" : entry["geonameid"], "place_name" : entry["name"], "feature_class" : entry["feature_class"], "feature_code" : entry["feature_code"]} return new_res except (IndexError, TypeError): # two conditions for these errors: # 1. there are no results for some reason (Index) # 2. res is set to "" because the country model was below the thresh new_res = {"admin1" : "", "lat" : "", "lon" : "", "country_code3" : "", "geonameid" : "", "place_name" : "", "feature_class" : "", "feature_code" : ""} return new_res
python
def format_geonames(self, entry, searchterm=None): """ Pull out just the fields we want from a geonames entry To do: - switch to model picking Parameters ----------- res : dict ES/geonames result searchterm : str (not implemented). Needed for better results picking Returns -------- new_res : dict containing selected fields from selected geonames entry """ try: lat, lon = entry['coordinates'].split(",") new_res = {"admin1" : self.get_admin1(entry['country_code2'], entry['admin1_code']), "lat" : lat, "lon" : lon, "country_code3" : entry["country_code3"], "geonameid" : entry["geonameid"], "place_name" : entry["name"], "feature_class" : entry["feature_class"], "feature_code" : entry["feature_code"]} return new_res except (IndexError, TypeError): # two conditions for these errors: # 1. there are no results for some reason (Index) # 2. res is set to "" because the country model was below the thresh new_res = {"admin1" : "", "lat" : "", "lon" : "", "country_code3" : "", "geonameid" : "", "place_name" : "", "feature_class" : "", "feature_code" : ""} return new_res
[ "def", "format_geonames", "(", "self", ",", "entry", ",", "searchterm", "=", "None", ")", ":", "try", ":", "lat", ",", "lon", "=", "entry", "[", "'coordinates'", "]", ".", "split", "(", "\",\"", ")", "new_res", "=", "{", "\"admin1\"", ":", "self", "....
Pull out just the fields we want from a geonames entry To do: - switch to model picking Parameters ----------- res : dict ES/geonames result searchterm : str (not implemented). Needed for better results picking Returns -------- new_res : dict containing selected fields from selected geonames entry
[ "Pull", "out", "just", "the", "fields", "we", "want", "from", "a", "geonames", "entry" ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L883-L926
train
228,743
openeventdata/mordecai
mordecai/geoparse.py
Geoparser.clean_proced
def clean_proced(self, proced): """Small helper function to delete the features from the final dictionary. These features are mostly interesting for debugging but won't be relevant for most users. """ for loc in proced: try: del loc['all_countries'] except KeyError: pass try: del loc['matrix'] except KeyError: pass try: del loc['all_confidence'] except KeyError: pass try: del loc['place_confidence'] except KeyError: pass try: del loc['text'] except KeyError: pass try: del loc['label'] except KeyError: pass try: del loc['features'] except KeyError: pass return proced
python
def clean_proced(self, proced): """Small helper function to delete the features from the final dictionary. These features are mostly interesting for debugging but won't be relevant for most users. """ for loc in proced: try: del loc['all_countries'] except KeyError: pass try: del loc['matrix'] except KeyError: pass try: del loc['all_confidence'] except KeyError: pass try: del loc['place_confidence'] except KeyError: pass try: del loc['text'] except KeyError: pass try: del loc['label'] except KeyError: pass try: del loc['features'] except KeyError: pass return proced
[ "def", "clean_proced", "(", "self", ",", "proced", ")", ":", "for", "loc", "in", "proced", ":", "try", ":", "del", "loc", "[", "'all_countries'", "]", "except", "KeyError", ":", "pass", "try", ":", "del", "loc", "[", "'matrix'", "]", "except", "KeyErro...
Small helper function to delete the features from the final dictionary. These features are mostly interesting for debugging but won't be relevant for most users.
[ "Small", "helper", "function", "to", "delete", "the", "features", "from", "the", "final", "dictionary", ".", "These", "features", "are", "mostly", "interesting", "for", "debugging", "but", "won", "t", "be", "relevant", "for", "most", "users", "." ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L928-L961
train
228,744
openeventdata/mordecai
mordecai/geoparse.py
Geoparser.geoparse
def geoparse(self, doc, verbose=False): """Main geoparsing function. Text to extracted, resolved entities. Parameters ---------- doc : str or spaCy The document to be geoparsed. Can be either raw text or already spacy processed. In some cases, it makes sense to bulk parse using spacy's .pipe() before sending through to Mordecai Returns ------- proced : list of dicts Each entity gets an entry in the list, with the dictionary including geo info, spans, and optionally, the input features. """ if not hasattr(doc, "ents"): doc = nlp(doc) proced = self.infer_country(doc) if not proced: return [] # logging! #print("Nothing came back from infer_country...") if self.threads: pool = ThreadPool(len(proced)) results = pool.map(self.proc_lookup_country, proced) pool.close() pool.join() else: results = [] for loc in proced: # if the confidence is too low, don't use the country info if loc['country_conf'] > self.country_threshold: res = self.query_geonames_country(loc['word'], loc['country_predicted']) results.append(res) else: results.append("") for n, loc in enumerate(proced): res = results[n] try: _ = res['hits']['hits'] # If there's no geonames result, what to do? # For now, just continue. # In the future, delete? Or add an empty "loc" field? except (TypeError, KeyError): continue # Pick the best place X, meta = self.features_for_rank(loc, res) if X.shape[1] == 0: # This happens if there are no results... continue all_tasks, sorted_meta, sorted_X = self.format_for_prodigy(X, meta, loc['word'], return_feature_subset=True) fl_pad = np.pad(sorted_X, ((0, 4 - sorted_X.shape[0]), (0, 0)), 'constant') fl_unwrap = fl_pad.flatten() prediction = self.rank_model.predict(np.asmatrix(fl_unwrap)) place_confidence = prediction.max() loc['geo'] = sorted_meta[prediction.argmax()] loc['place_confidence'] = place_confidence if not verbose: proced = self.clean_proced(proced) return proced
python
def geoparse(self, doc, verbose=False): """Main geoparsing function. Text to extracted, resolved entities. Parameters ---------- doc : str or spaCy The document to be geoparsed. Can be either raw text or already spacy processed. In some cases, it makes sense to bulk parse using spacy's .pipe() before sending through to Mordecai Returns ------- proced : list of dicts Each entity gets an entry in the list, with the dictionary including geo info, spans, and optionally, the input features. """ if not hasattr(doc, "ents"): doc = nlp(doc) proced = self.infer_country(doc) if not proced: return [] # logging! #print("Nothing came back from infer_country...") if self.threads: pool = ThreadPool(len(proced)) results = pool.map(self.proc_lookup_country, proced) pool.close() pool.join() else: results = [] for loc in proced: # if the confidence is too low, don't use the country info if loc['country_conf'] > self.country_threshold: res = self.query_geonames_country(loc['word'], loc['country_predicted']) results.append(res) else: results.append("") for n, loc in enumerate(proced): res = results[n] try: _ = res['hits']['hits'] # If there's no geonames result, what to do? # For now, just continue. # In the future, delete? Or add an empty "loc" field? except (TypeError, KeyError): continue # Pick the best place X, meta = self.features_for_rank(loc, res) if X.shape[1] == 0: # This happens if there are no results... continue all_tasks, sorted_meta, sorted_X = self.format_for_prodigy(X, meta, loc['word'], return_feature_subset=True) fl_pad = np.pad(sorted_X, ((0, 4 - sorted_X.shape[0]), (0, 0)), 'constant') fl_unwrap = fl_pad.flatten() prediction = self.rank_model.predict(np.asmatrix(fl_unwrap)) place_confidence = prediction.max() loc['geo'] = sorted_meta[prediction.argmax()] loc['place_confidence'] = place_confidence if not verbose: proced = self.clean_proced(proced) return proced
[ "def", "geoparse", "(", "self", ",", "doc", ",", "verbose", "=", "False", ")", ":", "if", "not", "hasattr", "(", "doc", ",", "\"ents\"", ")", ":", "doc", "=", "nlp", "(", "doc", ")", "proced", "=", "self", ".", "infer_country", "(", "doc", ")", "...
Main geoparsing function. Text to extracted, resolved entities. Parameters ---------- doc : str or spaCy The document to be geoparsed. Can be either raw text or already spacy processed. In some cases, it makes sense to bulk parse using spacy's .pipe() before sending through to Mordecai Returns ------- proced : list of dicts Each entity gets an entry in the list, with the dictionary including geo info, spans, and optionally, the input features.
[ "Main", "geoparsing", "function", ".", "Text", "to", "extracted", "resolved", "entities", "." ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L963-L1024
train
228,745
openeventdata/mordecai
mordecai/geoparse.py
Geoparser.batch_geoparse
def batch_geoparse(self, text_list): """ Batch geoparsing function. Take in a list of text documents and return a list of lists of the geoparsed documents. The speed improvements come exclusively from using spaCy's `nlp.pipe`. Parameters ---------- text_list : list of strs List of documents. The documents should not have been pre-processed by spaCy. Returns ------- processed : list of list of dictionaries. The list is the same length as the input list of documents. Each element is a list of dicts, one for each geolocated entity. """ if not self.threads: print("batch_geoparsed should be used with threaded searches. Please set `threads=True` when initializing the geoparser.") nlped_docs = list(nlp.pipe(text_list, as_tuples=False, n_threads=multiprocessing.cpu_count())) processed = [] for i in tqdm(nlped_docs, disable=not self.progress): p = self.geoparse(i) processed.append(p) return processed
python
def batch_geoparse(self, text_list): """ Batch geoparsing function. Take in a list of text documents and return a list of lists of the geoparsed documents. The speed improvements come exclusively from using spaCy's `nlp.pipe`. Parameters ---------- text_list : list of strs List of documents. The documents should not have been pre-processed by spaCy. Returns ------- processed : list of list of dictionaries. The list is the same length as the input list of documents. Each element is a list of dicts, one for each geolocated entity. """ if not self.threads: print("batch_geoparsed should be used with threaded searches. Please set `threads=True` when initializing the geoparser.") nlped_docs = list(nlp.pipe(text_list, as_tuples=False, n_threads=multiprocessing.cpu_count())) processed = [] for i in tqdm(nlped_docs, disable=not self.progress): p = self.geoparse(i) processed.append(p) return processed
[ "def", "batch_geoparse", "(", "self", ",", "text_list", ")", ":", "if", "not", "self", ".", "threads", ":", "print", "(", "\"batch_geoparsed should be used with threaded searches. Please set `threads=True` when initializing the geoparser.\"", ")", "nlped_docs", "=", "list", ...
Batch geoparsing function. Take in a list of text documents and return a list of lists of the geoparsed documents. The speed improvements come exclusively from using spaCy's `nlp.pipe`. Parameters ---------- text_list : list of strs List of documents. The documents should not have been pre-processed by spaCy. Returns ------- processed : list of list of dictionaries. The list is the same length as the input list of documents. Each element is a list of dicts, one for each geolocated entity.
[ "Batch", "geoparsing", "function", ".", "Take", "in", "a", "list", "of", "text", "documents", "and", "return", "a", "list", "of", "lists", "of", "the", "geoparsed", "documents", ".", "The", "speed", "improvements", "come", "exclusively", "from", "using", "sp...
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L1027-L1050
train
228,746
openeventdata/mordecai
train/train_country_model.py
entry_to_matrix
def entry_to_matrix(prodigy_entry): """ Take in a line from the labeled json and return a vector of labels and a matrix of features for training. Two ways to get 0s: - marked as false by user - generated automatically from other entries when guess is correct Rather than iterating through entities, just get the number of the correct entity directly. Then get one or two GPEs before and after. """ doc = prodigy_entry['text'] doc = nlp(doc) geo_proced = geo.process_text(doc, require_maj=False) # find the geoproced entity that matches the Prodigy entry ent_text = np.asarray([gp['word'] for gp in geo_proced]) # get mask for correct ent #print(ent_text) match = ent_text == entry['meta']['word'] #print("match: ", match) anti_match = np.abs(match - 1) #print("Anti-match ", anti_match) match_position = match.argmax() geo_proc = geo_proced[match_position] iso = geo.cts[prodigy_entry['label']] # convert country text label to ISO feat = geo.features_to_matrix(geo_proc) answer_x = feat['matrix'] label = np.asarray(feat['labels']) if prodigy_entry['answer'] == "accept": answer_binary = label == iso answer_binary = answer_binary.astype('int') #print(answer_x.shape) #print(answer_binary.shape) elif prodigy_entry['answer'] == "reject": # all we know is that the label that was presented is wrong. # just return the corresponding row in the feature matrix, # and force the label to be 0 answer_binary = label == iso answer_x = answer_x[answer_binary,:] # just take the row corresponding to the answer answer_binary = np.asarray([0]) # set the outcome to 0 because reject # NEED TO SHARE LABELS ACROSS! THE CORRECT ONE MIGHT NOT EVEN APPEAR FOR ALL ENTITIES x = feat['matrix'] other_x = x[anti_match,:] #print(other_x) #print(label[anti_match]) # here, need to get the rows corresponding to the correct label # print(geo_proc['meta']) # here's where we get the other place name features. # Need to: # 1. do features_to_matrix but use the label of the current entity # to determine 0/1 in the feature matrix # 2. put them all into one big feature matrix, # 3. ...ordering by distance? And need to decide max entity length # 4. also include these distances as one of the features #print(answer_x.shape[0]) #print(answer_binary.shape[0]) try: if answer_x.shape[0] == answer_binary.shape[0]: return (answer_x, answer_binary) except: pass
python
def entry_to_matrix(prodigy_entry): """ Take in a line from the labeled json and return a vector of labels and a matrix of features for training. Two ways to get 0s: - marked as false by user - generated automatically from other entries when guess is correct Rather than iterating through entities, just get the number of the correct entity directly. Then get one or two GPEs before and after. """ doc = prodigy_entry['text'] doc = nlp(doc) geo_proced = geo.process_text(doc, require_maj=False) # find the geoproced entity that matches the Prodigy entry ent_text = np.asarray([gp['word'] for gp in geo_proced]) # get mask for correct ent #print(ent_text) match = ent_text == entry['meta']['word'] #print("match: ", match) anti_match = np.abs(match - 1) #print("Anti-match ", anti_match) match_position = match.argmax() geo_proc = geo_proced[match_position] iso = geo.cts[prodigy_entry['label']] # convert country text label to ISO feat = geo.features_to_matrix(geo_proc) answer_x = feat['matrix'] label = np.asarray(feat['labels']) if prodigy_entry['answer'] == "accept": answer_binary = label == iso answer_binary = answer_binary.astype('int') #print(answer_x.shape) #print(answer_binary.shape) elif prodigy_entry['answer'] == "reject": # all we know is that the label that was presented is wrong. # just return the corresponding row in the feature matrix, # and force the label to be 0 answer_binary = label == iso answer_x = answer_x[answer_binary,:] # just take the row corresponding to the answer answer_binary = np.asarray([0]) # set the outcome to 0 because reject # NEED TO SHARE LABELS ACROSS! THE CORRECT ONE MIGHT NOT EVEN APPEAR FOR ALL ENTITIES x = feat['matrix'] other_x = x[anti_match,:] #print(other_x) #print(label[anti_match]) # here, need to get the rows corresponding to the correct label # print(geo_proc['meta']) # here's where we get the other place name features. # Need to: # 1. do features_to_matrix but use the label of the current entity # to determine 0/1 in the feature matrix # 2. put them all into one big feature matrix, # 3. ...ordering by distance? And need to decide max entity length # 4. also include these distances as one of the features #print(answer_x.shape[0]) #print(answer_binary.shape[0]) try: if answer_x.shape[0] == answer_binary.shape[0]: return (answer_x, answer_binary) except: pass
[ "def", "entry_to_matrix", "(", "prodigy_entry", ")", ":", "doc", "=", "prodigy_entry", "[", "'text'", "]", "doc", "=", "nlp", "(", "doc", ")", "geo_proced", "=", "geo", ".", "process_text", "(", "doc", ",", "require_maj", "=", "False", ")", "# find the geo...
Take in a line from the labeled json and return a vector of labels and a matrix of features for training. Two ways to get 0s: - marked as false by user - generated automatically from other entries when guess is correct Rather than iterating through entities, just get the number of the correct entity directly. Then get one or two GPEs before and after.
[ "Take", "in", "a", "line", "from", "the", "labeled", "json", "and", "return", "a", "vector", "of", "labels", "and", "a", "matrix", "of", "features", "for", "training", "." ]
bd82b8bcc27621345c57cbe9ec7f8c8552620ffc
https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/train/train_country_model.py#L22-L92
train
228,747
picklepete/pyicloud
pyicloud/services/findmyiphone.py
FindMyiPhoneServiceManager.refresh_client
def refresh_client(self): """ Refreshes the FindMyiPhoneService endpoint, This ensures that the location data is up-to-date. """ req = self.session.post( self._fmip_refresh_url, params=self.params, data=json.dumps( { 'clientContext': { 'fmly': True, 'shouldLocate': True, 'selectedDevice': 'all', } } ) ) self.response = req.json() for device_info in self.response['content']: device_id = device_info['id'] if device_id not in self._devices: self._devices[device_id] = AppleDevice( device_info, self.session, self.params, manager=self, sound_url=self._fmip_sound_url, lost_url=self._fmip_lost_url, message_url=self._fmip_message_url, ) else: self._devices[device_id].update(device_info) if not self._devices: raise PyiCloudNoDevicesException()
python
def refresh_client(self): """ Refreshes the FindMyiPhoneService endpoint, This ensures that the location data is up-to-date. """ req = self.session.post( self._fmip_refresh_url, params=self.params, data=json.dumps( { 'clientContext': { 'fmly': True, 'shouldLocate': True, 'selectedDevice': 'all', } } ) ) self.response = req.json() for device_info in self.response['content']: device_id = device_info['id'] if device_id not in self._devices: self._devices[device_id] = AppleDevice( device_info, self.session, self.params, manager=self, sound_url=self._fmip_sound_url, lost_url=self._fmip_lost_url, message_url=self._fmip_message_url, ) else: self._devices[device_id].update(device_info) if not self._devices: raise PyiCloudNoDevicesException()
[ "def", "refresh_client", "(", "self", ")", ":", "req", "=", "self", ".", "session", ".", "post", "(", "self", ".", "_fmip_refresh_url", ",", "params", "=", "self", ".", "params", ",", "data", "=", "json", ".", "dumps", "(", "{", "'clientContext'", ":",...
Refreshes the FindMyiPhoneService endpoint, This ensures that the location data is up-to-date.
[ "Refreshes", "the", "FindMyiPhoneService", "endpoint" ]
9bb6d750662ce24c8febc94807ddbdcdf3cadaa2
https://github.com/picklepete/pyicloud/blob/9bb6d750662ce24c8febc94807ddbdcdf3cadaa2/pyicloud/services/findmyiphone.py#L30-L67
train
228,748
picklepete/pyicloud
pyicloud/services/findmyiphone.py
AppleDevice.status
def status(self, additional=[]): """ Returns status information for device. This returns only a subset of possible properties. """ self.manager.refresh_client() fields = ['batteryLevel', 'deviceDisplayName', 'deviceStatus', 'name'] fields += additional properties = {} for field in fields: properties[field] = self.content.get(field) return properties
python
def status(self, additional=[]): """ Returns status information for device. This returns only a subset of possible properties. """ self.manager.refresh_client() fields = ['batteryLevel', 'deviceDisplayName', 'deviceStatus', 'name'] fields += additional properties = {} for field in fields: properties[field] = self.content.get(field) return properties
[ "def", "status", "(", "self", ",", "additional", "=", "[", "]", ")", ":", "self", ".", "manager", ".", "refresh_client", "(", ")", "fields", "=", "[", "'batteryLevel'", ",", "'deviceDisplayName'", ",", "'deviceStatus'", ",", "'name'", "]", "fields", "+=", ...
Returns status information for device. This returns only a subset of possible properties.
[ "Returns", "status", "information", "for", "device", "." ]
9bb6d750662ce24c8febc94807ddbdcdf3cadaa2
https://github.com/picklepete/pyicloud/blob/9bb6d750662ce24c8febc94807ddbdcdf3cadaa2/pyicloud/services/findmyiphone.py#L115-L126
train
228,749
picklepete/pyicloud
pyicloud/services/findmyiphone.py
AppleDevice.lost_device
def lost_device( self, number, text='This iPhone has been lost. Please call me.', newpasscode="" ): """ Send a request to the device to trigger 'lost mode'. The device will show the message in `text`, and if a number has been passed, then the person holding the device can call the number without entering the passcode. """ data = json.dumps({ 'text': text, 'userText': True, 'ownerNbr': number, 'lostModeEnabled': True, 'trackingEnabled': True, 'device': self.content['id'], 'passcode': newpasscode }) self.session.post( self.lost_url, params=self.params, data=data )
python
def lost_device( self, number, text='This iPhone has been lost. Please call me.', newpasscode="" ): """ Send a request to the device to trigger 'lost mode'. The device will show the message in `text`, and if a number has been passed, then the person holding the device can call the number without entering the passcode. """ data = json.dumps({ 'text': text, 'userText': True, 'ownerNbr': number, 'lostModeEnabled': True, 'trackingEnabled': True, 'device': self.content['id'], 'passcode': newpasscode }) self.session.post( self.lost_url, params=self.params, data=data )
[ "def", "lost_device", "(", "self", ",", "number", ",", "text", "=", "'This iPhone has been lost. Please call me.'", ",", "newpasscode", "=", "\"\"", ")", ":", "data", "=", "json", ".", "dumps", "(", "{", "'text'", ":", "text", ",", "'userText'", ":", "True",...
Send a request to the device to trigger 'lost mode'. The device will show the message in `text`, and if a number has been passed, then the person holding the device can call the number without entering the passcode.
[ "Send", "a", "request", "to", "the", "device", "to", "trigger", "lost", "mode", "." ]
9bb6d750662ce24c8febc94807ddbdcdf3cadaa2
https://github.com/picklepete/pyicloud/blob/9bb6d750662ce24c8febc94807ddbdcdf3cadaa2/pyicloud/services/findmyiphone.py#L169-L193
train
228,750
picklepete/pyicloud
pyicloud/services/calendar.py
CalendarService.events
def events(self, from_dt=None, to_dt=None): """ Retrieves events for a given date range, by default, this month. """ self.refresh_client(from_dt, to_dt) return self.response['Event']
python
def events(self, from_dt=None, to_dt=None): """ Retrieves events for a given date range, by default, this month. """ self.refresh_client(from_dt, to_dt) return self.response['Event']
[ "def", "events", "(", "self", ",", "from_dt", "=", "None", ",", "to_dt", "=", "None", ")", ":", "self", ".", "refresh_client", "(", "from_dt", ",", "to_dt", ")", "return", "self", ".", "response", "[", "'Event'", "]" ]
Retrieves events for a given date range, by default, this month.
[ "Retrieves", "events", "for", "a", "given", "date", "range", "by", "default", "this", "month", "." ]
9bb6d750662ce24c8febc94807ddbdcdf3cadaa2
https://github.com/picklepete/pyicloud/blob/9bb6d750662ce24c8febc94807ddbdcdf3cadaa2/pyicloud/services/calendar.py#L58-L63
train
228,751
picklepete/pyicloud
pyicloud/services/calendar.py
CalendarService.calendars
def calendars(self): """ Retrieves calendars for this month """ today = datetime.today() first_day, last_day = monthrange(today.year, today.month) from_dt = datetime(today.year, today.month, first_day) to_dt = datetime(today.year, today.month, last_day) params = dict(self.params) params.update({ 'lang': 'en-us', 'usertz': get_localzone().zone, 'startDate': from_dt.strftime('%Y-%m-%d'), 'endDate': to_dt.strftime('%Y-%m-%d') }) req = self.session.get(self._calendars, params=params) self.response = req.json() return self.response['Collection']
python
def calendars(self): """ Retrieves calendars for this month """ today = datetime.today() first_day, last_day = monthrange(today.year, today.month) from_dt = datetime(today.year, today.month, first_day) to_dt = datetime(today.year, today.month, last_day) params = dict(self.params) params.update({ 'lang': 'en-us', 'usertz': get_localzone().zone, 'startDate': from_dt.strftime('%Y-%m-%d'), 'endDate': to_dt.strftime('%Y-%m-%d') }) req = self.session.get(self._calendars, params=params) self.response = req.json() return self.response['Collection']
[ "def", "calendars", "(", "self", ")", ":", "today", "=", "datetime", ".", "today", "(", ")", "first_day", ",", "last_day", "=", "monthrange", "(", "today", ".", "year", ",", "today", ".", "month", ")", "from_dt", "=", "datetime", "(", "today", ".", "...
Retrieves calendars for this month
[ "Retrieves", "calendars", "for", "this", "month" ]
9bb6d750662ce24c8febc94807ddbdcdf3cadaa2
https://github.com/picklepete/pyicloud/blob/9bb6d750662ce24c8febc94807ddbdcdf3cadaa2/pyicloud/services/calendar.py#L65-L82
train
228,752
picklepete/pyicloud
pyicloud/cmdline.py
create_pickled_data
def create_pickled_data(idevice, filename): """This helper will output the idevice to a pickled file named after the passed filename. This allows the data to be used without resorting to screen / pipe scrapping. """ data = {} for x in idevice.content: data[x] = idevice.content[x] location = filename pickle_file = open(location, 'wb') pickle.dump(data, pickle_file, protocol=pickle.HIGHEST_PROTOCOL) pickle_file.close()
python
def create_pickled_data(idevice, filename): """This helper will output the idevice to a pickled file named after the passed filename. This allows the data to be used without resorting to screen / pipe scrapping. """ data = {} for x in idevice.content: data[x] = idevice.content[x] location = filename pickle_file = open(location, 'wb') pickle.dump(data, pickle_file, protocol=pickle.HIGHEST_PROTOCOL) pickle_file.close()
[ "def", "create_pickled_data", "(", "idevice", ",", "filename", ")", ":", "data", "=", "{", "}", "for", "x", "in", "idevice", ".", "content", ":", "data", "[", "x", "]", "=", "idevice", ".", "content", "[", "x", "]", "location", "=", "filename", "pick...
This helper will output the idevice to a pickled file named after the passed filename. This allows the data to be used without resorting to screen / pipe scrapping.
[ "This", "helper", "will", "output", "the", "idevice", "to", "a", "pickled", "file", "named", "after", "the", "passed", "filename", "." ]
9bb6d750662ce24c8febc94807ddbdcdf3cadaa2
https://github.com/picklepete/pyicloud/blob/9bb6d750662ce24c8febc94807ddbdcdf3cadaa2/pyicloud/cmdline.py#L23-L35
train
228,753
picklepete/pyicloud
pyicloud/services/contacts.py
ContactsService.refresh_client
def refresh_client(self, from_dt=None, to_dt=None): """ Refreshes the ContactsService endpoint, ensuring that the contacts data is up-to-date. """ params_contacts = dict(self.params) params_contacts.update({ 'clientVersion': '2.1', 'locale': 'en_US', 'order': 'last,first', }) req = self.session.get( self._contacts_refresh_url, params=params_contacts ) self.response = req.json() params_refresh = dict(self.params) params_refresh.update({ 'prefToken': req.json()["prefToken"], 'syncToken': req.json()["syncToken"], }) self.session.post(self._contacts_changeset_url, params=params_refresh) req = self.session.get( self._contacts_refresh_url, params=params_contacts ) self.response = req.json()
python
def refresh_client(self, from_dt=None, to_dt=None): """ Refreshes the ContactsService endpoint, ensuring that the contacts data is up-to-date. """ params_contacts = dict(self.params) params_contacts.update({ 'clientVersion': '2.1', 'locale': 'en_US', 'order': 'last,first', }) req = self.session.get( self._contacts_refresh_url, params=params_contacts ) self.response = req.json() params_refresh = dict(self.params) params_refresh.update({ 'prefToken': req.json()["prefToken"], 'syncToken': req.json()["syncToken"], }) self.session.post(self._contacts_changeset_url, params=params_refresh) req = self.session.get( self._contacts_refresh_url, params=params_contacts ) self.response = req.json()
[ "def", "refresh_client", "(", "self", ",", "from_dt", "=", "None", ",", "to_dt", "=", "None", ")", ":", "params_contacts", "=", "dict", "(", "self", ".", "params", ")", "params_contacts", ".", "update", "(", "{", "'clientVersion'", ":", "'2.1'", ",", "'l...
Refreshes the ContactsService endpoint, ensuring that the contacts data is up-to-date.
[ "Refreshes", "the", "ContactsService", "endpoint", "ensuring", "that", "the", "contacts", "data", "is", "up", "-", "to", "-", "date", "." ]
9bb6d750662ce24c8febc94807ddbdcdf3cadaa2
https://github.com/picklepete/pyicloud/blob/9bb6d750662ce24c8febc94807ddbdcdf3cadaa2/pyicloud/services/contacts.py#L20-L46
train
228,754
picklepete/pyicloud
pyicloud/base.py
PyiCloudService.authenticate
def authenticate(self): """ Handles authentication, and persists the X-APPLE-WEB-KB cookie so that subsequent logins will not cause additional e-mails from Apple. """ logger.info("Authenticating as %s", self.user['apple_id']) data = dict(self.user) # We authenticate every time, so "remember me" is not needed data.update({'extended_login': False}) try: req = self.session.post( self._base_login_url, params=self.params, data=json.dumps(data) ) except PyiCloudAPIResponseError as error: msg = 'Invalid email/password combination.' raise PyiCloudFailedLoginException(msg, error) resp = req.json() self.params.update({'dsid': resp['dsInfo']['dsid']}) if not os.path.exists(self._cookie_directory): os.mkdir(self._cookie_directory) self.session.cookies.save() logger.debug("Cookies saved to %s", self._get_cookiejar_path()) self.data = resp self.webservices = self.data['webservices'] logger.info("Authentication completed successfully") logger.debug(self.params)
python
def authenticate(self): """ Handles authentication, and persists the X-APPLE-WEB-KB cookie so that subsequent logins will not cause additional e-mails from Apple. """ logger.info("Authenticating as %s", self.user['apple_id']) data = dict(self.user) # We authenticate every time, so "remember me" is not needed data.update({'extended_login': False}) try: req = self.session.post( self._base_login_url, params=self.params, data=json.dumps(data) ) except PyiCloudAPIResponseError as error: msg = 'Invalid email/password combination.' raise PyiCloudFailedLoginException(msg, error) resp = req.json() self.params.update({'dsid': resp['dsInfo']['dsid']}) if not os.path.exists(self._cookie_directory): os.mkdir(self._cookie_directory) self.session.cookies.save() logger.debug("Cookies saved to %s", self._get_cookiejar_path()) self.data = resp self.webservices = self.data['webservices'] logger.info("Authentication completed successfully") logger.debug(self.params)
[ "def", "authenticate", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Authenticating as %s\"", ",", "self", ".", "user", "[", "'apple_id'", "]", ")", "data", "=", "dict", "(", "self", ".", "user", ")", "# We authenticate every time, so \"remember me\" is ...
Handles authentication, and persists the X-APPLE-WEB-KB cookie so that subsequent logins will not cause additional e-mails from Apple.
[ "Handles", "authentication", "and", "persists", "the", "X", "-", "APPLE", "-", "WEB", "-", "KB", "cookie", "so", "that", "subsequent", "logins", "will", "not", "cause", "additional", "e", "-", "mails", "from", "Apple", "." ]
9bb6d750662ce24c8febc94807ddbdcdf3cadaa2
https://github.com/picklepete/pyicloud/blob/9bb6d750662ce24c8febc94807ddbdcdf3cadaa2/pyicloud/base.py#L195-L230
train
228,755
picklepete/pyicloud
pyicloud/base.py
PyiCloudService.trusted_devices
def trusted_devices(self): """ Returns devices trusted for two-step authentication.""" request = self.session.get( '%s/listDevices' % self._setup_endpoint, params=self.params ) return request.json().get('devices')
python
def trusted_devices(self): """ Returns devices trusted for two-step authentication.""" request = self.session.get( '%s/listDevices' % self._setup_endpoint, params=self.params ) return request.json().get('devices')
[ "def", "trusted_devices", "(", "self", ")", ":", "request", "=", "self", ".", "session", ".", "get", "(", "'%s/listDevices'", "%", "self", ".", "_setup_endpoint", ",", "params", "=", "self", ".", "params", ")", "return", "request", ".", "json", "(", ")",...
Returns devices trusted for two-step authentication.
[ "Returns", "devices", "trusted", "for", "two", "-", "step", "authentication", "." ]
9bb6d750662ce24c8febc94807ddbdcdf3cadaa2
https://github.com/picklepete/pyicloud/blob/9bb6d750662ce24c8febc94807ddbdcdf3cadaa2/pyicloud/base.py#L247-L253
train
228,756
picklepete/pyicloud
pyicloud/base.py
PyiCloudService.send_verification_code
def send_verification_code(self, device): """ Requests that a verification code is sent to the given device""" data = json.dumps(device) request = self.session.post( '%s/sendVerificationCode' % self._setup_endpoint, params=self.params, data=data ) return request.json().get('success', False)
python
def send_verification_code(self, device): """ Requests that a verification code is sent to the given device""" data = json.dumps(device) request = self.session.post( '%s/sendVerificationCode' % self._setup_endpoint, params=self.params, data=data ) return request.json().get('success', False)
[ "def", "send_verification_code", "(", "self", ",", "device", ")", ":", "data", "=", "json", ".", "dumps", "(", "device", ")", "request", "=", "self", ".", "session", ".", "post", "(", "'%s/sendVerificationCode'", "%", "self", ".", "_setup_endpoint", ",", "...
Requests that a verification code is sent to the given device
[ "Requests", "that", "a", "verification", "code", "is", "sent", "to", "the", "given", "device" ]
9bb6d750662ce24c8febc94807ddbdcdf3cadaa2
https://github.com/picklepete/pyicloud/blob/9bb6d750662ce24c8febc94807ddbdcdf3cadaa2/pyicloud/base.py#L255-L263
train
228,757
picklepete/pyicloud
pyicloud/base.py
PyiCloudService.validate_verification_code
def validate_verification_code(self, device, code): """ Verifies a verification code received on a trusted device""" device.update({ 'verificationCode': code, 'trustBrowser': True }) data = json.dumps(device) try: request = self.session.post( '%s/validateVerificationCode' % self._setup_endpoint, params=self.params, data=data ) except PyiCloudAPIResponseError as error: if error.code == -21669: # Wrong verification code return False raise # Re-authenticate, which will both update the HSA data, and # ensure that we save the X-APPLE-WEBAUTH-HSA-TRUST cookie. self.authenticate() return not self.requires_2sa
python
def validate_verification_code(self, device, code): """ Verifies a verification code received on a trusted device""" device.update({ 'verificationCode': code, 'trustBrowser': True }) data = json.dumps(device) try: request = self.session.post( '%s/validateVerificationCode' % self._setup_endpoint, params=self.params, data=data ) except PyiCloudAPIResponseError as error: if error.code == -21669: # Wrong verification code return False raise # Re-authenticate, which will both update the HSA data, and # ensure that we save the X-APPLE-WEBAUTH-HSA-TRUST cookie. self.authenticate() return not self.requires_2sa
[ "def", "validate_verification_code", "(", "self", ",", "device", ",", "code", ")", ":", "device", ".", "update", "(", "{", "'verificationCode'", ":", "code", ",", "'trustBrowser'", ":", "True", "}", ")", "data", "=", "json", ".", "dumps", "(", "device", ...
Verifies a verification code received on a trusted device
[ "Verifies", "a", "verification", "code", "received", "on", "a", "trusted", "device" ]
9bb6d750662ce24c8febc94807ddbdcdf3cadaa2
https://github.com/picklepete/pyicloud/blob/9bb6d750662ce24c8febc94807ddbdcdf3cadaa2/pyicloud/base.py#L265-L289
train
228,758
picklepete/pyicloud
pyicloud/base.py
PyiCloudService.devices
def devices(self): """ Return all devices.""" service_root = self.webservices['findme']['url'] return FindMyiPhoneServiceManager( service_root, self.session, self.params )
python
def devices(self): """ Return all devices.""" service_root = self.webservices['findme']['url'] return FindMyiPhoneServiceManager( service_root, self.session, self.params )
[ "def", "devices", "(", "self", ")", ":", "service_root", "=", "self", ".", "webservices", "[", "'findme'", "]", "[", "'url'", "]", "return", "FindMyiPhoneServiceManager", "(", "service_root", ",", "self", ".", "session", ",", "self", ".", "params", ")" ]
Return all devices.
[ "Return", "all", "devices", "." ]
9bb6d750662ce24c8febc94807ddbdcdf3cadaa2
https://github.com/picklepete/pyicloud/blob/9bb6d750662ce24c8febc94807ddbdcdf3cadaa2/pyicloud/base.py#L292-L299
train
228,759
kennethreitz/grequests
grequests.py
send
def send(r, pool=None, stream=False): """Sends the request object using the specified pool. If a pool isn't specified this method blocks. Pools are useful because you can specify size and can hence limit concurrency.""" if pool is not None: return pool.spawn(r.send, stream=stream) return gevent.spawn(r.send, stream=stream)
python
def send(r, pool=None, stream=False): """Sends the request object using the specified pool. If a pool isn't specified this method blocks. Pools are useful because you can specify size and can hence limit concurrency.""" if pool is not None: return pool.spawn(r.send, stream=stream) return gevent.spawn(r.send, stream=stream)
[ "def", "send", "(", "r", ",", "pool", "=", "None", ",", "stream", "=", "False", ")", ":", "if", "pool", "is", "not", "None", ":", "return", "pool", ".", "spawn", "(", "r", ".", "send", ",", "stream", "=", "stream", ")", "return", "gevent", ".", ...
Sends the request object using the specified pool. If a pool isn't specified this method blocks. Pools are useful because you can specify size and can hence limit concurrency.
[ "Sends", "the", "request", "object", "using", "the", "specified", "pool", ".", "If", "a", "pool", "isn", "t", "specified", "this", "method", "blocks", ".", "Pools", "are", "useful", "because", "you", "can", "specify", "size", "and", "can", "hence", "limit"...
ba25872510e06af213b0c209d204cdc913e3a429
https://github.com/kennethreitz/grequests/blob/ba25872510e06af213b0c209d204cdc913e3a429/grequests.py#L79-L86
train
228,760
kennethreitz/grequests
grequests.py
imap
def imap(requests, stream=False, size=2, exception_handler=None): """Concurrently converts a generator object of Requests to a generator of Responses. :param requests: a generator of Request objects. :param stream: If True, the content will not be downloaded immediately. :param size: Specifies the number of requests to make at a time. default is 2 :param exception_handler: Callback function, called when exception occured. Params: Request, Exception """ pool = Pool(size) def send(r): return r.send(stream=stream) for request in pool.imap_unordered(send, requests): if request.response is not None: yield request.response elif exception_handler: ex_result = exception_handler(request, request.exception) if ex_result is not None: yield ex_result pool.join()
python
def imap(requests, stream=False, size=2, exception_handler=None): """Concurrently converts a generator object of Requests to a generator of Responses. :param requests: a generator of Request objects. :param stream: If True, the content will not be downloaded immediately. :param size: Specifies the number of requests to make at a time. default is 2 :param exception_handler: Callback function, called when exception occured. Params: Request, Exception """ pool = Pool(size) def send(r): return r.send(stream=stream) for request in pool.imap_unordered(send, requests): if request.response is not None: yield request.response elif exception_handler: ex_result = exception_handler(request, request.exception) if ex_result is not None: yield ex_result pool.join()
[ "def", "imap", "(", "requests", ",", "stream", "=", "False", ",", "size", "=", "2", ",", "exception_handler", "=", "None", ")", ":", "pool", "=", "Pool", "(", "size", ")", "def", "send", "(", "r", ")", ":", "return", "r", ".", "send", "(", "strea...
Concurrently converts a generator object of Requests to a generator of Responses. :param requests: a generator of Request objects. :param stream: If True, the content will not be downloaded immediately. :param size: Specifies the number of requests to make at a time. default is 2 :param exception_handler: Callback function, called when exception occured. Params: Request, Exception
[ "Concurrently", "converts", "a", "generator", "object", "of", "Requests", "to", "a", "generator", "of", "Responses", "." ]
ba25872510e06af213b0c209d204cdc913e3a429
https://github.com/kennethreitz/grequests/blob/ba25872510e06af213b0c209d204cdc913e3a429/grequests.py#L132-L155
train
228,761
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.set_user_profile
def set_user_profile(self, displayname=None, avatar_url=None, reason="Changing room profile information"): """Set user profile within a room. This sets displayname and avatar_url for the logged in user only in a specific room. It does not change the user's global user profile. """ member = self.client.api.get_membership(self.room_id, self.client.user_id) if member["membership"] != "join": raise Exception("Can't set profile if you have not joined the room.") if displayname is None: displayname = member["displayname"] if avatar_url is None: avatar_url = member["avatar_url"] self.client.api.set_membership( self.room_id, self.client.user_id, 'join', reason, { "displayname": displayname, "avatar_url": avatar_url } )
python
def set_user_profile(self, displayname=None, avatar_url=None, reason="Changing room profile information"): """Set user profile within a room. This sets displayname and avatar_url for the logged in user only in a specific room. It does not change the user's global user profile. """ member = self.client.api.get_membership(self.room_id, self.client.user_id) if member["membership"] != "join": raise Exception("Can't set profile if you have not joined the room.") if displayname is None: displayname = member["displayname"] if avatar_url is None: avatar_url = member["avatar_url"] self.client.api.set_membership( self.room_id, self.client.user_id, 'join', reason, { "displayname": displayname, "avatar_url": avatar_url } )
[ "def", "set_user_profile", "(", "self", ",", "displayname", "=", "None", ",", "avatar_url", "=", "None", ",", "reason", "=", "\"Changing room profile information\"", ")", ":", "member", "=", "self", ".", "client", ".", "api", ".", "get_membership", "(", "self"...
Set user profile within a room. This sets displayname and avatar_url for the logged in user only in a specific room. It does not change the user's global user profile.
[ "Set", "user", "profile", "within", "a", "room", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L57-L81
train
228,762
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.display_name
def display_name(self): """Calculates the display name for a room.""" if self.name: return self.name elif self.canonical_alias: return self.canonical_alias # Member display names without me members = [u.get_display_name(self) for u in self.get_joined_members() if self.client.user_id != u.user_id] members.sort() if len(members) == 1: return members[0] elif len(members) == 2: return "{0} and {1}".format(members[0], members[1]) elif len(members) > 2: return "{0} and {1} others".format(members[0], len(members) - 1) else: # len(members) <= 0 or not an integer # TODO i18n return "Empty room"
python
def display_name(self): """Calculates the display name for a room.""" if self.name: return self.name elif self.canonical_alias: return self.canonical_alias # Member display names without me members = [u.get_display_name(self) for u in self.get_joined_members() if self.client.user_id != u.user_id] members.sort() if len(members) == 1: return members[0] elif len(members) == 2: return "{0} and {1}".format(members[0], members[1]) elif len(members) > 2: return "{0} and {1} others".format(members[0], len(members) - 1) else: # len(members) <= 0 or not an integer # TODO i18n return "Empty room"
[ "def", "display_name", "(", "self", ")", ":", "if", "self", ".", "name", ":", "return", "self", ".", "name", "elif", "self", ".", "canonical_alias", ":", "return", "self", ".", "canonical_alias", "# Member display names without me", "members", "=", "[", "u", ...
Calculates the display name for a room.
[ "Calculates", "the", "display", "name", "for", "a", "room", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L84-L104
train
228,763
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.send_text
def send_text(self, text): """Send a plain text message to the room.""" return self.client.api.send_message(self.room_id, text)
python
def send_text(self, text): """Send a plain text message to the room.""" return self.client.api.send_message(self.room_id, text)
[ "def", "send_text", "(", "self", ",", "text", ")", ":", "return", "self", ".", "client", ".", "api", ".", "send_message", "(", "self", ".", "room_id", ",", "text", ")" ]
Send a plain text message to the room.
[ "Send", "a", "plain", "text", "message", "to", "the", "room", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L106-L108
train
228,764
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.send_html
def send_html(self, html, body=None, msgtype="m.text"): """Send an html formatted message. Args: html (str): The html formatted message to be sent. body (str): The unformatted body of the message to be sent. """ return self.client.api.send_message_event( self.room_id, "m.room.message", self.get_html_content(html, body, msgtype))
python
def send_html(self, html, body=None, msgtype="m.text"): """Send an html formatted message. Args: html (str): The html formatted message to be sent. body (str): The unformatted body of the message to be sent. """ return self.client.api.send_message_event( self.room_id, "m.room.message", self.get_html_content(html, body, msgtype))
[ "def", "send_html", "(", "self", ",", "html", ",", "body", "=", "None", ",", "msgtype", "=", "\"m.text\"", ")", ":", "return", "self", ".", "client", ".", "api", ".", "send_message_event", "(", "self", ".", "room_id", ",", "\"m.room.message\"", ",", "sel...
Send an html formatted message. Args: html (str): The html formatted message to be sent. body (str): The unformatted body of the message to be sent.
[ "Send", "an", "html", "formatted", "message", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L118-L126
train
228,765
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.send_file
def send_file(self, url, name, **fileinfo): """Send a pre-uploaded file to the room. See http://matrix.org/docs/spec/r0.2.0/client_server.html#m-file for fileinfo. Args: url (str): The mxc url of the file. name (str): The filename of the image. fileinfo (): Extra information about the file """ return self.client.api.send_content( self.room_id, url, name, "m.file", extra_information=fileinfo )
python
def send_file(self, url, name, **fileinfo): """Send a pre-uploaded file to the room. See http://matrix.org/docs/spec/r0.2.0/client_server.html#m-file for fileinfo. Args: url (str): The mxc url of the file. name (str): The filename of the image. fileinfo (): Extra information about the file """ return self.client.api.send_content( self.room_id, url, name, "m.file", extra_information=fileinfo )
[ "def", "send_file", "(", "self", ",", "url", ",", "name", ",", "*", "*", "fileinfo", ")", ":", "return", "self", ".", "client", ".", "api", ".", "send_content", "(", "self", ".", "room_id", ",", "url", ",", "name", ",", "\"m.file\"", ",", "extra_info...
Send a pre-uploaded file to the room. See http://matrix.org/docs/spec/r0.2.0/client_server.html#m-file for fileinfo. Args: url (str): The mxc url of the file. name (str): The filename of the image. fileinfo (): Extra information about the file
[ "Send", "a", "pre", "-", "uploaded", "file", "to", "the", "room", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L150-L165
train
228,766
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.send_image
def send_image(self, url, name, **imageinfo): """Send a pre-uploaded image to the room. See http://matrix.org/docs/spec/r0.0.1/client_server.html#m-image for imageinfo Args: url (str): The mxc url of the image. name (str): The filename of the image. imageinfo (): Extra information about the image. """ return self.client.api.send_content( self.room_id, url, name, "m.image", extra_information=imageinfo )
python
def send_image(self, url, name, **imageinfo): """Send a pre-uploaded image to the room. See http://matrix.org/docs/spec/r0.0.1/client_server.html#m-image for imageinfo Args: url (str): The mxc url of the image. name (str): The filename of the image. imageinfo (): Extra information about the image. """ return self.client.api.send_content( self.room_id, url, name, "m.image", extra_information=imageinfo )
[ "def", "send_image", "(", "self", ",", "url", ",", "name", ",", "*", "*", "imageinfo", ")", ":", "return", "self", ".", "client", ".", "api", ".", "send_content", "(", "self", ".", "room_id", ",", "url", ",", "name", ",", "\"m.image\"", ",", "extra_i...
Send a pre-uploaded image to the room. See http://matrix.org/docs/spec/r0.0.1/client_server.html#m-image for imageinfo Args: url (str): The mxc url of the image. name (str): The filename of the image. imageinfo (): Extra information about the image.
[ "Send", "a", "pre", "-", "uploaded", "image", "to", "the", "room", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L173-L187
train
228,767
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.send_location
def send_location(self, geo_uri, name, thumb_url=None, **thumb_info): """Send a location to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-location for thumb_info Args: geo_uri (str): The geo uri representing the location. name (str): Description for the location. thumb_url (str): URL to the thumbnail of the location. thumb_info (): Metadata about the thumbnail, type ImageInfo. """ return self.client.api.send_location(self.room_id, geo_uri, name, thumb_url, thumb_info)
python
def send_location(self, geo_uri, name, thumb_url=None, **thumb_info): """Send a location to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-location for thumb_info Args: geo_uri (str): The geo uri representing the location. name (str): Description for the location. thumb_url (str): URL to the thumbnail of the location. thumb_info (): Metadata about the thumbnail, type ImageInfo. """ return self.client.api.send_location(self.room_id, geo_uri, name, thumb_url, thumb_info)
[ "def", "send_location", "(", "self", ",", "geo_uri", ",", "name", ",", "thumb_url", "=", "None", ",", "*", "*", "thumb_info", ")", ":", "return", "self", ".", "client", ".", "api", ".", "send_location", "(", "self", ".", "room_id", ",", "geo_uri", ",",...
Send a location to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-location for thumb_info Args: geo_uri (str): The geo uri representing the location. name (str): Description for the location. thumb_url (str): URL to the thumbnail of the location. thumb_info (): Metadata about the thumbnail, type ImageInfo.
[ "Send", "a", "location", "to", "the", "room", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L189-L202
train
228,768
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.send_video
def send_video(self, url, name, **videoinfo): """Send a pre-uploaded video to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-video for videoinfo Args: url (str): The mxc url of the video. name (str): The filename of the video. videoinfo (): Extra information about the video. """ return self.client.api.send_content(self.room_id, url, name, "m.video", extra_information=videoinfo)
python
def send_video(self, url, name, **videoinfo): """Send a pre-uploaded video to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-video for videoinfo Args: url (str): The mxc url of the video. name (str): The filename of the video. videoinfo (): Extra information about the video. """ return self.client.api.send_content(self.room_id, url, name, "m.video", extra_information=videoinfo)
[ "def", "send_video", "(", "self", ",", "url", ",", "name", ",", "*", "*", "videoinfo", ")", ":", "return", "self", ".", "client", ".", "api", ".", "send_content", "(", "self", ".", "room_id", ",", "url", ",", "name", ",", "\"m.video\"", ",", "extra_i...
Send a pre-uploaded video to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-video for videoinfo Args: url (str): The mxc url of the video. name (str): The filename of the video. videoinfo (): Extra information about the video.
[ "Send", "a", "pre", "-", "uploaded", "video", "to", "the", "room", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L204-L216
train
228,769
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.send_audio
def send_audio(self, url, name, **audioinfo): """Send a pre-uploaded audio to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-audio for audioinfo Args: url (str): The mxc url of the audio. name (str): The filename of the audio. audioinfo (): Extra information about the audio. """ return self.client.api.send_content(self.room_id, url, name, "m.audio", extra_information=audioinfo)
python
def send_audio(self, url, name, **audioinfo): """Send a pre-uploaded audio to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-audio for audioinfo Args: url (str): The mxc url of the audio. name (str): The filename of the audio. audioinfo (): Extra information about the audio. """ return self.client.api.send_content(self.room_id, url, name, "m.audio", extra_information=audioinfo)
[ "def", "send_audio", "(", "self", ",", "url", ",", "name", ",", "*", "*", "audioinfo", ")", ":", "return", "self", ".", "client", ".", "api", ".", "send_content", "(", "self", ".", "room_id", ",", "url", ",", "name", ",", "\"m.audio\"", ",", "extra_i...
Send a pre-uploaded audio to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-audio for audioinfo Args: url (str): The mxc url of the audio. name (str): The filename of the audio. audioinfo (): Extra information about the audio.
[ "Send", "a", "pre", "-", "uploaded", "audio", "to", "the", "room", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L218-L230
train
228,770
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.redact_message
def redact_message(self, event_id, reason=None): """Redacts the message with specified event_id for the given reason. See https://matrix.org/docs/spec/r0.0.1/client_server.html#id112 """ return self.client.api.redact_event(self.room_id, event_id, reason)
python
def redact_message(self, event_id, reason=None): """Redacts the message with specified event_id for the given reason. See https://matrix.org/docs/spec/r0.0.1/client_server.html#id112 """ return self.client.api.redact_event(self.room_id, event_id, reason)
[ "def", "redact_message", "(", "self", ",", "event_id", ",", "reason", "=", "None", ")", ":", "return", "self", ".", "client", ".", "api", ".", "redact_event", "(", "self", ".", "room_id", ",", "event_id", ",", "reason", ")" ]
Redacts the message with specified event_id for the given reason. See https://matrix.org/docs/spec/r0.0.1/client_server.html#id112
[ "Redacts", "the", "message", "with", "specified", "event_id", "for", "the", "given", "reason", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L232-L237
train
228,771
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.add_listener
def add_listener(self, callback, event_type=None): """Add a callback handler for events going to this room. Args: callback (func(room, event)): Callback called when an event arrives. event_type (str): The event_type to filter for. Returns: uuid.UUID: Unique id of the listener, can be used to identify the listener. """ listener_id = uuid4() self.listeners.append( { 'uid': listener_id, 'callback': callback, 'event_type': event_type } ) return listener_id
python
def add_listener(self, callback, event_type=None): """Add a callback handler for events going to this room. Args: callback (func(room, event)): Callback called when an event arrives. event_type (str): The event_type to filter for. Returns: uuid.UUID: Unique id of the listener, can be used to identify the listener. """ listener_id = uuid4() self.listeners.append( { 'uid': listener_id, 'callback': callback, 'event_type': event_type } ) return listener_id
[ "def", "add_listener", "(", "self", ",", "callback", ",", "event_type", "=", "None", ")", ":", "listener_id", "=", "uuid4", "(", ")", "self", ".", "listeners", ".", "append", "(", "{", "'uid'", ":", "listener_id", ",", "'callback'", ":", "callback", ",",...
Add a callback handler for events going to this room. Args: callback (func(room, event)): Callback called when an event arrives. event_type (str): The event_type to filter for. Returns: uuid.UUID: Unique id of the listener, can be used to identify the listener.
[ "Add", "a", "callback", "handler", "for", "events", "going", "to", "this", "room", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L239-L256
train
228,772
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.remove_listener
def remove_listener(self, uid): """Remove listener with given uid.""" self.listeners[:] = (listener for listener in self.listeners if listener['uid'] != uid)
python
def remove_listener(self, uid): """Remove listener with given uid.""" self.listeners[:] = (listener for listener in self.listeners if listener['uid'] != uid)
[ "def", "remove_listener", "(", "self", ",", "uid", ")", ":", "self", ".", "listeners", "[", ":", "]", "=", "(", "listener", "for", "listener", "in", "self", ".", "listeners", "if", "listener", "[", "'uid'", "]", "!=", "uid", ")" ]
Remove listener with given uid.
[ "Remove", "listener", "with", "given", "uid", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L258-L261
train
228,773
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.add_ephemeral_listener
def add_ephemeral_listener(self, callback, event_type=None): """Add a callback handler for ephemeral events going to this room. Args: callback (func(room, event)): Callback called when an ephemeral event arrives. event_type (str): The event_type to filter for. Returns: uuid.UUID: Unique id of the listener, can be used to identify the listener. """ listener_id = uuid4() self.ephemeral_listeners.append( { 'uid': listener_id, 'callback': callback, 'event_type': event_type } ) return listener_id
python
def add_ephemeral_listener(self, callback, event_type=None): """Add a callback handler for ephemeral events going to this room. Args: callback (func(room, event)): Callback called when an ephemeral event arrives. event_type (str): The event_type to filter for. Returns: uuid.UUID: Unique id of the listener, can be used to identify the listener. """ listener_id = uuid4() self.ephemeral_listeners.append( { 'uid': listener_id, 'callback': callback, 'event_type': event_type } ) return listener_id
[ "def", "add_ephemeral_listener", "(", "self", ",", "callback", ",", "event_type", "=", "None", ")", ":", "listener_id", "=", "uuid4", "(", ")", "self", ".", "ephemeral_listeners", ".", "append", "(", "{", "'uid'", ":", "listener_id", ",", "'callback'", ":", ...
Add a callback handler for ephemeral events going to this room. Args: callback (func(room, event)): Callback called when an ephemeral event arrives. event_type (str): The event_type to filter for. Returns: uuid.UUID: Unique id of the listener, can be used to identify the listener.
[ "Add", "a", "callback", "handler", "for", "ephemeral", "events", "going", "to", "this", "room", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L263-L280
train
228,774
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.remove_ephemeral_listener
def remove_ephemeral_listener(self, uid): """Remove ephemeral listener with given uid.""" self.ephemeral_listeners[:] = (listener for listener in self.ephemeral_listeners if listener['uid'] != uid)
python
def remove_ephemeral_listener(self, uid): """Remove ephemeral listener with given uid.""" self.ephemeral_listeners[:] = (listener for listener in self.ephemeral_listeners if listener['uid'] != uid)
[ "def", "remove_ephemeral_listener", "(", "self", ",", "uid", ")", ":", "self", ".", "ephemeral_listeners", "[", ":", "]", "=", "(", "listener", "for", "listener", "in", "self", ".", "ephemeral_listeners", "if", "listener", "[", "'uid'", "]", "!=", "uid", "...
Remove ephemeral listener with given uid.
[ "Remove", "ephemeral", "listener", "with", "given", "uid", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L282-L285
train
228,775
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.invite_user
def invite_user(self, user_id): """Invite a user to this room. Returns: boolean: Whether invitation was sent. """ try: self.client.api.invite_user(self.room_id, user_id) return True except MatrixRequestError: return False
python
def invite_user(self, user_id): """Invite a user to this room. Returns: boolean: Whether invitation was sent. """ try: self.client.api.invite_user(self.room_id, user_id) return True except MatrixRequestError: return False
[ "def", "invite_user", "(", "self", ",", "user_id", ")", ":", "try", ":", "self", ".", "client", ".", "api", ".", "invite_user", "(", "self", ".", "room_id", ",", "user_id", ")", "return", "True", "except", "MatrixRequestError", ":", "return", "False" ]
Invite a user to this room. Returns: boolean: Whether invitation was sent.
[ "Invite", "a", "user", "to", "this", "room", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L323-L333
train
228,776
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.kick_user
def kick_user(self, user_id, reason=""): """Kick a user from this room. Args: user_id (str): The matrix user id of a user. reason (str): A reason for kicking the user. Returns: boolean: Whether user was kicked. """ try: self.client.api.kick_user(self.room_id, user_id) return True except MatrixRequestError: return False
python
def kick_user(self, user_id, reason=""): """Kick a user from this room. Args: user_id (str): The matrix user id of a user. reason (str): A reason for kicking the user. Returns: boolean: Whether user was kicked. """ try: self.client.api.kick_user(self.room_id, user_id) return True except MatrixRequestError: return False
[ "def", "kick_user", "(", "self", ",", "user_id", ",", "reason", "=", "\"\"", ")", ":", "try", ":", "self", ".", "client", ".", "api", ".", "kick_user", "(", "self", ".", "room_id", ",", "user_id", ")", "return", "True", "except", "MatrixRequestError", ...
Kick a user from this room. Args: user_id (str): The matrix user id of a user. reason (str): A reason for kicking the user. Returns: boolean: Whether user was kicked.
[ "Kick", "a", "user", "from", "this", "room", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L335-L350
train
228,777
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.leave
def leave(self): """Leave the room. Returns: boolean: Leaving the room was successful. """ try: self.client.api.leave_room(self.room_id) del self.client.rooms[self.room_id] return True except MatrixRequestError: return False
python
def leave(self): """Leave the room. Returns: boolean: Leaving the room was successful. """ try: self.client.api.leave_room(self.room_id) del self.client.rooms[self.room_id] return True except MatrixRequestError: return False
[ "def", "leave", "(", "self", ")", ":", "try", ":", "self", ".", "client", ".", "api", ".", "leave_room", "(", "self", ".", "room_id", ")", "del", "self", ".", "client", ".", "rooms", "[", "self", ".", "room_id", "]", "return", "True", "except", "Ma...
Leave the room. Returns: boolean: Leaving the room was successful.
[ "Leave", "the", "room", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L380-L391
train
228,778
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.update_room_name
def update_room_name(self): """Updates self.name and returns True if room name has changed.""" try: response = self.client.api.get_room_name(self.room_id) if "name" in response and response["name"] != self.name: self.name = response["name"] return True else: return False except MatrixRequestError: return False
python
def update_room_name(self): """Updates self.name and returns True if room name has changed.""" try: response = self.client.api.get_room_name(self.room_id) if "name" in response and response["name"] != self.name: self.name = response["name"] return True else: return False except MatrixRequestError: return False
[ "def", "update_room_name", "(", "self", ")", ":", "try", ":", "response", "=", "self", ".", "client", ".", "api", ".", "get_room_name", "(", "self", ".", "room_id", ")", "if", "\"name\"", "in", "response", "and", "response", "[", "\"name\"", "]", "!=", ...
Updates self.name and returns True if room name has changed.
[ "Updates", "self", ".", "name", "and", "returns", "True", "if", "room", "name", "has", "changed", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L393-L403
train
228,779
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.set_room_name
def set_room_name(self, name): """Return True if room name successfully changed.""" try: self.client.api.set_room_name(self.room_id, name) self.name = name return True except MatrixRequestError: return False
python
def set_room_name(self, name): """Return True if room name successfully changed.""" try: self.client.api.set_room_name(self.room_id, name) self.name = name return True except MatrixRequestError: return False
[ "def", "set_room_name", "(", "self", ",", "name", ")", ":", "try", ":", "self", ".", "client", ".", "api", ".", "set_room_name", "(", "self", ".", "room_id", ",", "name", ")", "self", ".", "name", "=", "name", "return", "True", "except", "MatrixRequest...
Return True if room name successfully changed.
[ "Return", "True", "if", "room", "name", "successfully", "changed", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L405-L412
train
228,780
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.send_state_event
def send_state_event(self, event_type, content, state_key=""): """Send a state event to the room. Args: event_type (str): The type of event that you are sending. content (): An object with the content of the message. state_key (str, optional): A unique key to identify the state. """ return self.client.api.send_state_event( self.room_id, event_type, content, state_key )
python
def send_state_event(self, event_type, content, state_key=""): """Send a state event to the room. Args: event_type (str): The type of event that you are sending. content (): An object with the content of the message. state_key (str, optional): A unique key to identify the state. """ return self.client.api.send_state_event( self.room_id, event_type, content, state_key )
[ "def", "send_state_event", "(", "self", ",", "event_type", ",", "content", ",", "state_key", "=", "\"\"", ")", ":", "return", "self", ".", "client", ".", "api", ".", "send_state_event", "(", "self", ".", "room_id", ",", "event_type", ",", "content", ",", ...
Send a state event to the room. Args: event_type (str): The type of event that you are sending. content (): An object with the content of the message. state_key (str, optional): A unique key to identify the state.
[ "Send", "a", "state", "event", "to", "the", "room", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L414-L427
train
228,781
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.update_room_topic
def update_room_topic(self): """Updates self.topic and returns True if room topic has changed.""" try: response = self.client.api.get_room_topic(self.room_id) if "topic" in response and response["topic"] != self.topic: self.topic = response["topic"] return True else: return False except MatrixRequestError: return False
python
def update_room_topic(self): """Updates self.topic and returns True if room topic has changed.""" try: response = self.client.api.get_room_topic(self.room_id) if "topic" in response and response["topic"] != self.topic: self.topic = response["topic"] return True else: return False except MatrixRequestError: return False
[ "def", "update_room_topic", "(", "self", ")", ":", "try", ":", "response", "=", "self", ".", "client", ".", "api", ".", "get_room_topic", "(", "self", ".", "room_id", ")", "if", "\"topic\"", "in", "response", "and", "response", "[", "\"topic\"", "]", "!=...
Updates self.topic and returns True if room topic has changed.
[ "Updates", "self", ".", "topic", "and", "returns", "True", "if", "room", "topic", "has", "changed", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L429-L439
train
228,782
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.set_room_topic
def set_room_topic(self, topic): """Set room topic. Returns: boolean: True if the topic changed, False if not """ try: self.client.api.set_room_topic(self.room_id, topic) self.topic = topic return True except MatrixRequestError: return False
python
def set_room_topic(self, topic): """Set room topic. Returns: boolean: True if the topic changed, False if not """ try: self.client.api.set_room_topic(self.room_id, topic) self.topic = topic return True except MatrixRequestError: return False
[ "def", "set_room_topic", "(", "self", ",", "topic", ")", ":", "try", ":", "self", ".", "client", ".", "api", ".", "set_room_topic", "(", "self", ".", "room_id", ",", "topic", ")", "self", ".", "topic", "=", "topic", "return", "True", "except", "MatrixR...
Set room topic. Returns: boolean: True if the topic changed, False if not
[ "Set", "room", "topic", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L441-L452
train
228,783
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.update_aliases
def update_aliases(self): """Get aliases information from room state. Returns: boolean: True if the aliases changed, False if not """ try: response = self.client.api.get_room_state(self.room_id) for chunk in response: if "content" in chunk and "aliases" in chunk["content"]: if chunk["content"]["aliases"] != self.aliases: self.aliases = chunk["content"]["aliases"] return True else: return False except MatrixRequestError: return False
python
def update_aliases(self): """Get aliases information from room state. Returns: boolean: True if the aliases changed, False if not """ try: response = self.client.api.get_room_state(self.room_id) for chunk in response: if "content" in chunk and "aliases" in chunk["content"]: if chunk["content"]["aliases"] != self.aliases: self.aliases = chunk["content"]["aliases"] return True else: return False except MatrixRequestError: return False
[ "def", "update_aliases", "(", "self", ")", ":", "try", ":", "response", "=", "self", ".", "client", ".", "api", ".", "get_room_state", "(", "self", ".", "room_id", ")", "for", "chunk", "in", "response", ":", "if", "\"content\"", "in", "chunk", "and", "...
Get aliases information from room state. Returns: boolean: True if the aliases changed, False if not
[ "Get", "aliases", "information", "from", "room", "state", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L454-L470
train
228,784
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.add_room_alias
def add_room_alias(self, room_alias): """Add an alias to the room and return True if successful.""" try: self.client.api.set_room_alias(self.room_id, room_alias) return True except MatrixRequestError: return False
python
def add_room_alias(self, room_alias): """Add an alias to the room and return True if successful.""" try: self.client.api.set_room_alias(self.room_id, room_alias) return True except MatrixRequestError: return False
[ "def", "add_room_alias", "(", "self", ",", "room_alias", ")", ":", "try", ":", "self", ".", "client", ".", "api", ".", "set_room_alias", "(", "self", ".", "room_id", ",", "room_alias", ")", "return", "True", "except", "MatrixRequestError", ":", "return", "...
Add an alias to the room and return True if successful.
[ "Add", "an", "alias", "to", "the", "room", "and", "return", "True", "if", "successful", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L472-L478
train
228,785
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.backfill_previous_messages
def backfill_previous_messages(self, reverse=False, limit=10): """Backfill handling of previous messages. Args: reverse (bool): When false messages will be backfilled in their original order (old to new), otherwise the order will be reversed (new to old). limit (int): Number of messages to go back. """ res = self.client.api.get_room_messages(self.room_id, self.prev_batch, direction="b", limit=limit) events = res["chunk"] if not reverse: events = reversed(events) for event in events: self._put_event(event)
python
def backfill_previous_messages(self, reverse=False, limit=10): """Backfill handling of previous messages. Args: reverse (bool): When false messages will be backfilled in their original order (old to new), otherwise the order will be reversed (new to old). limit (int): Number of messages to go back. """ res = self.client.api.get_room_messages(self.room_id, self.prev_batch, direction="b", limit=limit) events = res["chunk"] if not reverse: events = reversed(events) for event in events: self._put_event(event)
[ "def", "backfill_previous_messages", "(", "self", ",", "reverse", "=", "False", ",", "limit", "=", "10", ")", ":", "res", "=", "self", ".", "client", ".", "api", ".", "get_room_messages", "(", "self", ".", "room_id", ",", "self", ".", "prev_batch", ",", ...
Backfill handling of previous messages. Args: reverse (bool): When false messages will be backfilled in their original order (old to new), otherwise the order will be reversed (new to old). limit (int): Number of messages to go back.
[ "Backfill", "handling", "of", "previous", "messages", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L502-L516
train
228,786
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.modify_user_power_levels
def modify_user_power_levels(self, users=None, users_default=None): """Modify the power level for a subset of users Args: users(dict): Power levels to assign to specific users, in the form {"@name0:host0": 10, "@name1:host1": 100, "@name3:host3", None} A level of None causes the user to revert to the default level as specified by users_default. users_default(int): Default power level for users in the room Returns: True if successful, False if not """ try: content = self.client.api.get_power_levels(self.room_id) if users_default: content["users_default"] = users_default if users: if "users" in content: content["users"].update(users) else: content["users"] = users # Remove any keys with value None for user, power_level in list(content["users"].items()): if power_level is None: del content["users"][user] self.client.api.set_power_levels(self.room_id, content) return True except MatrixRequestError: return False
python
def modify_user_power_levels(self, users=None, users_default=None): """Modify the power level for a subset of users Args: users(dict): Power levels to assign to specific users, in the form {"@name0:host0": 10, "@name1:host1": 100, "@name3:host3", None} A level of None causes the user to revert to the default level as specified by users_default. users_default(int): Default power level for users in the room Returns: True if successful, False if not """ try: content = self.client.api.get_power_levels(self.room_id) if users_default: content["users_default"] = users_default if users: if "users" in content: content["users"].update(users) else: content["users"] = users # Remove any keys with value None for user, power_level in list(content["users"].items()): if power_level is None: del content["users"][user] self.client.api.set_power_levels(self.room_id, content) return True except MatrixRequestError: return False
[ "def", "modify_user_power_levels", "(", "self", ",", "users", "=", "None", ",", "users_default", "=", "None", ")", ":", "try", ":", "content", "=", "self", ".", "client", ".", "api", ".", "get_power_levels", "(", "self", ".", "room_id", ")", "if", "users...
Modify the power level for a subset of users Args: users(dict): Power levels to assign to specific users, in the form {"@name0:host0": 10, "@name1:host1": 100, "@name3:host3", None} A level of None causes the user to revert to the default level as specified by users_default. users_default(int): Default power level for users in the room Returns: True if successful, False if not
[ "Modify", "the", "power", "level", "for", "a", "subset", "of", "users" ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L518-L549
train
228,787
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.modify_required_power_levels
def modify_required_power_levels(self, events=None, **kwargs): """Modifies room power level requirements. Args: events(dict): Power levels required for sending specific event types, in the form {"m.room.whatever0": 60, "m.room.whatever2": None}. Overrides events_default and state_default for the specified events. A level of None causes the target event to revert to the default level as specified by events_default or state_default. **kwargs: Key/value pairs specifying the power levels required for various actions: - events_default(int): Default level for sending message events - state_default(int): Default level for sending state events - invite(int): Inviting a user - redact(int): Redacting an event - ban(int): Banning a user - kick(int): Kicking a user Returns: True if successful, False if not """ try: content = self.client.api.get_power_levels(self.room_id) content.update(kwargs) for key, value in list(content.items()): if value is None: del content[key] if events: if "events" in content: content["events"].update(events) else: content["events"] = events # Remove any keys with value None for event, power_level in list(content["events"].items()): if power_level is None: del content["events"][event] self.client.api.set_power_levels(self.room_id, content) return True except MatrixRequestError: return False
python
def modify_required_power_levels(self, events=None, **kwargs): """Modifies room power level requirements. Args: events(dict): Power levels required for sending specific event types, in the form {"m.room.whatever0": 60, "m.room.whatever2": None}. Overrides events_default and state_default for the specified events. A level of None causes the target event to revert to the default level as specified by events_default or state_default. **kwargs: Key/value pairs specifying the power levels required for various actions: - events_default(int): Default level for sending message events - state_default(int): Default level for sending state events - invite(int): Inviting a user - redact(int): Redacting an event - ban(int): Banning a user - kick(int): Kicking a user Returns: True if successful, False if not """ try: content = self.client.api.get_power_levels(self.room_id) content.update(kwargs) for key, value in list(content.items()): if value is None: del content[key] if events: if "events" in content: content["events"].update(events) else: content["events"] = events # Remove any keys with value None for event, power_level in list(content["events"].items()): if power_level is None: del content["events"][event] self.client.api.set_power_levels(self.room_id, content) return True except MatrixRequestError: return False
[ "def", "modify_required_power_levels", "(", "self", ",", "events", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "content", "=", "self", ".", "client", ".", "api", ".", "get_power_levels", "(", "self", ".", "room_id", ")", "content", ".", ...
Modifies room power level requirements. Args: events(dict): Power levels required for sending specific event types, in the form {"m.room.whatever0": 60, "m.room.whatever2": None}. Overrides events_default and state_default for the specified events. A level of None causes the target event to revert to the default level as specified by events_default or state_default. **kwargs: Key/value pairs specifying the power levels required for various actions: - events_default(int): Default level for sending message events - state_default(int): Default level for sending state events - invite(int): Inviting a user - redact(int): Redacting an event - ban(int): Banning a user - kick(int): Kicking a user Returns: True if successful, False if not
[ "Modifies", "room", "power", "level", "requirements", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L551-L594
train
228,788
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.set_invite_only
def set_invite_only(self, invite_only): """Set how the room can be joined. Args: invite_only(bool): If True, users will have to be invited to join the room. If False, anyone who knows the room link can join. Returns: True if successful, False if not """ join_rule = "invite" if invite_only else "public" try: self.client.api.set_join_rule(self.room_id, join_rule) self.invite_only = invite_only return True except MatrixRequestError: return False
python
def set_invite_only(self, invite_only): """Set how the room can be joined. Args: invite_only(bool): If True, users will have to be invited to join the room. If False, anyone who knows the room link can join. Returns: True if successful, False if not """ join_rule = "invite" if invite_only else "public" try: self.client.api.set_join_rule(self.room_id, join_rule) self.invite_only = invite_only return True except MatrixRequestError: return False
[ "def", "set_invite_only", "(", "self", ",", "invite_only", ")", ":", "join_rule", "=", "\"invite\"", "if", "invite_only", "else", "\"public\"", "try", ":", "self", ".", "client", ".", "api", ".", "set_join_rule", "(", "self", ".", "room_id", ",", "join_rule"...
Set how the room can be joined. Args: invite_only(bool): If True, users will have to be invited to join the room. If False, anyone who knows the room link can join. Returns: True if successful, False if not
[ "Set", "how", "the", "room", "can", "be", "joined", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L596-L612
train
228,789
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.set_guest_access
def set_guest_access(self, allow_guests): """Set whether guests can join the room and return True if successful.""" guest_access = "can_join" if allow_guests else "forbidden" try: self.client.api.set_guest_access(self.room_id, guest_access) self.guest_access = allow_guests return True except MatrixRequestError: return False
python
def set_guest_access(self, allow_guests): """Set whether guests can join the room and return True if successful.""" guest_access = "can_join" if allow_guests else "forbidden" try: self.client.api.set_guest_access(self.room_id, guest_access) self.guest_access = allow_guests return True except MatrixRequestError: return False
[ "def", "set_guest_access", "(", "self", ",", "allow_guests", ")", ":", "guest_access", "=", "\"can_join\"", "if", "allow_guests", "else", "\"forbidden\"", "try", ":", "self", ".", "client", ".", "api", ".", "set_guest_access", "(", "self", ".", "room_id", ",",...
Set whether guests can join the room and return True if successful.
[ "Set", "whether", "guests", "can", "join", "the", "room", "and", "return", "True", "if", "successful", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L614-L622
train
228,790
matrix-org/matrix-python-sdk
matrix_client/room.py
Room.enable_encryption
def enable_encryption(self): """Enables encryption in the room. NOTE: Once enabled, encryption cannot be disabled. Returns: True if successful, False if not """ try: self.send_state_event("m.room.encryption", {"algorithm": "m.megolm.v1.aes-sha2"}) self.encrypted = True return True except MatrixRequestError: return False
python
def enable_encryption(self): """Enables encryption in the room. NOTE: Once enabled, encryption cannot be disabled. Returns: True if successful, False if not """ try: self.send_state_event("m.room.encryption", {"algorithm": "m.megolm.v1.aes-sha2"}) self.encrypted = True return True except MatrixRequestError: return False
[ "def", "enable_encryption", "(", "self", ")", ":", "try", ":", "self", ".", "send_state_event", "(", "\"m.room.encryption\"", ",", "{", "\"algorithm\"", ":", "\"m.megolm.v1.aes-sha2\"", "}", ")", "self", ".", "encrypted", "=", "True", "return", "True", "except",...
Enables encryption in the room. NOTE: Once enabled, encryption cannot be disabled. Returns: True if successful, False if not
[ "Enables", "encryption", "in", "the", "room", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L624-L638
train
228,791
matrix-org/matrix-python-sdk
samples/UserPassOrTokenClient.py
example
def example(host, user, password, token): """run the example.""" client = None try: if token: print('token login') client = MatrixClient(host, token=token, user_id=user) else: print('password login') client = MatrixClient(host) token = client.login_with_password(user, password) print('got token: %s' % token) except MatrixRequestError as e: print(e) if e.code == 403: print("Bad username or password") exit(2) elif e.code == 401: print("Bad username or token") exit(3) else: print("Verify server details.") exit(4) except MissingSchema as e: print(e) print("Bad formatting of URL.") exit(5) except InvalidSchema as e: print(e) print("Invalid URL schema") exit(6) print("is in rooms") for room_id, room in client.get_rooms().items(): print(room_id)
python
def example(host, user, password, token): """run the example.""" client = None try: if token: print('token login') client = MatrixClient(host, token=token, user_id=user) else: print('password login') client = MatrixClient(host) token = client.login_with_password(user, password) print('got token: %s' % token) except MatrixRequestError as e: print(e) if e.code == 403: print("Bad username or password") exit(2) elif e.code == 401: print("Bad username or token") exit(3) else: print("Verify server details.") exit(4) except MissingSchema as e: print(e) print("Bad formatting of URL.") exit(5) except InvalidSchema as e: print(e) print("Invalid URL schema") exit(6) print("is in rooms") for room_id, room in client.get_rooms().items(): print(room_id)
[ "def", "example", "(", "host", ",", "user", ",", "password", ",", "token", ")", ":", "client", "=", "None", "try", ":", "if", "token", ":", "print", "(", "'token login'", ")", "client", "=", "MatrixClient", "(", "host", ",", "token", "=", "token", ",...
run the example.
[ "run", "the", "example", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/samples/UserPassOrTokenClient.py#L24-L57
train
228,792
matrix-org/matrix-python-sdk
samples/UserPassOrTokenClient.py
main
def main(): """Main entry.""" parser = argparse.ArgumentParser() parser.add_argument("--host", type=str, required=True) parser.add_argument("--user", type=str, required=True) parser.add_argument("--password", type=str) parser.add_argument("--token", type=str) args = parser.parse_args() if not args.password and not args.token: print('password or token is required') exit(1) example(args.host, args.user, args.password, args.token)
python
def main(): """Main entry.""" parser = argparse.ArgumentParser() parser.add_argument("--host", type=str, required=True) parser.add_argument("--user", type=str, required=True) parser.add_argument("--password", type=str) parser.add_argument("--token", type=str) args = parser.parse_args() if not args.password and not args.token: print('password or token is required') exit(1) example(args.host, args.user, args.password, args.token)
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"--host\"", ",", "type", "=", "str", ",", "required", "=", "True", ")", "parser", ".", "add_argument", "(", "\"--user\"", ",",...
Main entry.
[ "Main", "entry", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/samples/UserPassOrTokenClient.py#L60-L71
train
228,793
matrix-org/matrix-python-sdk
matrix_client/api.py
MatrixHttpApi.sync
def sync(self, since=None, timeout_ms=30000, filter=None, full_state=None, set_presence=None): """ Perform a sync request. Args: since (str): Optional. A token which specifies where to continue a sync from. timeout_ms (int): Optional. The time in milliseconds to wait. filter (int|str): Either a Filter ID or a JSON string. full_state (bool): Return the full state for every room the user has joined Defaults to false. set_presence (str): Should the client be marked as "online" or" offline" """ request = { # non-integer timeouts appear to cause issues "timeout": int(timeout_ms) } if since: request["since"] = since if filter: request["filter"] = filter if full_state: request["full_state"] = json.dumps(full_state) if set_presence: request["set_presence"] = set_presence return self._send("GET", "/sync", query_params=request, api_path=MATRIX_V2_API_PATH)
python
def sync(self, since=None, timeout_ms=30000, filter=None, full_state=None, set_presence=None): """ Perform a sync request. Args: since (str): Optional. A token which specifies where to continue a sync from. timeout_ms (int): Optional. The time in milliseconds to wait. filter (int|str): Either a Filter ID or a JSON string. full_state (bool): Return the full state for every room the user has joined Defaults to false. set_presence (str): Should the client be marked as "online" or" offline" """ request = { # non-integer timeouts appear to cause issues "timeout": int(timeout_ms) } if since: request["since"] = since if filter: request["filter"] = filter if full_state: request["full_state"] = json.dumps(full_state) if set_presence: request["set_presence"] = set_presence return self._send("GET", "/sync", query_params=request, api_path=MATRIX_V2_API_PATH)
[ "def", "sync", "(", "self", ",", "since", "=", "None", ",", "timeout_ms", "=", "30000", ",", "filter", "=", "None", ",", "full_state", "=", "None", ",", "set_presence", "=", "None", ")", ":", "request", "=", "{", "# non-integer timeouts appear to cause issue...
Perform a sync request. Args: since (str): Optional. A token which specifies where to continue a sync from. timeout_ms (int): Optional. The time in milliseconds to wait. filter (int|str): Either a Filter ID or a JSON string. full_state (bool): Return the full state for every room the user has joined Defaults to false. set_presence (str): Should the client be marked as "online" or" offline"
[ "Perform", "a", "sync", "request", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L92-L123
train
228,794
matrix-org/matrix-python-sdk
matrix_client/api.py
MatrixHttpApi.send_location
def send_location(self, room_id, geo_uri, name, thumb_url=None, thumb_info=None, timestamp=None): """Send m.location message event Args: room_id (str): The room ID to send the event in. geo_uri (str): The geo uri representing the location. name (str): Description for the location. thumb_url (str): URL to the thumbnail of the location. thumb_info (dict): Metadata about the thumbnail, type ImageInfo. timestamp (int): Set origin_server_ts (For application services only) """ content_pack = { "geo_uri": geo_uri, "msgtype": "m.location", "body": name, } if thumb_url: content_pack["thumbnail_url"] = thumb_url if thumb_info: content_pack["thumbnail_info"] = thumb_info return self.send_message_event(room_id, "m.room.message", content_pack, timestamp=timestamp)
python
def send_location(self, room_id, geo_uri, name, thumb_url=None, thumb_info=None, timestamp=None): """Send m.location message event Args: room_id (str): The room ID to send the event in. geo_uri (str): The geo uri representing the location. name (str): Description for the location. thumb_url (str): URL to the thumbnail of the location. thumb_info (dict): Metadata about the thumbnail, type ImageInfo. timestamp (int): Set origin_server_ts (For application services only) """ content_pack = { "geo_uri": geo_uri, "msgtype": "m.location", "body": name, } if thumb_url: content_pack["thumbnail_url"] = thumb_url if thumb_info: content_pack["thumbnail_info"] = thumb_info return self.send_message_event(room_id, "m.room.message", content_pack, timestamp=timestamp)
[ "def", "send_location", "(", "self", ",", "room_id", ",", "geo_uri", ",", "name", ",", "thumb_url", "=", "None", ",", "thumb_info", "=", "None", ",", "timestamp", "=", "None", ")", ":", "content_pack", "=", "{", "\"geo_uri\"", ":", "geo_uri", ",", "\"msg...
Send m.location message event Args: room_id (str): The room ID to send the event in. geo_uri (str): The geo uri representing the location. name (str): Description for the location. thumb_url (str): URL to the thumbnail of the location. thumb_info (dict): Metadata about the thumbnail, type ImageInfo. timestamp (int): Set origin_server_ts (For application services only)
[ "Send", "m", ".", "location", "message", "event" ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L351-L374
train
228,795
matrix-org/matrix-python-sdk
matrix_client/api.py
MatrixHttpApi.kick_user
def kick_user(self, room_id, user_id, reason=""): """Calls set_membership with membership="leave" for the user_id provided """ self.set_membership(room_id, user_id, "leave", reason)
python
def kick_user(self, room_id, user_id, reason=""): """Calls set_membership with membership="leave" for the user_id provided """ self.set_membership(room_id, user_id, "leave", reason)
[ "def", "kick_user", "(", "self", ",", "room_id", ",", "user_id", ",", "reason", "=", "\"\"", ")", ":", "self", ".", "set_membership", "(", "room_id", ",", "user_id", ",", "\"leave\"", ",", "reason", ")" ]
Calls set_membership with membership="leave" for the user_id provided
[ "Calls", "set_membership", "with", "membership", "=", "leave", "for", "the", "user_id", "provided" ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L555-L558
train
228,796
matrix-org/matrix-python-sdk
matrix_client/api.py
MatrixHttpApi.media_download
def media_download(self, mxcurl, allow_remote=True): """Download raw media from provided mxc URL. Args: mxcurl (str): mxc media URL. allow_remote (bool): indicates to the server that it should not attempt to fetch the media if it is deemed remote. Defaults to true if not provided. """ query_params = {} if not allow_remote: query_params["allow_remote"] = False if mxcurl.startswith('mxc://'): return self._send( "GET", mxcurl[6:], api_path="/_matrix/media/r0/download/", query_params=query_params, return_json=False ) else: raise ValueError( "MXC URL '%s' did not begin with 'mxc://'" % mxcurl )
python
def media_download(self, mxcurl, allow_remote=True): """Download raw media from provided mxc URL. Args: mxcurl (str): mxc media URL. allow_remote (bool): indicates to the server that it should not attempt to fetch the media if it is deemed remote. Defaults to true if not provided. """ query_params = {} if not allow_remote: query_params["allow_remote"] = False if mxcurl.startswith('mxc://'): return self._send( "GET", mxcurl[6:], api_path="/_matrix/media/r0/download/", query_params=query_params, return_json=False ) else: raise ValueError( "MXC URL '%s' did not begin with 'mxc://'" % mxcurl )
[ "def", "media_download", "(", "self", ",", "mxcurl", ",", "allow_remote", "=", "True", ")", ":", "query_params", "=", "{", "}", "if", "not", "allow_remote", ":", "query_params", "[", "\"allow_remote\"", "]", "=", "False", "if", "mxcurl", ".", "startswith", ...
Download raw media from provided mxc URL. Args: mxcurl (str): mxc media URL. allow_remote (bool): indicates to the server that it should not attempt to fetch the media if it is deemed remote. Defaults to true if not provided.
[ "Download", "raw", "media", "from", "provided", "mxc", "URL", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L791-L813
train
228,797
matrix-org/matrix-python-sdk
matrix_client/api.py
MatrixHttpApi.get_thumbnail
def get_thumbnail(self, mxcurl, width, height, method='scale', allow_remote=True): """Download raw media thumbnail from provided mxc URL. Args: mxcurl (str): mxc media URL width (int): desired thumbnail width height (int): desired thumbnail height method (str): thumb creation method. Must be in ['scale', 'crop']. Default 'scale'. allow_remote (bool): indicates to the server that it should not attempt to fetch the media if it is deemed remote. Defaults to true if not provided. """ if method not in ['scale', 'crop']: raise ValueError( "Unsupported thumb method '%s'" % method ) query_params = { "width": width, "height": height, "method": method } if not allow_remote: query_params["allow_remote"] = False if mxcurl.startswith('mxc://'): return self._send( "GET", mxcurl[6:], query_params=query_params, api_path="/_matrix/media/r0/thumbnail/", return_json=False ) else: raise ValueError( "MXC URL '%s' did not begin with 'mxc://'" % mxcurl )
python
def get_thumbnail(self, mxcurl, width, height, method='scale', allow_remote=True): """Download raw media thumbnail from provided mxc URL. Args: mxcurl (str): mxc media URL width (int): desired thumbnail width height (int): desired thumbnail height method (str): thumb creation method. Must be in ['scale', 'crop']. Default 'scale'. allow_remote (bool): indicates to the server that it should not attempt to fetch the media if it is deemed remote. Defaults to true if not provided. """ if method not in ['scale', 'crop']: raise ValueError( "Unsupported thumb method '%s'" % method ) query_params = { "width": width, "height": height, "method": method } if not allow_remote: query_params["allow_remote"] = False if mxcurl.startswith('mxc://'): return self._send( "GET", mxcurl[6:], query_params=query_params, api_path="/_matrix/media/r0/thumbnail/", return_json=False ) else: raise ValueError( "MXC URL '%s' did not begin with 'mxc://'" % mxcurl )
[ "def", "get_thumbnail", "(", "self", ",", "mxcurl", ",", "width", ",", "height", ",", "method", "=", "'scale'", ",", "allow_remote", "=", "True", ")", ":", "if", "method", "not", "in", "[", "'scale'", ",", "'crop'", "]", ":", "raise", "ValueError", "("...
Download raw media thumbnail from provided mxc URL. Args: mxcurl (str): mxc media URL width (int): desired thumbnail width height (int): desired thumbnail height method (str): thumb creation method. Must be in ['scale', 'crop']. Default 'scale'. allow_remote (bool): indicates to the server that it should not attempt to fetch the media if it is deemed remote. Defaults to true if not provided.
[ "Download", "raw", "media", "thumbnail", "from", "provided", "mxc", "URL", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L815-L849
train
228,798
matrix-org/matrix-python-sdk
matrix_client/api.py
MatrixHttpApi.get_url_preview
def get_url_preview(self, url, ts=None): """Get preview for URL. Args: url (str): URL to get a preview ts (double): The preferred point in time to return a preview for. The server may return a newer version if it does not have the requested version available. """ params = {'url': url} if ts: params['ts'] = ts return self._send( "GET", "", query_params=params, api_path="/_matrix/media/r0/preview_url" )
python
def get_url_preview(self, url, ts=None): """Get preview for URL. Args: url (str): URL to get a preview ts (double): The preferred point in time to return a preview for. The server may return a newer version if it does not have the requested version available. """ params = {'url': url} if ts: params['ts'] = ts return self._send( "GET", "", query_params=params, api_path="/_matrix/media/r0/preview_url" )
[ "def", "get_url_preview", "(", "self", ",", "url", ",", "ts", "=", "None", ")", ":", "params", "=", "{", "'url'", ":", "url", "}", "if", "ts", ":", "params", "[", "'ts'", "]", "=", "ts", "return", "self", ".", "_send", "(", "\"GET\"", ",", "\"\""...
Get preview for URL. Args: url (str): URL to get a preview ts (double): The preferred point in time to return a preview for. The server may return a newer version if it does not have the requested version available.
[ "Get", "preview", "for", "URL", "." ]
e734cce3ccd35f2d355c6a19a7a701033472498a
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L851-L868
train
228,799