id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
247,700 | 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):
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 |
247,701 | 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):
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 |
247,702 | 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):
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 |
247,703 | 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):
# 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 |
247,704 | 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):
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 |
247,705 | 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):
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 |
247,706 | 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):
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 |
247,707 | 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):
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 |
247,708 | 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):
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 |
247,709 | 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):
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 |
247,710 | 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):
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 |
247,711 | 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=[]):
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 |
247,712 | 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=""
):
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 |
247,713 | 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):
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 |
247,714 | 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):
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 |
247,715 | 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):
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 |
247,716 | 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):
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 |
247,717 | 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):
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 |
247,718 | 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):
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 |
247,719 | 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):
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 |
247,720 | 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):
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 |
247,721 | 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):
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 |
247,722 | 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):
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 |
247,723 | 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):
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 |
247,724 | 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"):
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 |
247,725 | 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):
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 |
247,726 | 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):
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 |
247,727 | 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"):
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 |
247,728 | 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):
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 |
247,729 | 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):
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 |
247,730 | 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):
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 |
247,731 | 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):
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 |
247,732 | 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):
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 |
247,733 | 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):
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 |
247,734 | 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):
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 |
247,735 | 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):
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 |
247,736 | 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):
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 |
247,737 | 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):
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 |
247,738 | 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):
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 |
247,739 | 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=""):
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 |
247,740 | 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):
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 |
247,741 | 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):
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 |
247,742 | 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):
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 |
247,743 | 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=""):
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 |
247,744 | 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):
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 |
247,745 | 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):
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 |
247,746 | 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):
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 |
247,747 | 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):
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 |
247,748 | 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):
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 |
247,749 | 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):
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 |
247,750 | 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):
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 |
247,751 | 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):
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 |
247,752 | 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):
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 |
247,753 | 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):
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 |
247,754 | 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):
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 |
247,755 | 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():
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 |
247,756 | 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):
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 |
247,757 | 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):
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 |
247,758 | 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=""):
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 |
247,759 | 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):
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 |
247,760 | 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):
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 |
247,761 | 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):
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 |
247,762 | matrix-org/matrix-python-sdk | matrix_client/api.py | MatrixHttpApi.get_room_id | def get_room_id(self, room_alias):
"""Get room id from its alias.
Args:
room_alias (str): The room alias name.
Returns:
Wanted room's id.
"""
content = self._send("GET", "/directory/room/{}".format(quote(room_alias)))
return content.get("room_id", None) | python | def get_room_id(self, room_alias):
content = self._send("GET", "/directory/room/{}".format(quote(room_alias)))
return content.get("room_id", None) | [
"def",
"get_room_id",
"(",
"self",
",",
"room_alias",
")",
":",
"content",
"=",
"self",
".",
"_send",
"(",
"\"GET\"",
",",
"\"/directory/room/{}\"",
".",
"format",
"(",
"quote",
"(",
"room_alias",
")",
")",
")",
"return",
"content",
".",
"get",
"(",
"\"r... | Get room id from its alias.
Args:
room_alias (str): The room alias name.
Returns:
Wanted room's id. | [
"Get",
"room",
"id",
"from",
"its",
"alias",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L870-L880 |
247,763 | matrix-org/matrix-python-sdk | matrix_client/api.py | MatrixHttpApi.set_room_alias | def set_room_alias(self, room_id, room_alias):
"""Set alias to room id
Args:
room_id (str): The room id.
room_alias (str): The room wanted alias name.
"""
data = {
"room_id": room_id
}
return self._send("PUT", "/directory/room/{}".format(quote(room_alias)),
content=data) | python | def set_room_alias(self, room_id, room_alias):
data = {
"room_id": room_id
}
return self._send("PUT", "/directory/room/{}".format(quote(room_alias)),
content=data) | [
"def",
"set_room_alias",
"(",
"self",
",",
"room_id",
",",
"room_alias",
")",
":",
"data",
"=",
"{",
"\"room_id\"",
":",
"room_id",
"}",
"return",
"self",
".",
"_send",
"(",
"\"PUT\"",
",",
"\"/directory/room/{}\"",
".",
"format",
"(",
"quote",
"(",
"room_... | Set alias to room id
Args:
room_id (str): The room id.
room_alias (str): The room wanted alias name. | [
"Set",
"alias",
"to",
"room",
"id"
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L882-L894 |
247,764 | matrix-org/matrix-python-sdk | matrix_client/api.py | MatrixHttpApi.set_join_rule | def set_join_rule(self, room_id, join_rule):
"""Set the rule for users wishing to join the room.
Args:
room_id(str): The room to set the rules for.
join_rule(str): The chosen rule. One of: ["public", "knock",
"invite", "private"]
"""
content = {
"join_rule": join_rule
}
return self.send_state_event(room_id, "m.room.join_rules", content) | python | def set_join_rule(self, room_id, join_rule):
content = {
"join_rule": join_rule
}
return self.send_state_event(room_id, "m.room.join_rules", content) | [
"def",
"set_join_rule",
"(",
"self",
",",
"room_id",
",",
"join_rule",
")",
":",
"content",
"=",
"{",
"\"join_rule\"",
":",
"join_rule",
"}",
"return",
"self",
".",
"send_state_event",
"(",
"room_id",
",",
"\"m.room.join_rules\"",
",",
"content",
")"
] | Set the rule for users wishing to join the room.
Args:
room_id(str): The room to set the rules for.
join_rule(str): The chosen rule. One of: ["public", "knock",
"invite", "private"] | [
"Set",
"the",
"rule",
"for",
"users",
"wishing",
"to",
"join",
"the",
"room",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L915-L926 |
247,765 | matrix-org/matrix-python-sdk | matrix_client/api.py | MatrixHttpApi.set_guest_access | def set_guest_access(self, room_id, guest_access):
"""Set the guest access policy of the room.
Args:
room_id(str): The room to set the rules for.
guest_access(str): Wether guests can join. One of: ["can_join",
"forbidden"]
"""
content = {
"guest_access": guest_access
}
return self.send_state_event(room_id, "m.room.guest_access", content) | python | def set_guest_access(self, room_id, guest_access):
content = {
"guest_access": guest_access
}
return self.send_state_event(room_id, "m.room.guest_access", content) | [
"def",
"set_guest_access",
"(",
"self",
",",
"room_id",
",",
"guest_access",
")",
":",
"content",
"=",
"{",
"\"guest_access\"",
":",
"guest_access",
"}",
"return",
"self",
".",
"send_state_event",
"(",
"room_id",
",",
"\"m.room.guest_access\"",
",",
"content",
"... | Set the guest access policy of the room.
Args:
room_id(str): The room to set the rules for.
guest_access(str): Wether guests can join. One of: ["can_join",
"forbidden"] | [
"Set",
"the",
"guest",
"access",
"policy",
"of",
"the",
"room",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L928-L939 |
247,766 | matrix-org/matrix-python-sdk | matrix_client/api.py | MatrixHttpApi.update_device_info | def update_device_info(self, device_id, display_name):
"""Update the display name of a device.
Args:
device_id (str): The device ID of the device to update.
display_name (str): New display name for the device.
"""
content = {
"display_name": display_name
}
return self._send("PUT", "/devices/%s" % device_id, content=content) | python | def update_device_info(self, device_id, display_name):
content = {
"display_name": display_name
}
return self._send("PUT", "/devices/%s" % device_id, content=content) | [
"def",
"update_device_info",
"(",
"self",
",",
"device_id",
",",
"display_name",
")",
":",
"content",
"=",
"{",
"\"display_name\"",
":",
"display_name",
"}",
"return",
"self",
".",
"_send",
"(",
"\"PUT\"",
",",
"\"/devices/%s\"",
"%",
"device_id",
",",
"conten... | Update the display name of a device.
Args:
device_id (str): The device ID of the device to update.
display_name (str): New display name for the device. | [
"Update",
"the",
"display",
"name",
"of",
"a",
"device",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L949-L959 |
247,767 | matrix-org/matrix-python-sdk | matrix_client/api.py | MatrixHttpApi.delete_device | def delete_device(self, auth_body, device_id):
"""Deletes the given device, and invalidates any access token associated with it.
NOTE: This endpoint uses the User-Interactive Authentication API.
Args:
auth_body (dict): Authentication params.
device_id (str): The device ID of the device to delete.
"""
content = {
"auth": auth_body
}
return self._send("DELETE", "/devices/%s" % device_id, content=content) | python | def delete_device(self, auth_body, device_id):
content = {
"auth": auth_body
}
return self._send("DELETE", "/devices/%s" % device_id, content=content) | [
"def",
"delete_device",
"(",
"self",
",",
"auth_body",
",",
"device_id",
")",
":",
"content",
"=",
"{",
"\"auth\"",
":",
"auth_body",
"}",
"return",
"self",
".",
"_send",
"(",
"\"DELETE\"",
",",
"\"/devices/%s\"",
"%",
"device_id",
",",
"content",
"=",
"co... | Deletes the given device, and invalidates any access token associated with it.
NOTE: This endpoint uses the User-Interactive Authentication API.
Args:
auth_body (dict): Authentication params.
device_id (str): The device ID of the device to delete. | [
"Deletes",
"the",
"given",
"device",
"and",
"invalidates",
"any",
"access",
"token",
"associated",
"with",
"it",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L961-L973 |
247,768 | matrix-org/matrix-python-sdk | matrix_client/api.py | MatrixHttpApi.delete_devices | def delete_devices(self, auth_body, devices):
"""Bulk deletion of devices.
NOTE: This endpoint uses the User-Interactive Authentication API.
Args:
auth_body (dict): Authentication params.
devices (list): List of device ID"s to delete.
"""
content = {
"auth": auth_body,
"devices": devices
}
return self._send("POST", "/delete_devices", content=content) | python | def delete_devices(self, auth_body, devices):
content = {
"auth": auth_body,
"devices": devices
}
return self._send("POST", "/delete_devices", content=content) | [
"def",
"delete_devices",
"(",
"self",
",",
"auth_body",
",",
"devices",
")",
":",
"content",
"=",
"{",
"\"auth\"",
":",
"auth_body",
",",
"\"devices\"",
":",
"devices",
"}",
"return",
"self",
".",
"_send",
"(",
"\"POST\"",
",",
"\"/delete_devices\"",
",",
... | Bulk deletion of devices.
NOTE: This endpoint uses the User-Interactive Authentication API.
Args:
auth_body (dict): Authentication params.
devices (list): List of device ID"s to delete. | [
"Bulk",
"deletion",
"of",
"devices",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L975-L988 |
247,769 | matrix-org/matrix-python-sdk | matrix_client/api.py | MatrixHttpApi.upload_keys | def upload_keys(self, device_keys=None, one_time_keys=None):
"""Publishes end-to-end encryption keys for the device.
Said device must be the one used when logging in.
Args:
device_keys (dict): Optional. Identity keys for the device. The required
keys are:
| user_id (str): The ID of the user the device belongs to. Must match
the user ID used when logging in.
| device_id (str): The ID of the device these keys belong to. Must match
the device ID used when logging in.
| algorithms (list<str>): The encryption algorithms supported by this
device.
| keys (dict): Public identity keys. Should be formatted as
<algorithm:device_id>: <key>.
| signatures (dict): Signatures for the device key object. Should be
formatted as <user_id>: {<algorithm:device_id>: <key>}
one_time_keys (dict): Optional. One-time public keys. Should be
formatted as <algorithm:key_id>: <key>, the key format being
determined by the algorithm.
"""
content = {}
if device_keys:
content["device_keys"] = device_keys
if one_time_keys:
content["one_time_keys"] = one_time_keys
return self._send("POST", "/keys/upload", content=content) | python | def upload_keys(self, device_keys=None, one_time_keys=None):
content = {}
if device_keys:
content["device_keys"] = device_keys
if one_time_keys:
content["one_time_keys"] = one_time_keys
return self._send("POST", "/keys/upload", content=content) | [
"def",
"upload_keys",
"(",
"self",
",",
"device_keys",
"=",
"None",
",",
"one_time_keys",
"=",
"None",
")",
":",
"content",
"=",
"{",
"}",
"if",
"device_keys",
":",
"content",
"[",
"\"device_keys\"",
"]",
"=",
"device_keys",
"if",
"one_time_keys",
":",
"co... | Publishes end-to-end encryption keys for the device.
Said device must be the one used when logging in.
Args:
device_keys (dict): Optional. Identity keys for the device. The required
keys are:
| user_id (str): The ID of the user the device belongs to. Must match
the user ID used when logging in.
| device_id (str): The ID of the device these keys belong to. Must match
the device ID used when logging in.
| algorithms (list<str>): The encryption algorithms supported by this
device.
| keys (dict): Public identity keys. Should be formatted as
<algorithm:device_id>: <key>.
| signatures (dict): Signatures for the device key object. Should be
formatted as <user_id>: {<algorithm:device_id>: <key>}
one_time_keys (dict): Optional. One-time public keys. Should be
formatted as <algorithm:key_id>: <key>, the key format being
determined by the algorithm. | [
"Publishes",
"end",
"-",
"to",
"-",
"end",
"encryption",
"keys",
"for",
"the",
"device",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L990-L1019 |
247,770 | matrix-org/matrix-python-sdk | matrix_client/api.py | MatrixHttpApi.query_keys | def query_keys(self, user_devices, timeout=None, token=None):
"""Query HS for public keys by user and optionally device.
Args:
user_devices (dict): The devices whose keys to download. Should be
formatted as <user_id>: [<device_ids>]. No device_ids indicates
all devices for the corresponding user.
timeout (int): Optional. The time (in milliseconds) to wait when
downloading keys from remote servers.
token (str): Optional. If the client is fetching keys as a result of
a device update received in a sync request, this should be the
'since' token of that sync request, or any later sync token.
"""
content = {"device_keys": user_devices}
if timeout:
content["timeout"] = timeout
if token:
content["token"] = token
return self._send("POST", "/keys/query", content=content) | python | def query_keys(self, user_devices, timeout=None, token=None):
content = {"device_keys": user_devices}
if timeout:
content["timeout"] = timeout
if token:
content["token"] = token
return self._send("POST", "/keys/query", content=content) | [
"def",
"query_keys",
"(",
"self",
",",
"user_devices",
",",
"timeout",
"=",
"None",
",",
"token",
"=",
"None",
")",
":",
"content",
"=",
"{",
"\"device_keys\"",
":",
"user_devices",
"}",
"if",
"timeout",
":",
"content",
"[",
"\"timeout\"",
"]",
"=",
"tim... | Query HS for public keys by user and optionally device.
Args:
user_devices (dict): The devices whose keys to download. Should be
formatted as <user_id>: [<device_ids>]. No device_ids indicates
all devices for the corresponding user.
timeout (int): Optional. The time (in milliseconds) to wait when
downloading keys from remote servers.
token (str): Optional. If the client is fetching keys as a result of
a device update received in a sync request, this should be the
'since' token of that sync request, or any later sync token. | [
"Query",
"HS",
"for",
"public",
"keys",
"by",
"user",
"and",
"optionally",
"device",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L1021-L1039 |
247,771 | matrix-org/matrix-python-sdk | matrix_client/api.py | MatrixHttpApi.claim_keys | def claim_keys(self, key_request, timeout=None):
"""Claims one-time keys for use in pre-key messages.
Args:
key_request (dict): The keys to be claimed. Format should be
<user_id>: { <device_id>: <algorithm> }.
timeout (int): Optional. The time (in milliseconds) to wait when
downloading keys from remote servers.
"""
content = {"one_time_keys": key_request}
if timeout:
content["timeout"] = timeout
return self._send("POST", "/keys/claim", content=content) | python | def claim_keys(self, key_request, timeout=None):
content = {"one_time_keys": key_request}
if timeout:
content["timeout"] = timeout
return self._send("POST", "/keys/claim", content=content) | [
"def",
"claim_keys",
"(",
"self",
",",
"key_request",
",",
"timeout",
"=",
"None",
")",
":",
"content",
"=",
"{",
"\"one_time_keys\"",
":",
"key_request",
"}",
"if",
"timeout",
":",
"content",
"[",
"\"timeout\"",
"]",
"=",
"timeout",
"return",
"self",
".",... | Claims one-time keys for use in pre-key messages.
Args:
key_request (dict): The keys to be claimed. Format should be
<user_id>: { <device_id>: <algorithm> }.
timeout (int): Optional. The time (in milliseconds) to wait when
downloading keys from remote servers. | [
"Claims",
"one",
"-",
"time",
"keys",
"for",
"use",
"in",
"pre",
"-",
"key",
"messages",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L1041-L1053 |
247,772 | matrix-org/matrix-python-sdk | matrix_client/api.py | MatrixHttpApi.key_changes | def key_changes(self, from_token, to_token):
"""Gets a list of users who have updated their device identity keys.
Args:
from_token (str): The desired start point of the list. Should be the
next_batch field from a response to an earlier call to /sync.
to_token (str): The desired end point of the list. Should be the next_batch
field from a recent call to /sync - typically the most recent such call.
"""
params = {"from": from_token, "to": to_token}
return self._send("GET", "/keys/changes", query_params=params) | python | def key_changes(self, from_token, to_token):
params = {"from": from_token, "to": to_token}
return self._send("GET", "/keys/changes", query_params=params) | [
"def",
"key_changes",
"(",
"self",
",",
"from_token",
",",
"to_token",
")",
":",
"params",
"=",
"{",
"\"from\"",
":",
"from_token",
",",
"\"to\"",
":",
"to_token",
"}",
"return",
"self",
".",
"_send",
"(",
"\"GET\"",
",",
"\"/keys/changes\"",
",",
"query_p... | Gets a list of users who have updated their device identity keys.
Args:
from_token (str): The desired start point of the list. Should be the
next_batch field from a response to an earlier call to /sync.
to_token (str): The desired end point of the list. Should be the next_batch
field from a recent call to /sync - typically the most recent such call. | [
"Gets",
"a",
"list",
"of",
"users",
"who",
"have",
"updated",
"their",
"device",
"identity",
"keys",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L1055-L1065 |
247,773 | matrix-org/matrix-python-sdk | matrix_client/api.py | MatrixHttpApi.send_to_device | def send_to_device(self, event_type, messages, txn_id=None):
"""Sends send-to-device events to a set of client devices.
Args:
event_type (str): The type of event to send.
messages (dict): The messages to send. Format should be
<user_id>: {<device_id>: <event_content>}.
The device ID may also be '*', meaning all known devices for the user.
txn_id (str): Optional. The transaction ID for this event, will be generated
automatically otherwise.
"""
txn_id = txn_id if txn_id else self._make_txn_id()
return self._send(
"PUT",
"/sendToDevice/{}/{}".format(event_type, txn_id),
content={"messages": messages}
) | python | def send_to_device(self, event_type, messages, txn_id=None):
txn_id = txn_id if txn_id else self._make_txn_id()
return self._send(
"PUT",
"/sendToDevice/{}/{}".format(event_type, txn_id),
content={"messages": messages}
) | [
"def",
"send_to_device",
"(",
"self",
",",
"event_type",
",",
"messages",
",",
"txn_id",
"=",
"None",
")",
":",
"txn_id",
"=",
"txn_id",
"if",
"txn_id",
"else",
"self",
".",
"_make_txn_id",
"(",
")",
"return",
"self",
".",
"_send",
"(",
"\"PUT\"",
",",
... | Sends send-to-device events to a set of client devices.
Args:
event_type (str): The type of event to send.
messages (dict): The messages to send. Format should be
<user_id>: {<device_id>: <event_content>}.
The device ID may also be '*', meaning all known devices for the user.
txn_id (str): Optional. The transaction ID for this event, will be generated
automatically otherwise. | [
"Sends",
"send",
"-",
"to",
"-",
"device",
"events",
"to",
"a",
"set",
"of",
"client",
"devices",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L1067-L1083 |
247,774 | matrix-org/matrix-python-sdk | matrix_client/client.py | MatrixClient.register_with_password | def register_with_password(self, username, password):
""" Register for a new account on this HS.
Args:
username (str): Account username
password (str): Account password
Returns:
str: Access Token
Raises:
MatrixRequestError
"""
response = self.api.register(
auth_body={"type": "m.login.dummy"},
kind='user',
username=username,
password=password,
)
return self._post_registration(response) | python | def register_with_password(self, username, password):
response = self.api.register(
auth_body={"type": "m.login.dummy"},
kind='user',
username=username,
password=password,
)
return self._post_registration(response) | [
"def",
"register_with_password",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"response",
"=",
"self",
".",
"api",
".",
"register",
"(",
"auth_body",
"=",
"{",
"\"type\"",
":",
"\"m.login.dummy\"",
"}",
",",
"kind",
"=",
"'user'",
",",
"usernam... | Register for a new account on this HS.
Args:
username (str): Account username
password (str): Account password
Returns:
str: Access Token
Raises:
MatrixRequestError | [
"Register",
"for",
"a",
"new",
"account",
"on",
"this",
"HS",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/client.py#L190-L209 |
247,775 | matrix-org/matrix-python-sdk | matrix_client/client.py | MatrixClient.login_with_password_no_sync | def login_with_password_no_sync(self, username, password):
"""Deprecated. Use ``login`` with ``sync=False``.
Login to the homeserver.
Args:
username (str): Account username
password (str): Account password
Returns:
str: Access token
Raises:
MatrixRequestError
"""
warn("login_with_password_no_sync is deprecated. Use login with sync=False.",
DeprecationWarning)
return self.login(username, password, sync=False) | python | def login_with_password_no_sync(self, username, password):
warn("login_with_password_no_sync is deprecated. Use login with sync=False.",
DeprecationWarning)
return self.login(username, password, sync=False) | [
"def",
"login_with_password_no_sync",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"warn",
"(",
"\"login_with_password_no_sync is deprecated. Use login with sync=False.\"",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"login",
"(",
"username",
",",
... | Deprecated. Use ``login`` with ``sync=False``.
Login to the homeserver.
Args:
username (str): Account username
password (str): Account password
Returns:
str: Access token
Raises:
MatrixRequestError | [
"Deprecated",
".",
"Use",
"login",
"with",
"sync",
"=",
"False",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/client.py#L219-L236 |
247,776 | matrix-org/matrix-python-sdk | matrix_client/client.py | MatrixClient.login_with_password | def login_with_password(self, username, password, limit=10):
"""Deprecated. Use ``login`` with ``sync=True``.
Login to the homeserver.
Args:
username (str): Account username
password (str): Account password
limit (int): Deprecated. How many messages to return when syncing.
This will be replaced by a filter API in a later release.
Returns:
str: Access token
Raises:
MatrixRequestError
"""
warn("login_with_password is deprecated. Use login with sync=True.",
DeprecationWarning)
return self.login(username, password, limit, sync=True) | python | def login_with_password(self, username, password, limit=10):
warn("login_with_password is deprecated. Use login with sync=True.",
DeprecationWarning)
return self.login(username, password, limit, sync=True) | [
"def",
"login_with_password",
"(",
"self",
",",
"username",
",",
"password",
",",
"limit",
"=",
"10",
")",
":",
"warn",
"(",
"\"login_with_password is deprecated. Use login with sync=True.\"",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"login",
"(",
"use... | Deprecated. Use ``login`` with ``sync=True``.
Login to the homeserver.
Args:
username (str): Account username
password (str): Account password
limit (int): Deprecated. How many messages to return when syncing.
This will be replaced by a filter API in a later release.
Returns:
str: Access token
Raises:
MatrixRequestError | [
"Deprecated",
".",
"Use",
"login",
"with",
"sync",
"=",
"True",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/client.py#L238-L257 |
247,777 | matrix-org/matrix-python-sdk | matrix_client/client.py | MatrixClient.login | def login(self, username, password, limit=10, sync=True, device_id=None):
"""Login to the homeserver.
Args:
username (str): Account username
password (str): Account password
limit (int): Deprecated. How many messages to return when syncing.
This will be replaced by a filter API in a later release.
sync (bool): Optional. Whether to initiate a /sync request after logging in.
device_id (str): Optional. ID of the client device. The server will
auto-generate a device_id if this is not specified.
Returns:
str: Access token
Raises:
MatrixRequestError
"""
response = self.api.login(
"m.login.password", user=username, password=password, device_id=device_id
)
self.user_id = response["user_id"]
self.token = response["access_token"]
self.hs = response["home_server"]
self.api.token = self.token
self.device_id = response["device_id"]
if self._encryption:
self.olm_device = OlmDevice(
self.api, self.user_id, self.device_id, **self.encryption_conf)
self.olm_device.upload_identity_keys()
self.olm_device.upload_one_time_keys()
if sync:
""" Limit Filter """
self.sync_filter = '{ "room": { "timeline" : { "limit" : %i } } }' % limit
self._sync()
return self.token | python | def login(self, username, password, limit=10, sync=True, device_id=None):
response = self.api.login(
"m.login.password", user=username, password=password, device_id=device_id
)
self.user_id = response["user_id"]
self.token = response["access_token"]
self.hs = response["home_server"]
self.api.token = self.token
self.device_id = response["device_id"]
if self._encryption:
self.olm_device = OlmDevice(
self.api, self.user_id, self.device_id, **self.encryption_conf)
self.olm_device.upload_identity_keys()
self.olm_device.upload_one_time_keys()
if sync:
""" Limit Filter """
self.sync_filter = '{ "room": { "timeline" : { "limit" : %i } } }' % limit
self._sync()
return self.token | [
"def",
"login",
"(",
"self",
",",
"username",
",",
"password",
",",
"limit",
"=",
"10",
",",
"sync",
"=",
"True",
",",
"device_id",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"api",
".",
"login",
"(",
"\"m.login.password\"",
",",
"user",
"=... | Login to the homeserver.
Args:
username (str): Account username
password (str): Account password
limit (int): Deprecated. How many messages to return when syncing.
This will be replaced by a filter API in a later release.
sync (bool): Optional. Whether to initiate a /sync request after logging in.
device_id (str): Optional. ID of the client device. The server will
auto-generate a device_id if this is not specified.
Returns:
str: Access token
Raises:
MatrixRequestError | [
"Login",
"to",
"the",
"homeserver",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/client.py#L259-L296 |
247,778 | matrix-org/matrix-python-sdk | matrix_client/client.py | MatrixClient.create_room | def create_room(self, alias=None, is_public=False, invitees=None):
""" Create a new room on the homeserver.
Args:
alias (str): The canonical_alias of the room.
is_public (bool): The public/private visibility of the room.
invitees (str[]): A set of user ids to invite into the room.
Returns:
Room
Raises:
MatrixRequestError
"""
response = self.api.create_room(alias=alias,
is_public=is_public,
invitees=invitees)
return self._mkroom(response["room_id"]) | python | def create_room(self, alias=None, is_public=False, invitees=None):
response = self.api.create_room(alias=alias,
is_public=is_public,
invitees=invitees)
return self._mkroom(response["room_id"]) | [
"def",
"create_room",
"(",
"self",
",",
"alias",
"=",
"None",
",",
"is_public",
"=",
"False",
",",
"invitees",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"api",
".",
"create_room",
"(",
"alias",
"=",
"alias",
",",
"is_public",
"=",
"is_public... | Create a new room on the homeserver.
Args:
alias (str): The canonical_alias of the room.
is_public (bool): The public/private visibility of the room.
invitees (str[]): A set of user ids to invite into the room.
Returns:
Room
Raises:
MatrixRequestError | [
"Create",
"a",
"new",
"room",
"on",
"the",
"homeserver",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/client.py#L306-L323 |
247,779 | matrix-org/matrix-python-sdk | matrix_client/client.py | MatrixClient.add_listener | def add_listener(self, callback, event_type=None):
""" Add a listener that will send a callback when the client recieves
an event.
Args:
callback (func(roomchunk)): 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_uid = uuid4()
# TODO: listeners should be stored in dict and accessed/deleted directly. Add
# convenience method such that MatrixClient.listeners.new(Listener(...)) performs
# MatrixClient.listeners[uuid4()] = Listener(...)
self.listeners.append(
{
'uid': listener_uid,
'callback': callback,
'event_type': event_type
}
)
return listener_uid | python | def add_listener(self, callback, event_type=None):
listener_uid = uuid4()
# TODO: listeners should be stored in dict and accessed/deleted directly. Add
# convenience method such that MatrixClient.listeners.new(Listener(...)) performs
# MatrixClient.listeners[uuid4()] = Listener(...)
self.listeners.append(
{
'uid': listener_uid,
'callback': callback,
'event_type': event_type
}
)
return listener_uid | [
"def",
"add_listener",
"(",
"self",
",",
"callback",
",",
"event_type",
"=",
"None",
")",
":",
"listener_uid",
"=",
"uuid4",
"(",
")",
"# TODO: listeners should be stored in dict and accessed/deleted directly. Add",
"# convenience method such that MatrixClient.listeners.new(Liste... | Add a listener that will send a callback when the client recieves
an event.
Args:
callback (func(roomchunk)): 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",
"listener",
"that",
"will",
"send",
"a",
"callback",
"when",
"the",
"client",
"recieves",
"an",
"event",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/client.py#L355-L377 |
247,780 | matrix-org/matrix-python-sdk | matrix_client/client.py | MatrixClient.add_presence_listener | def add_presence_listener(self, callback):
""" Add a presence listener that will send a callback when the client receives
a presence update.
Args:
callback (func(roomchunk)): Callback called when a presence update arrives.
Returns:
uuid.UUID: Unique id of the listener, can be used to identify the listener.
"""
listener_uid = uuid4()
self.presence_listeners[listener_uid] = callback
return listener_uid | python | def add_presence_listener(self, callback):
listener_uid = uuid4()
self.presence_listeners[listener_uid] = callback
return listener_uid | [
"def",
"add_presence_listener",
"(",
"self",
",",
"callback",
")",
":",
"listener_uid",
"=",
"uuid4",
"(",
")",
"self",
".",
"presence_listeners",
"[",
"listener_uid",
"]",
"=",
"callback",
"return",
"listener_uid"
] | Add a presence listener that will send a callback when the client receives
a presence update.
Args:
callback (func(roomchunk)): Callback called when a presence update arrives.
Returns:
uuid.UUID: Unique id of the listener, can be used to identify the listener. | [
"Add",
"a",
"presence",
"listener",
"that",
"will",
"send",
"a",
"callback",
"when",
"the",
"client",
"receives",
"a",
"presence",
"update",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/client.py#L388-L400 |
247,781 | matrix-org/matrix-python-sdk | matrix_client/client.py | MatrixClient.listen_forever | def listen_forever(self, timeout_ms=30000, exception_handler=None,
bad_sync_timeout=5):
""" Keep listening for events forever.
Args:
timeout_ms (int): How long to poll the Home Server for before
retrying.
exception_handler (func(exception)): Optional exception handler
function which can be used to handle exceptions in the caller
thread.
bad_sync_timeout (int): Base time to wait after an error before
retrying. Will be increased according to exponential backoff.
"""
_bad_sync_timeout = bad_sync_timeout
self.should_listen = True
while (self.should_listen):
try:
self._sync(timeout_ms)
_bad_sync_timeout = bad_sync_timeout
# TODO: we should also handle MatrixHttpLibError for retry in case no response
except MatrixRequestError as e:
logger.warning("A MatrixRequestError occured during sync.")
if e.code >= 500:
logger.warning("Problem occured serverside. Waiting %i seconds",
bad_sync_timeout)
sleep(bad_sync_timeout)
_bad_sync_timeout = min(_bad_sync_timeout * 2,
self.bad_sync_timeout_limit)
elif exception_handler is not None:
exception_handler(e)
else:
raise
except Exception as e:
logger.exception("Exception thrown during sync")
if exception_handler is not None:
exception_handler(e)
else:
raise | python | def listen_forever(self, timeout_ms=30000, exception_handler=None,
bad_sync_timeout=5):
_bad_sync_timeout = bad_sync_timeout
self.should_listen = True
while (self.should_listen):
try:
self._sync(timeout_ms)
_bad_sync_timeout = bad_sync_timeout
# TODO: we should also handle MatrixHttpLibError for retry in case no response
except MatrixRequestError as e:
logger.warning("A MatrixRequestError occured during sync.")
if e.code >= 500:
logger.warning("Problem occured serverside. Waiting %i seconds",
bad_sync_timeout)
sleep(bad_sync_timeout)
_bad_sync_timeout = min(_bad_sync_timeout * 2,
self.bad_sync_timeout_limit)
elif exception_handler is not None:
exception_handler(e)
else:
raise
except Exception as e:
logger.exception("Exception thrown during sync")
if exception_handler is not None:
exception_handler(e)
else:
raise | [
"def",
"listen_forever",
"(",
"self",
",",
"timeout_ms",
"=",
"30000",
",",
"exception_handler",
"=",
"None",
",",
"bad_sync_timeout",
"=",
"5",
")",
":",
"_bad_sync_timeout",
"=",
"bad_sync_timeout",
"self",
".",
"should_listen",
"=",
"True",
"while",
"(",
"s... | Keep listening for events forever.
Args:
timeout_ms (int): How long to poll the Home Server for before
retrying.
exception_handler (func(exception)): Optional exception handler
function which can be used to handle exceptions in the caller
thread.
bad_sync_timeout (int): Base time to wait after an error before
retrying. Will be increased according to exponential backoff. | [
"Keep",
"listening",
"for",
"events",
"forever",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/client.py#L473-L510 |
247,782 | matrix-org/matrix-python-sdk | matrix_client/client.py | MatrixClient.start_listener_thread | def start_listener_thread(self, timeout_ms=30000, exception_handler=None):
""" Start a listener thread to listen for events in the background.
Args:
timeout (int): How long to poll the Home Server for before
retrying.
exception_handler (func(exception)): Optional exception handler
function which can be used to handle exceptions in the caller
thread.
"""
try:
thread = Thread(target=self.listen_forever,
args=(timeout_ms, exception_handler))
thread.daemon = True
self.sync_thread = thread
self.should_listen = True
thread.start()
except RuntimeError:
e = sys.exc_info()[0]
logger.error("Error: unable to start thread. %s", str(e)) | python | def start_listener_thread(self, timeout_ms=30000, exception_handler=None):
try:
thread = Thread(target=self.listen_forever,
args=(timeout_ms, exception_handler))
thread.daemon = True
self.sync_thread = thread
self.should_listen = True
thread.start()
except RuntimeError:
e = sys.exc_info()[0]
logger.error("Error: unable to start thread. %s", str(e)) | [
"def",
"start_listener_thread",
"(",
"self",
",",
"timeout_ms",
"=",
"30000",
",",
"exception_handler",
"=",
"None",
")",
":",
"try",
":",
"thread",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"listen_forever",
",",
"args",
"=",
"(",
"timeout_ms",
",",... | Start a listener thread to listen for events in the background.
Args:
timeout (int): How long to poll the Home Server for before
retrying.
exception_handler (func(exception)): Optional exception handler
function which can be used to handle exceptions in the caller
thread. | [
"Start",
"a",
"listener",
"thread",
"to",
"listen",
"for",
"events",
"in",
"the",
"background",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/client.py#L512-L531 |
247,783 | matrix-org/matrix-python-sdk | matrix_client/client.py | MatrixClient.stop_listener_thread | def stop_listener_thread(self):
""" Stop listener thread running in the background
"""
if self.sync_thread:
self.should_listen = False
self.sync_thread.join()
self.sync_thread = None | python | def stop_listener_thread(self):
if self.sync_thread:
self.should_listen = False
self.sync_thread.join()
self.sync_thread = None | [
"def",
"stop_listener_thread",
"(",
"self",
")",
":",
"if",
"self",
".",
"sync_thread",
":",
"self",
".",
"should_listen",
"=",
"False",
"self",
".",
"sync_thread",
".",
"join",
"(",
")",
"self",
".",
"sync_thread",
"=",
"None"
] | Stop listener thread running in the background | [
"Stop",
"listener",
"thread",
"running",
"in",
"the",
"background"
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/client.py#L533-L539 |
247,784 | matrix-org/matrix-python-sdk | matrix_client/client.py | MatrixClient.upload | def upload(self, content, content_type, filename=None):
""" Upload content to the home server and recieve a MXC url.
Args:
content (bytes): The data of the content.
content_type (str): The mimetype of the content.
filename (str): Optional. Filename of the content.
Raises:
MatrixUnexpectedResponse: If the homeserver gave a strange response
MatrixRequestError: If the upload failed for some reason.
"""
try:
response = self.api.media_upload(content, content_type, filename)
if "content_uri" in response:
return response["content_uri"]
else:
raise MatrixUnexpectedResponse(
"The upload was successful, but content_uri wasn't found."
)
except MatrixRequestError as e:
raise MatrixRequestError(
code=e.code,
content="Upload failed: %s" % e
) | python | def upload(self, content, content_type, filename=None):
try:
response = self.api.media_upload(content, content_type, filename)
if "content_uri" in response:
return response["content_uri"]
else:
raise MatrixUnexpectedResponse(
"The upload was successful, but content_uri wasn't found."
)
except MatrixRequestError as e:
raise MatrixRequestError(
code=e.code,
content="Upload failed: %s" % e
) | [
"def",
"upload",
"(",
"self",
",",
"content",
",",
"content_type",
",",
"filename",
"=",
"None",
")",
":",
"try",
":",
"response",
"=",
"self",
".",
"api",
".",
"media_upload",
"(",
"content",
",",
"content_type",
",",
"filename",
")",
"if",
"\"content_u... | Upload content to the home server and recieve a MXC url.
Args:
content (bytes): The data of the content.
content_type (str): The mimetype of the content.
filename (str): Optional. Filename of the content.
Raises:
MatrixUnexpectedResponse: If the homeserver gave a strange response
MatrixRequestError: If the upload failed for some reason. | [
"Upload",
"content",
"to",
"the",
"home",
"server",
"and",
"recieve",
"a",
"MXC",
"url",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/client.py#L542-L566 |
247,785 | matrix-org/matrix-python-sdk | matrix_client/client.py | MatrixClient.remove_room_alias | def remove_room_alias(self, room_alias):
"""Remove mapping of an alias
Args:
room_alias(str): The alias to be removed.
Returns:
bool: True if the alias is removed, False otherwise.
"""
try:
self.api.remove_room_alias(room_alias)
return True
except MatrixRequestError:
return False | python | def remove_room_alias(self, room_alias):
try:
self.api.remove_room_alias(room_alias)
return True
except MatrixRequestError:
return False | [
"def",
"remove_room_alias",
"(",
"self",
",",
"room_alias",
")",
":",
"try",
":",
"self",
".",
"api",
".",
"remove_room_alias",
"(",
"room_alias",
")",
"return",
"True",
"except",
"MatrixRequestError",
":",
"return",
"False"
] | Remove mapping of an alias
Args:
room_alias(str): The alias to be removed.
Returns:
bool: True if the alias is removed, False otherwise. | [
"Remove",
"mapping",
"of",
"an",
"alias"
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/client.py#L656-L669 |
247,786 | matrix-org/matrix-python-sdk | matrix_client/crypto/olm_device.py | OlmDevice.upload_identity_keys | def upload_identity_keys(self):
"""Uploads this device's identity keys to HS.
This device must be the one used when logging in.
"""
device_keys = {
'user_id': self.user_id,
'device_id': self.device_id,
'algorithms': self._algorithms,
'keys': {'{}:{}'.format(alg, self.device_id): key
for alg, key in self.identity_keys.items()}
}
self.sign_json(device_keys)
ret = self.api.upload_keys(device_keys=device_keys)
self.one_time_keys_manager.server_counts = ret['one_time_key_counts']
logger.info('Uploaded identity keys.') | python | def upload_identity_keys(self):
device_keys = {
'user_id': self.user_id,
'device_id': self.device_id,
'algorithms': self._algorithms,
'keys': {'{}:{}'.format(alg, self.device_id): key
for alg, key in self.identity_keys.items()}
}
self.sign_json(device_keys)
ret = self.api.upload_keys(device_keys=device_keys)
self.one_time_keys_manager.server_counts = ret['one_time_key_counts']
logger.info('Uploaded identity keys.') | [
"def",
"upload_identity_keys",
"(",
"self",
")",
":",
"device_keys",
"=",
"{",
"'user_id'",
":",
"self",
".",
"user_id",
",",
"'device_id'",
":",
"self",
".",
"device_id",
",",
"'algorithms'",
":",
"self",
".",
"_algorithms",
",",
"'keys'",
":",
"{",
"'{}:... | Uploads this device's identity keys to HS.
This device must be the one used when logging in. | [
"Uploads",
"this",
"device",
"s",
"identity",
"keys",
"to",
"HS",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/crypto/olm_device.py#L63-L78 |
247,787 | matrix-org/matrix-python-sdk | matrix_client/crypto/olm_device.py | OlmDevice.upload_one_time_keys | def upload_one_time_keys(self, force_update=False):
"""Uploads new one-time keys to the HS, if needed.
Args:
force_update (bool): Fetch the number of one-time keys currently on the HS
before uploading, even if we already know one. In most cases this should
not be necessary, as we get this value from sync responses.
Returns:
A dict containg the number of new keys that were uploaded for each key type
(signed_curve25519 or curve25519). The format is
``<key_type>: <uploaded_number>``. If no keys of a given type have been
uploaded, the corresponding key will not be present. Consequently, an
empty dict indicates that no keys were uploaded.
"""
if force_update or not self.one_time_keys_manager.server_counts:
counts = self.api.upload_keys()['one_time_key_counts']
self.one_time_keys_manager.server_counts = counts
signed_keys_to_upload = self.one_time_keys_manager.signed_curve25519_to_upload
unsigned_keys_to_upload = self.one_time_keys_manager.curve25519_to_upload
self.olm_account.generate_one_time_keys(signed_keys_to_upload +
unsigned_keys_to_upload)
one_time_keys = {}
keys = self.olm_account.one_time_keys['curve25519']
for i, key_id in enumerate(keys):
if i < signed_keys_to_upload:
key = self.sign_json({'key': keys[key_id]})
key_type = 'signed_curve25519'
else:
key = keys[key_id]
key_type = 'curve25519'
one_time_keys['{}:{}'.format(key_type, key_id)] = key
ret = self.api.upload_keys(one_time_keys=one_time_keys)
self.one_time_keys_manager.server_counts = ret['one_time_key_counts']
self.olm_account.mark_keys_as_published()
keys_uploaded = {}
if unsigned_keys_to_upload:
keys_uploaded['curve25519'] = unsigned_keys_to_upload
if signed_keys_to_upload:
keys_uploaded['signed_curve25519'] = signed_keys_to_upload
logger.info('Uploaded new one-time keys: %s.', keys_uploaded)
return keys_uploaded | python | def upload_one_time_keys(self, force_update=False):
if force_update or not self.one_time_keys_manager.server_counts:
counts = self.api.upload_keys()['one_time_key_counts']
self.one_time_keys_manager.server_counts = counts
signed_keys_to_upload = self.one_time_keys_manager.signed_curve25519_to_upload
unsigned_keys_to_upload = self.one_time_keys_manager.curve25519_to_upload
self.olm_account.generate_one_time_keys(signed_keys_to_upload +
unsigned_keys_to_upload)
one_time_keys = {}
keys = self.olm_account.one_time_keys['curve25519']
for i, key_id in enumerate(keys):
if i < signed_keys_to_upload:
key = self.sign_json({'key': keys[key_id]})
key_type = 'signed_curve25519'
else:
key = keys[key_id]
key_type = 'curve25519'
one_time_keys['{}:{}'.format(key_type, key_id)] = key
ret = self.api.upload_keys(one_time_keys=one_time_keys)
self.one_time_keys_manager.server_counts = ret['one_time_key_counts']
self.olm_account.mark_keys_as_published()
keys_uploaded = {}
if unsigned_keys_to_upload:
keys_uploaded['curve25519'] = unsigned_keys_to_upload
if signed_keys_to_upload:
keys_uploaded['signed_curve25519'] = signed_keys_to_upload
logger.info('Uploaded new one-time keys: %s.', keys_uploaded)
return keys_uploaded | [
"def",
"upload_one_time_keys",
"(",
"self",
",",
"force_update",
"=",
"False",
")",
":",
"if",
"force_update",
"or",
"not",
"self",
".",
"one_time_keys_manager",
".",
"server_counts",
":",
"counts",
"=",
"self",
".",
"api",
".",
"upload_keys",
"(",
")",
"[",... | Uploads new one-time keys to the HS, if needed.
Args:
force_update (bool): Fetch the number of one-time keys currently on the HS
before uploading, even if we already know one. In most cases this should
not be necessary, as we get this value from sync responses.
Returns:
A dict containg the number of new keys that were uploaded for each key type
(signed_curve25519 or curve25519). The format is
``<key_type>: <uploaded_number>``. If no keys of a given type have been
uploaded, the corresponding key will not be present. Consequently, an
empty dict indicates that no keys were uploaded. | [
"Uploads",
"new",
"one",
"-",
"time",
"keys",
"to",
"the",
"HS",
"if",
"needed",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/crypto/olm_device.py#L80-L126 |
247,788 | matrix-org/matrix-python-sdk | matrix_client/crypto/olm_device.py | OlmDevice.update_one_time_key_counts | def update_one_time_key_counts(self, counts):
"""Update data on one-time keys count and upload new ones if necessary.
Args:
counts (dict): Counts of keys currently on the HS for each key type.
"""
self.one_time_keys_manager.server_counts = counts
if self.one_time_keys_manager.should_upload():
logger.info('Uploading new one-time keys.')
self.upload_one_time_keys() | python | def update_one_time_key_counts(self, counts):
self.one_time_keys_manager.server_counts = counts
if self.one_time_keys_manager.should_upload():
logger.info('Uploading new one-time keys.')
self.upload_one_time_keys() | [
"def",
"update_one_time_key_counts",
"(",
"self",
",",
"counts",
")",
":",
"self",
".",
"one_time_keys_manager",
".",
"server_counts",
"=",
"counts",
"if",
"self",
".",
"one_time_keys_manager",
".",
"should_upload",
"(",
")",
":",
"logger",
".",
"info",
"(",
"... | Update data on one-time keys count and upload new ones if necessary.
Args:
counts (dict): Counts of keys currently on the HS for each key type. | [
"Update",
"data",
"on",
"one",
"-",
"time",
"keys",
"count",
"and",
"upload",
"new",
"ones",
"if",
"necessary",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/crypto/olm_device.py#L128-L137 |
247,789 | matrix-org/matrix-python-sdk | matrix_client/crypto/olm_device.py | OlmDevice.sign_json | def sign_json(self, json):
"""Signs a JSON object.
NOTE: The object is modified in-place and the return value can be ignored.
As specified, this is done by encoding the JSON object without ``signatures`` or
keys grouped as ``unsigned``, using canonical encoding.
Args:
json (dict): The JSON object to sign.
Returns:
The same JSON object, with a ``signatures`` key added. It is formatted as
``"signatures": ed25519:<device_id>: <base64_signature>``.
"""
signatures = json.pop('signatures', {})
unsigned = json.pop('unsigned', None)
signature_base64 = self.olm_account.sign(encode_canonical_json(json))
key_id = 'ed25519:{}'.format(self.device_id)
signatures.setdefault(self.user_id, {})[key_id] = signature_base64
json['signatures'] = signatures
if unsigned:
json['unsigned'] = unsigned
return json | python | def sign_json(self, json):
signatures = json.pop('signatures', {})
unsigned = json.pop('unsigned', None)
signature_base64 = self.olm_account.sign(encode_canonical_json(json))
key_id = 'ed25519:{}'.format(self.device_id)
signatures.setdefault(self.user_id, {})[key_id] = signature_base64
json['signatures'] = signatures
if unsigned:
json['unsigned'] = unsigned
return json | [
"def",
"sign_json",
"(",
"self",
",",
"json",
")",
":",
"signatures",
"=",
"json",
".",
"pop",
"(",
"'signatures'",
",",
"{",
"}",
")",
"unsigned",
"=",
"json",
".",
"pop",
"(",
"'unsigned'",
",",
"None",
")",
"signature_base64",
"=",
"self",
".",
"o... | Signs a JSON object.
NOTE: The object is modified in-place and the return value can be ignored.
As specified, this is done by encoding the JSON object without ``signatures`` or
keys grouped as ``unsigned``, using canonical encoding.
Args:
json (dict): The JSON object to sign.
Returns:
The same JSON object, with a ``signatures`` key added. It is formatted as
``"signatures": ed25519:<device_id>: <base64_signature>``. | [
"Signs",
"a",
"JSON",
"object",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/crypto/olm_device.py#L139-L166 |
247,790 | matrix-org/matrix-python-sdk | matrix_client/crypto/olm_device.py | OlmDevice.verify_json | def verify_json(self, json, user_key, user_id, device_id):
"""Verifies a signed key object's signature.
The object must have a 'signatures' key associated with an object of the form
`user_id: {key_id: signature}`.
Args:
json (dict): The JSON object to verify.
user_key (str): The public ed25519 key which was used to sign the object.
user_id (str): The user who owns the device.
device_id (str): The device who owns the key.
Returns:
True if the verification was successful, False if not.
"""
try:
signatures = json.pop('signatures')
except KeyError:
return False
key_id = 'ed25519:{}'.format(device_id)
try:
signature_base64 = signatures[user_id][key_id]
except KeyError:
json['signatures'] = signatures
return False
unsigned = json.pop('unsigned', None)
try:
olm.ed25519_verify(user_key, encode_canonical_json(json), signature_base64)
success = True
except olm.utility.OlmVerifyError:
success = False
json['signatures'] = signatures
if unsigned:
json['unsigned'] = unsigned
return success | python | def verify_json(self, json, user_key, user_id, device_id):
try:
signatures = json.pop('signatures')
except KeyError:
return False
key_id = 'ed25519:{}'.format(device_id)
try:
signature_base64 = signatures[user_id][key_id]
except KeyError:
json['signatures'] = signatures
return False
unsigned = json.pop('unsigned', None)
try:
olm.ed25519_verify(user_key, encode_canonical_json(json), signature_base64)
success = True
except olm.utility.OlmVerifyError:
success = False
json['signatures'] = signatures
if unsigned:
json['unsigned'] = unsigned
return success | [
"def",
"verify_json",
"(",
"self",
",",
"json",
",",
"user_key",
",",
"user_id",
",",
"device_id",
")",
":",
"try",
":",
"signatures",
"=",
"json",
".",
"pop",
"(",
"'signatures'",
")",
"except",
"KeyError",
":",
"return",
"False",
"key_id",
"=",
"'ed255... | Verifies a signed key object's signature.
The object must have a 'signatures' key associated with an object of the form
`user_id: {key_id: signature}`.
Args:
json (dict): The JSON object to verify.
user_key (str): The public ed25519 key which was used to sign the object.
user_id (str): The user who owns the device.
device_id (str): The device who owns the key.
Returns:
True if the verification was successful, False if not. | [
"Verifies",
"a",
"signed",
"key",
"object",
"s",
"signature",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/crypto/olm_device.py#L168-L207 |
247,791 | matrix-org/matrix-python-sdk | matrix_client/user.py | User.get_display_name | def get_display_name(self, room=None):
"""Get this user's display name.
Args:
room (Room): Optional. When specified, return the display name of the user
in this room.
Returns:
The display name. Defaults to the user ID if not set.
"""
if room:
try:
return room.members_displaynames[self.user_id]
except KeyError:
return self.user_id
if not self.displayname:
self.displayname = self.api.get_display_name(self.user_id)
return self.displayname or self.user_id | python | def get_display_name(self, room=None):
if room:
try:
return room.members_displaynames[self.user_id]
except KeyError:
return self.user_id
if not self.displayname:
self.displayname = self.api.get_display_name(self.user_id)
return self.displayname or self.user_id | [
"def",
"get_display_name",
"(",
"self",
",",
"room",
"=",
"None",
")",
":",
"if",
"room",
":",
"try",
":",
"return",
"room",
".",
"members_displaynames",
"[",
"self",
".",
"user_id",
"]",
"except",
"KeyError",
":",
"return",
"self",
".",
"user_id",
"if",... | Get this user's display name.
Args:
room (Room): Optional. When specified, return the display name of the user
in this room.
Returns:
The display name. Defaults to the user ID if not set. | [
"Get",
"this",
"user",
"s",
"display",
"name",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/user.py#L30-L47 |
247,792 | matrix-org/matrix-python-sdk | matrix_client/user.py | User.set_display_name | def set_display_name(self, display_name):
""" Set this users display name.
Args:
display_name (str): Display Name
"""
self.displayname = display_name
return self.api.set_display_name(self.user_id, display_name) | python | def set_display_name(self, display_name):
self.displayname = display_name
return self.api.set_display_name(self.user_id, display_name) | [
"def",
"set_display_name",
"(",
"self",
",",
"display_name",
")",
":",
"self",
".",
"displayname",
"=",
"display_name",
"return",
"self",
".",
"api",
".",
"set_display_name",
"(",
"self",
".",
"user_id",
",",
"display_name",
")"
] | Set this users display name.
Args:
display_name (str): Display Name | [
"Set",
"this",
"users",
"display",
"name",
"."
] | e734cce3ccd35f2d355c6a19a7a701033472498a | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/user.py#L55-L62 |
247,793 | diyan/pywinrm | winrm/encryption.py | Encryption.prepare_encrypted_request | def prepare_encrypted_request(self, session, endpoint, message):
"""
Creates a prepared request to send to the server with an encrypted message
and correct headers
:param session: The handle of the session to prepare requests with
:param endpoint: The endpoint/server to prepare requests to
:param message: The unencrypted message to send to the server
:return: A prepared request that has an encrypted message
"""
host = urlsplit(endpoint).hostname
if self.protocol == 'credssp' and len(message) > self.SIXTEN_KB:
content_type = 'multipart/x-multi-encrypted'
encrypted_message = b''
message_chunks = [message[i:i+self.SIXTEN_KB] for i in range(0, len(message), self.SIXTEN_KB)]
for message_chunk in message_chunks:
encrypted_chunk = self._encrypt_message(message_chunk, host)
encrypted_message += encrypted_chunk
else:
content_type = 'multipart/encrypted'
encrypted_message = self._encrypt_message(message, host)
encrypted_message += self.MIME_BOUNDARY + b"--\r\n"
request = requests.Request('POST', endpoint, data=encrypted_message)
prepared_request = session.prepare_request(request)
prepared_request.headers['Content-Length'] = str(len(prepared_request.body))
prepared_request.headers['Content-Type'] = '{0};protocol="{1}";boundary="Encrypted Boundary"'\
.format(content_type, self.protocol_string.decode())
return prepared_request | python | def prepare_encrypted_request(self, session, endpoint, message):
host = urlsplit(endpoint).hostname
if self.protocol == 'credssp' and len(message) > self.SIXTEN_KB:
content_type = 'multipart/x-multi-encrypted'
encrypted_message = b''
message_chunks = [message[i:i+self.SIXTEN_KB] for i in range(0, len(message), self.SIXTEN_KB)]
for message_chunk in message_chunks:
encrypted_chunk = self._encrypt_message(message_chunk, host)
encrypted_message += encrypted_chunk
else:
content_type = 'multipart/encrypted'
encrypted_message = self._encrypt_message(message, host)
encrypted_message += self.MIME_BOUNDARY + b"--\r\n"
request = requests.Request('POST', endpoint, data=encrypted_message)
prepared_request = session.prepare_request(request)
prepared_request.headers['Content-Length'] = str(len(prepared_request.body))
prepared_request.headers['Content-Type'] = '{0};protocol="{1}";boundary="Encrypted Boundary"'\
.format(content_type, self.protocol_string.decode())
return prepared_request | [
"def",
"prepare_encrypted_request",
"(",
"self",
",",
"session",
",",
"endpoint",
",",
"message",
")",
":",
"host",
"=",
"urlsplit",
"(",
"endpoint",
")",
".",
"hostname",
"if",
"self",
".",
"protocol",
"==",
"'credssp'",
"and",
"len",
"(",
"message",
")",... | Creates a prepared request to send to the server with an encrypted message
and correct headers
:param session: The handle of the session to prepare requests with
:param endpoint: The endpoint/server to prepare requests to
:param message: The unencrypted message to send to the server
:return: A prepared request that has an encrypted message | [
"Creates",
"a",
"prepared",
"request",
"to",
"send",
"to",
"the",
"server",
"with",
"an",
"encrypted",
"message",
"and",
"correct",
"headers"
] | ed4c2d991d9d0fe921dfc958c475c4c6a570519e | https://github.com/diyan/pywinrm/blob/ed4c2d991d9d0fe921dfc958c475c4c6a570519e/winrm/encryption.py#L58-L88 |
247,794 | diyan/pywinrm | winrm/encryption.py | Encryption.parse_encrypted_response | def parse_encrypted_response(self, response):
"""
Takes in the encrypted response from the server and decrypts it
:param response: The response that needs to be decrytped
:return: The unencrypted message from the server
"""
content_type = response.headers['Content-Type']
if 'protocol="{0}"'.format(self.protocol_string.decode()) in content_type:
host = urlsplit(response.request.url).hostname
msg = self._decrypt_response(response, host)
else:
msg = response.text
return msg | python | def parse_encrypted_response(self, response):
content_type = response.headers['Content-Type']
if 'protocol="{0}"'.format(self.protocol_string.decode()) in content_type:
host = urlsplit(response.request.url).hostname
msg = self._decrypt_response(response, host)
else:
msg = response.text
return msg | [
"def",
"parse_encrypted_response",
"(",
"self",
",",
"response",
")",
":",
"content_type",
"=",
"response",
".",
"headers",
"[",
"'Content-Type'",
"]",
"if",
"'protocol=\"{0}\"'",
".",
"format",
"(",
"self",
".",
"protocol_string",
".",
"decode",
"(",
")",
")"... | Takes in the encrypted response from the server and decrypts it
:param response: The response that needs to be decrytped
:return: The unencrypted message from the server | [
"Takes",
"in",
"the",
"encrypted",
"response",
"from",
"the",
"server",
"and",
"decrypts",
"it"
] | ed4c2d991d9d0fe921dfc958c475c4c6a570519e | https://github.com/diyan/pywinrm/blob/ed4c2d991d9d0fe921dfc958c475c4c6a570519e/winrm/encryption.py#L90-L104 |
247,795 | diyan/pywinrm | winrm/protocol.py | Protocol.open_shell | def open_shell(self, i_stream='stdin', o_stream='stdout stderr',
working_directory=None, env_vars=None, noprofile=False,
codepage=437, lifetime=None, idle_timeout=None):
"""
Create a Shell on the destination host
@param string i_stream: Which input stream to open. Leave this alone
unless you know what you're doing (default: stdin)
@param string o_stream: Which output stream to open. Leave this alone
unless you know what you're doing (default: stdout stderr)
@param string working_directory: the directory to create the shell in
@param dict env_vars: environment variables to set for the shell. For
instance: {'PATH': '%PATH%;c:/Program Files (x86)/Git/bin/', 'CYGWIN':
'nontsec codepage:utf8'}
@returns The ShellId from the SOAP response. This is our open shell
instance on the remote machine.
@rtype string
"""
req = {'env:Envelope': self._get_soap_header(
resource_uri='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd', # NOQA
action='http://schemas.xmlsoap.org/ws/2004/09/transfer/Create')}
header = req['env:Envelope']['env:Header']
header['w:OptionSet'] = {
'w:Option': [
{
'@Name': 'WINRS_NOPROFILE',
'#text': str(noprofile).upper() # TODO remove str call
},
{
'@Name': 'WINRS_CODEPAGE',
'#text': str(codepage) # TODO remove str call
}
]
}
shell = req['env:Envelope'].setdefault(
'env:Body', {}).setdefault('rsp:Shell', {})
shell['rsp:InputStreams'] = i_stream
shell['rsp:OutputStreams'] = o_stream
if working_directory:
# TODO ensure that rsp:WorkingDirectory should be nested within rsp:Shell # NOQA
shell['rsp:WorkingDirectory'] = working_directory
# TODO check Lifetime param: http://msdn.microsoft.com/en-us/library/cc251546(v=PROT.13).aspx # NOQA
#if lifetime:
# shell['rsp:Lifetime'] = iso8601_duration.sec_to_dur(lifetime)
# TODO make it so the input is given in milliseconds and converted to xs:duration # NOQA
if idle_timeout:
shell['rsp:IdleTimeOut'] = idle_timeout
if env_vars:
env = shell.setdefault('rsp:Environment', {})
for key, value in env_vars.items():
env['rsp:Variable'] = {'@Name': key, '#text': value}
res = self.send_message(xmltodict.unparse(req))
#res = xmltodict.parse(res)
#return res['s:Envelope']['s:Body']['x:ResourceCreated']['a:ReferenceParameters']['w:SelectorSet']['w:Selector']['#text']
root = ET.fromstring(res)
return next(
node for node in root.findall('.//*')
if node.get('Name') == 'ShellId').text | python | def open_shell(self, i_stream='stdin', o_stream='stdout stderr',
working_directory=None, env_vars=None, noprofile=False,
codepage=437, lifetime=None, idle_timeout=None):
req = {'env:Envelope': self._get_soap_header(
resource_uri='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd', # NOQA
action='http://schemas.xmlsoap.org/ws/2004/09/transfer/Create')}
header = req['env:Envelope']['env:Header']
header['w:OptionSet'] = {
'w:Option': [
{
'@Name': 'WINRS_NOPROFILE',
'#text': str(noprofile).upper() # TODO remove str call
},
{
'@Name': 'WINRS_CODEPAGE',
'#text': str(codepage) # TODO remove str call
}
]
}
shell = req['env:Envelope'].setdefault(
'env:Body', {}).setdefault('rsp:Shell', {})
shell['rsp:InputStreams'] = i_stream
shell['rsp:OutputStreams'] = o_stream
if working_directory:
# TODO ensure that rsp:WorkingDirectory should be nested within rsp:Shell # NOQA
shell['rsp:WorkingDirectory'] = working_directory
# TODO check Lifetime param: http://msdn.microsoft.com/en-us/library/cc251546(v=PROT.13).aspx # NOQA
#if lifetime:
# shell['rsp:Lifetime'] = iso8601_duration.sec_to_dur(lifetime)
# TODO make it so the input is given in milliseconds and converted to xs:duration # NOQA
if idle_timeout:
shell['rsp:IdleTimeOut'] = idle_timeout
if env_vars:
env = shell.setdefault('rsp:Environment', {})
for key, value in env_vars.items():
env['rsp:Variable'] = {'@Name': key, '#text': value}
res = self.send_message(xmltodict.unparse(req))
#res = xmltodict.parse(res)
#return res['s:Envelope']['s:Body']['x:ResourceCreated']['a:ReferenceParameters']['w:SelectorSet']['w:Selector']['#text']
root = ET.fromstring(res)
return next(
node for node in root.findall('.//*')
if node.get('Name') == 'ShellId').text | [
"def",
"open_shell",
"(",
"self",
",",
"i_stream",
"=",
"'stdin'",
",",
"o_stream",
"=",
"'stdout stderr'",
",",
"working_directory",
"=",
"None",
",",
"env_vars",
"=",
"None",
",",
"noprofile",
"=",
"False",
",",
"codepage",
"=",
"437",
",",
"lifetime",
"... | Create a Shell on the destination host
@param string i_stream: Which input stream to open. Leave this alone
unless you know what you're doing (default: stdin)
@param string o_stream: Which output stream to open. Leave this alone
unless you know what you're doing (default: stdout stderr)
@param string working_directory: the directory to create the shell in
@param dict env_vars: environment variables to set for the shell. For
instance: {'PATH': '%PATH%;c:/Program Files (x86)/Git/bin/', 'CYGWIN':
'nontsec codepage:utf8'}
@returns The ShellId from the SOAP response. This is our open shell
instance on the remote machine.
@rtype string | [
"Create",
"a",
"Shell",
"on",
"the",
"destination",
"host"
] | ed4c2d991d9d0fe921dfc958c475c4c6a570519e | https://github.com/diyan/pywinrm/blob/ed4c2d991d9d0fe921dfc958c475c4c6a570519e/winrm/protocol.py#L104-L164 |
247,796 | diyan/pywinrm | winrm/protocol.py | Protocol.close_shell | def close_shell(self, shell_id):
"""
Close the shell
@param string shell_id: The shell id on the remote machine.
See #open_shell
@returns This should have more error checking but it just returns true
for now.
@rtype bool
"""
message_id = uuid.uuid4()
req = {'env:Envelope': self._get_soap_header(
resource_uri='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd', # NOQA
action='http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete',
shell_id=shell_id,
message_id=message_id)}
# SOAP message requires empty env:Body
req['env:Envelope'].setdefault('env:Body', {})
res = self.send_message(xmltodict.unparse(req))
root = ET.fromstring(res)
relates_to = next(
node for node in root.findall('.//*')
if node.tag.endswith('RelatesTo')).text
# TODO change assert into user-friendly exception
assert uuid.UUID(relates_to.replace('uuid:', '')) == message_id | python | def close_shell(self, shell_id):
message_id = uuid.uuid4()
req = {'env:Envelope': self._get_soap_header(
resource_uri='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd', # NOQA
action='http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete',
shell_id=shell_id,
message_id=message_id)}
# SOAP message requires empty env:Body
req['env:Envelope'].setdefault('env:Body', {})
res = self.send_message(xmltodict.unparse(req))
root = ET.fromstring(res)
relates_to = next(
node for node in root.findall('.//*')
if node.tag.endswith('RelatesTo')).text
# TODO change assert into user-friendly exception
assert uuid.UUID(relates_to.replace('uuid:', '')) == message_id | [
"def",
"close_shell",
"(",
"self",
",",
"shell_id",
")",
":",
"message_id",
"=",
"uuid",
".",
"uuid4",
"(",
")",
"req",
"=",
"{",
"'env:Envelope'",
":",
"self",
".",
"_get_soap_header",
"(",
"resource_uri",
"=",
"'http://schemas.microsoft.com/wbem/wsman/1/windows/... | Close the shell
@param string shell_id: The shell id on the remote machine.
See #open_shell
@returns This should have more error checking but it just returns true
for now.
@rtype bool | [
"Close",
"the",
"shell"
] | ed4c2d991d9d0fe921dfc958c475c4c6a570519e | https://github.com/diyan/pywinrm/blob/ed4c2d991d9d0fe921dfc958c475c4c6a570519e/winrm/protocol.py#L274-L299 |
247,797 | diyan/pywinrm | winrm/protocol.py | Protocol.run_command | def run_command(
self, shell_id, command, arguments=(), console_mode_stdin=True,
skip_cmd_shell=False):
"""
Run a command on a machine with an open shell
@param string shell_id: The shell id on the remote machine.
See #open_shell
@param string command: The command to run on the remote machine
@param iterable of string arguments: An array of arguments for this
command
@param bool console_mode_stdin: (default: True)
@param bool skip_cmd_shell: (default: False)
@return: The CommandId from the SOAP response.
This is the ID we need to query in order to get output.
@rtype string
"""
req = {'env:Envelope': self._get_soap_header(
resource_uri='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd', # NOQA
action='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command', # NOQA
shell_id=shell_id)}
header = req['env:Envelope']['env:Header']
header['w:OptionSet'] = {
'w:Option': [
{
'@Name': 'WINRS_CONSOLEMODE_STDIN',
'#text': str(console_mode_stdin).upper()
},
{
'@Name': 'WINRS_SKIP_CMD_SHELL',
'#text': str(skip_cmd_shell).upper()
}
]
}
cmd_line = req['env:Envelope'].setdefault(
'env:Body', {}).setdefault('rsp:CommandLine', {})
cmd_line['rsp:Command'] = {'#text': command}
if arguments:
unicode_args = [a if isinstance(a, text_type) else a.decode('utf-8') for a in arguments]
cmd_line['rsp:Arguments'] = u' '.join(unicode_args)
res = self.send_message(xmltodict.unparse(req))
root = ET.fromstring(res)
command_id = next(
node for node in root.findall('.//*')
if node.tag.endswith('CommandId')).text
return command_id | python | def run_command(
self, shell_id, command, arguments=(), console_mode_stdin=True,
skip_cmd_shell=False):
req = {'env:Envelope': self._get_soap_header(
resource_uri='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd', # NOQA
action='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command', # NOQA
shell_id=shell_id)}
header = req['env:Envelope']['env:Header']
header['w:OptionSet'] = {
'w:Option': [
{
'@Name': 'WINRS_CONSOLEMODE_STDIN',
'#text': str(console_mode_stdin).upper()
},
{
'@Name': 'WINRS_SKIP_CMD_SHELL',
'#text': str(skip_cmd_shell).upper()
}
]
}
cmd_line = req['env:Envelope'].setdefault(
'env:Body', {}).setdefault('rsp:CommandLine', {})
cmd_line['rsp:Command'] = {'#text': command}
if arguments:
unicode_args = [a if isinstance(a, text_type) else a.decode('utf-8') for a in arguments]
cmd_line['rsp:Arguments'] = u' '.join(unicode_args)
res = self.send_message(xmltodict.unparse(req))
root = ET.fromstring(res)
command_id = next(
node for node in root.findall('.//*')
if node.tag.endswith('CommandId')).text
return command_id | [
"def",
"run_command",
"(",
"self",
",",
"shell_id",
",",
"command",
",",
"arguments",
"=",
"(",
")",
",",
"console_mode_stdin",
"=",
"True",
",",
"skip_cmd_shell",
"=",
"False",
")",
":",
"req",
"=",
"{",
"'env:Envelope'",
":",
"self",
".",
"_get_soap_head... | Run a command on a machine with an open shell
@param string shell_id: The shell id on the remote machine.
See #open_shell
@param string command: The command to run on the remote machine
@param iterable of string arguments: An array of arguments for this
command
@param bool console_mode_stdin: (default: True)
@param bool skip_cmd_shell: (default: False)
@return: The CommandId from the SOAP response.
This is the ID we need to query in order to get output.
@rtype string | [
"Run",
"a",
"command",
"on",
"a",
"machine",
"with",
"an",
"open",
"shell"
] | ed4c2d991d9d0fe921dfc958c475c4c6a570519e | https://github.com/diyan/pywinrm/blob/ed4c2d991d9d0fe921dfc958c475c4c6a570519e/winrm/protocol.py#L301-L346 |
247,798 | diyan/pywinrm | winrm/protocol.py | Protocol.get_command_output | def get_command_output(self, shell_id, command_id):
"""
Get the Output of the given shell and command
@param string shell_id: The shell id on the remote machine.
See #open_shell
@param string command_id: The command id on the remote machine.
See #run_command
#@return [Hash] Returns a Hash with a key :exitcode and :data.
Data is an Array of Hashes where the cooresponding key
# is either :stdout or :stderr. The reason it is in an Array so so
we can get the output in the order it ocurrs on
# the console.
"""
stdout_buffer, stderr_buffer = [], []
command_done = False
while not command_done:
try:
stdout, stderr, return_code, command_done = \
self._raw_get_command_output(shell_id, command_id)
stdout_buffer.append(stdout)
stderr_buffer.append(stderr)
except WinRMOperationTimeoutError as e:
# this is an expected error when waiting for a long-running process, just silently retry
pass
return b''.join(stdout_buffer), b''.join(stderr_buffer), return_code | python | def get_command_output(self, shell_id, command_id):
stdout_buffer, stderr_buffer = [], []
command_done = False
while not command_done:
try:
stdout, stderr, return_code, command_done = \
self._raw_get_command_output(shell_id, command_id)
stdout_buffer.append(stdout)
stderr_buffer.append(stderr)
except WinRMOperationTimeoutError as e:
# this is an expected error when waiting for a long-running process, just silently retry
pass
return b''.join(stdout_buffer), b''.join(stderr_buffer), return_code | [
"def",
"get_command_output",
"(",
"self",
",",
"shell_id",
",",
"command_id",
")",
":",
"stdout_buffer",
",",
"stderr_buffer",
"=",
"[",
"]",
",",
"[",
"]",
"command_done",
"=",
"False",
"while",
"not",
"command_done",
":",
"try",
":",
"stdout",
",",
"stde... | Get the Output of the given shell and command
@param string shell_id: The shell id on the remote machine.
See #open_shell
@param string command_id: The command id on the remote machine.
See #run_command
#@return [Hash] Returns a Hash with a key :exitcode and :data.
Data is an Array of Hashes where the cooresponding key
# is either :stdout or :stderr. The reason it is in an Array so so
we can get the output in the order it ocurrs on
# the console. | [
"Get",
"the",
"Output",
"of",
"the",
"given",
"shell",
"and",
"command"
] | ed4c2d991d9d0fe921dfc958c475c4c6a570519e | https://github.com/diyan/pywinrm/blob/ed4c2d991d9d0fe921dfc958c475c4c6a570519e/winrm/protocol.py#L380-L404 |
247,799 | diyan/pywinrm | winrm/__init__.py | Session.run_ps | def run_ps(self, script):
"""base64 encodes a Powershell script and executes the powershell
encoded script command
"""
# must use utf16 little endian on windows
encoded_ps = b64encode(script.encode('utf_16_le')).decode('ascii')
rs = self.run_cmd('powershell -encodedcommand {0}'.format(encoded_ps))
if len(rs.std_err):
# if there was an error message, clean it it up and make it human
# readable
rs.std_err = self._clean_error_msg(rs.std_err)
return rs | python | def run_ps(self, script):
# must use utf16 little endian on windows
encoded_ps = b64encode(script.encode('utf_16_le')).decode('ascii')
rs = self.run_cmd('powershell -encodedcommand {0}'.format(encoded_ps))
if len(rs.std_err):
# if there was an error message, clean it it up and make it human
# readable
rs.std_err = self._clean_error_msg(rs.std_err)
return rs | [
"def",
"run_ps",
"(",
"self",
",",
"script",
")",
":",
"# must use utf16 little endian on windows",
"encoded_ps",
"=",
"b64encode",
"(",
"script",
".",
"encode",
"(",
"'utf_16_le'",
")",
")",
".",
"decode",
"(",
"'ascii'",
")",
"rs",
"=",
"self",
".",
"run_c... | base64 encodes a Powershell script and executes the powershell
encoded script command | [
"base64",
"encodes",
"a",
"Powershell",
"script",
"and",
"executes",
"the",
"powershell",
"encoded",
"script",
"command"
] | ed4c2d991d9d0fe921dfc958c475c4c6a570519e | https://github.com/diyan/pywinrm/blob/ed4c2d991d9d0fe921dfc958c475c4c6a570519e/winrm/__init__.py#L44-L55 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.