sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def _buttonbox(msg, title, choices, root=None, timeout=None):
"""
Display a msg, a title, and a set of buttons.
The buttons are defined by the members of the choices list.
Return the text of the button that the user selected.
@arg msg: the msg to be displayed.
@arg title: the window title
@... | Display a msg, a title, and a set of buttons.
The buttons are defined by the members of the choices list.
Return the text of the button that the user selected.
@arg msg: the msg to be displayed.
@arg title: the window title
@arg choices: a list or tuple of the choices to be displayed | entailment |
def __put_buttons_in_buttonframe(choices):
"""Put the buttons in the buttons frame"""
global __widgetTexts, __firstWidget, buttonsFrame
__firstWidget = None
__widgetTexts = {}
i = 0
for buttonText in choices:
tempButton = tk.Button(buttonsFrame, takefocus=1, text=buttonText)
_... | Put the buttons in the buttons frame | entailment |
def __fillablebox(msg, title='', default='', mask=None, root=None, timeout=None):
"""
Show a box in which a user can enter some text.
You may optionally specify some default text, which will appear in the
enterbox when it is displayed.
Returns the text that the user entered, or None if he cancels th... | Show a box in which a user can enter some text.
You may optionally specify some default text, which will appear in the
enterbox when it is displayed.
Returns the text that the user entered, or None if he cancels the operation. | entailment |
def parse(self, response):
"""
Parse the login xml response
:param response: the login response from the RETS server
:return: None
"""
self.headers = response.headers
if 'xml' in self.headers.get('Content-Type'):
# Got an XML response, likely an error... | Parse the login xml response
:param response: the login response from the RETS server
:return: None | entailment |
def read_line(line):
"""Reads lines of XML and delimits, strips, and returns."""
name, value = '', ''
if '=' in line:
name, value = line.split('=', 1)
return [name.strip(), value.strip()] | Reads lines of XML and delimits, strips, and returns. | entailment |
def generator(self, response):
"""
Takes a response socket connection and iteratively parses and yields the results as python dictionaries.
:param response: a Requests response object with stream=True
:return:
"""
delim = '\t' # Default to tab delimited
columns ... | Takes a response socket connection and iteratively parses and yields the results as python dictionaries.
:param response: a Requests response object with stream=True
:return: | entailment |
def flatten_urlinfo(urlinfo, shorter_keys=True):
""" Takes a urlinfo object and returns a flat dictionary."""
def flatten(value, prefix=""):
if is_string(value):
_result[prefix[1:]] = value
return
try:
len(value)
except (AttributeError, TypeError): # ... | Takes a urlinfo object and returns a flat dictionary. | entailment |
def create_v4_signature(self, request_params):
'''
Create URI and signature headers based on AWS V4 signing process.
Refer to https://docs.aws.amazon.com/AlexaWebInfoService/latest/ApiReferenceArticle.html for request params.
:param request_params: dictionary of request parameters
... | Create URI and signature headers based on AWS V4 signing process.
Refer to https://docs.aws.amazon.com/AlexaWebInfoService/latest/ApiReferenceArticle.html for request params.
:param request_params: dictionary of request parameters
:return: URL and header to be passed to requests.get | entailment |
def urlinfo(self, domain, response_group = URLINFO_RESPONSE_GROUPS):
'''
Provide information about supplied domain as specified by the response group
:param domain: Any valid URL
:param response_group: Any valid urlinfo response group
:return: Traffic and/or content data of the d... | Provide information about supplied domain as specified by the response group
:param domain: Any valid URL
:param response_group: Any valid urlinfo response group
:return: Traffic and/or content data of the domain in XML format | entailment |
def traffichistory(self, domain, response_group=TRAFFICINFO_RESPONSE_GROUPS, myrange=31, start=20070801):
'''
Provide traffic history of supplied domain
:param domain: Any valid URL
:param response_group: Any valid traffic history response group
:return: Traffic and/or content da... | Provide traffic history of supplied domain
:param domain: Any valid URL
:param response_group: Any valid traffic history response group
:return: Traffic and/or content data of the domain in XML format | entailment |
def cat_browse(self, domain, path, response_group=CATEGORYBROWSE_RESPONSE_GROUPS, descriptions='True'):
'''
Provide category browse information of specified domain
:param domain: Any valid URL
:param path: Valid category path
:param response_group: Any valid traffic history respo... | Provide category browse information of specified domain
:param domain: Any valid URL
:param path: Valid category path
:param response_group: Any valid traffic history response group
:return: Traffic and/or content data of the domain in XML format | entailment |
def add_capability(self, name, uri):
"""
Add a capability of the RETS board
:param name: The name of the capability
:param uri: The capability URI given by the RETS board
:return: None
"""
parse_results = urlparse(uri)
if parse_results.hostname is None:
... | Add a capability of the RETS board
:param name: The name of the capability
:param uri: The capability URI given by the RETS board
:return: None | entailment |
def login(self):
"""
Login to the RETS board and return an instance of Bulletin
:return: Bulletin instance
"""
response = self._request('Login')
parser = OneXLogin()
parser.parse(response)
self.session_id = response.cookies.get(self.session_id_cookie_name... | Login to the RETS board and return an instance of Bulletin
:return: Bulletin instance | entailment |
def get_resource_metadata(self, resource=None):
"""
Get resource metadata
:param resource: The name of the resource to get metadata for
:return: list
"""
result = self._make_metadata_request(meta_id=0, metadata_type='METADATA-RESOURCE')
if resource:
re... | Get resource metadata
:param resource: The name of the resource to get metadata for
:return: list | entailment |
def get_table_metadata(self, resource, resource_class):
"""
Get metadata for a given resource: class
:param resource: The name of the resource
:param resource_class: The name of the class to get metadata from
:return: list
"""
return self._make_metadata_request(me... | Get metadata for a given resource: class
:param resource: The name of the resource
:param resource_class: The name of the class to get metadata from
:return: list | entailment |
def get_lookup_values(self, resource, lookup_name):
"""
Get possible lookup values for a given field
:param resource: The name of the resource
:param lookup_name: The name of the the field to get lookup values for
:return: list
"""
return self._make_metadata_reque... | Get possible lookup values for a given field
:param resource: The name of the resource
:param lookup_name: The name of the the field to get lookup values for
:return: list | entailment |
def _make_metadata_request(self, meta_id, metadata_type=None):
"""
Get the Metadata. The Session initializes with 'COMPACT-DECODED' as the format type. If that returns a DTD error
then we change to the 'STANDARD-XML' format and try again.
:param meta_id: The name of the resource, class, ... | Get the Metadata. The Session initializes with 'COMPACT-DECODED' as the format type. If that returns a DTD error
then we change to the 'STANDARD-XML' format and try again.
:param meta_id: The name of the resource, class, or lookup to get metadata for
:param metadata_type: The RETS metadata type
... | entailment |
def get_preferred_object(self, resource, object_type, content_id, location=0):
"""
Get the first object from a Resource
:param resource: The name of the resource
:param object_type: The type of object to fetch
:param content_id: The unique id of the item to get objects for
... | Get the first object from a Resource
:param resource: The name of the resource
:param object_type: The type of object to fetch
:param content_id: The unique id of the item to get objects for
:param location: The path to get Objects from
:return: Object | entailment |
def get_object(self, resource, object_type, content_ids, object_ids='*', location=0):
"""
Get a list of Objects from a resource
:param resource: The resource to get objects from
:param object_type: The type of object to fetch
:param content_ids: The unique id of the item to get o... | Get a list of Objects from a resource
:param resource: The resource to get objects from
:param object_type: The type of object to fetch
:param content_ids: The unique id of the item to get objects for
:param object_ids: ids of the objects to download
:param location: The path to ... | entailment |
def search(self, resource, resource_class, search_filter=None, dmql_query=None, limit=9999999, offset=0,
optional_parameters=None, auto_offset=True, query_type='DMQL2', standard_names=0,
response_format='COMPACT-DECODED'):
"""
Preform a search on the RETS board
:par... | Preform a search on the RETS board
:param resource: The resource that contains the class to search
:param resource_class: The class to search
:param search_filter: The query as a dict
:param dmql_query: The query in dmql format
:param limit: Limit search values count
:par... | entailment |
def _request(self, capability, options=None, stream=False):
"""
Make a _request to the RETS server
:param capability: The name of the capability to use to get the URI
:param options: Options to put into the _request
:return: Response
"""
if options is None:
... | Make a _request to the RETS server
:param capability: The name of the capability to use to get the URI
:param options: Options to put into the _request
:return: Response | entailment |
def _user_agent_digest_hash(self):
"""
Hash the user agent and user agent password
Section 3.10 of https://www.nar.realtor/retsorg.nsf/retsproto1.7d6.pdf
:return: md5
"""
if not self.version:
raise MissingVersion("A version is required for user agent auth. The... | Hash the user agent and user agent password
Section 3.10 of https://www.nar.realtor/retsorg.nsf/retsproto1.7d6.pdf
:return: md5 | entailment |
def response_minify(self, response):
"""
minify response html to decrease traffic
"""
if response.content_type == u'text/html; charset=utf-8':
endpoint = request.endpoint or ''
view_func = current_app.view_functions.get(endpoint, None)
name = (
... | minify response html to decrease traffic | entailment |
def exempt(self, obj):
"""
decorator to mark a view as exempt from htmlmin.
"""
name = '%s.%s' % (obj.__module__, obj.__name__)
@wraps(obj)
def __inner(*a, **k):
return obj(*a, **k)
self._exempt_routes.add(name)
return __inner | decorator to mark a view as exempt from htmlmin. | entailment |
def dmql(query):
"""Client supplied raw DMQL, ensure quote wrap."""
if isinstance(query, dict):
raise ValueError("You supplied a dictionary to the dmql_query parameter, but a string is required."
" Did you mean to pass this to the search_filter parameter? ")
... | Client supplied raw DMQL, ensure quote wrap. | entailment |
def filter_to_dmql(filter_dict):
"""Converts the filter dictionary into DMQL"""
if not isinstance(filter_dict, (dict, collections.OrderedDict)):
raise TypeError('Expected a dictionary type buy got {} instead.'.format(type(filter_dict)))
def is_date_time_type(val):
"""Re... | Converts the filter dictionary into DMQL | entailment |
def get_attributes(input_dict):
"""
Get attributes of xml tags in input_dict and creates a dictionary with the attribute name as the key and the
attribute value as the value
:param input_dict: The xml tag with the attributes and values
:return: dict
"""
return {k.... | Get attributes of xml tags in input_dict and creates a dictionary with the attribute name as the key and the
attribute value as the value
:param input_dict: The xml tag with the attributes and values
:return: dict | entailment |
def data_columns_to_dict(columns_string, dict_string, delimiter=None):
"""
Turns column names in a single string into a dictionary with the key being the column name and the value
being the value in that column for each row
:param columns_string: A string of column names
:param d... | Turns column names in a single string into a dictionary with the key being the column name and the value
being the value in that column for each row
:param columns_string: A string of column names
:param dict_string: A string of values
:param delimiter: The delimiter to use to split the ... | entailment |
def analyze_reply_code(self, xml_response_dict):
"""
Checks the RETS Response Code and handles non-zero answers.
:param xml_response_dict:
:return: None
"""
if 'RETS-STATUS' in xml_response_dict:
attributes = self.get_attributes(xml_response_dict['RETS-STATUS'... | Checks the RETS Response Code and handles non-zero answers.
:param xml_response_dict:
:return: None | entailment |
def ids(self, content_ids, object_ids):
"""Appends the content and object ids how RETS expects them"""
result = []
content_ids = self.split(content_ids, False)
object_ids = self.split(object_ids)
for cid in content_ids:
result.append('{}:{}'.format(cid, ':'.join(obj... | Appends the content and object ids how RETS expects them | entailment |
def split(value, dash_ranges=True):
"""Splits """
if isinstance(value, list):
value = [str(v) for v in value]
else:
str_value = str(value)
dash_matches = re.match(pattern='(\d+)\-(\d+)', string=str_value)
if ':' in str_value or ',' in str_value:
... | Splits | entailment |
def set_value(self, key, value):
"""
Set key value to the file.
The fuction will be make the key and value to dictinary formate.
If its exist then it will update the current new key value to
the file.
Arg:
key : cache key
value : cache value
"""
... | Set key value to the file.
The fuction will be make the key and value to dictinary formate.
If its exist then it will update the current new key value to
the file.
Arg:
key : cache key
value : cache value | entailment |
def delete_value(self, key):
"""
Delete the key if the token is expired.
Arg:
key : cache key
"""
response = {}
response['status'] = False
response['msg'] = "key does not exist"
file_cache = self.read_file()
if key in file_cache:
... | Delete the key if the token is expired.
Arg:
key : cache key | entailment |
def read_file(self):
"""
Open the file and assiging the permission to read/write and
return the content in json formate.
Return : json data
"""
file_obj = open(self.file, 'r')
content = file_obj.read()
file_obj.close()
if content:
cont... | Open the file and assiging the permission to read/write and
return the content in json formate.
Return : json data | entailment |
def update_file(self, content):
"""
It will convert json content to json string and update into file.
Return:
Boolean True/False
"""
updated_content = json.dumps(content)
file_obj = open(self.file, 'r+')
file_obj.write(str(updated_content))
file_o... | It will convert json content to json string and update into file.
Return:
Boolean True/False | entailment |
def parse(self, response, metadata_type):
"""
Parses RETS metadata using the COMPACT-DECODED format
:param response:
:param metadata_type:
:return:
"""
xml = xmltodict.parse(response.text)
self.analyze_reply_code(xml_response_dict=xml)
base = xml.g... | Parses RETS metadata using the COMPACT-DECODED format
:param response:
:param metadata_type:
:return: | entailment |
def parse(self, response, metadata_type):
"""
Parses RETS metadata using the STANDARD-XML format
:param response: requests Response object
:param metadata_type: string
:return parsed: list
"""
xml = xmltodict.parse(response.text)
self.analyze_reply_code(xm... | Parses RETS metadata using the STANDARD-XML format
:param response: requests Response object
:param metadata_type: string
:return parsed: list | entailment |
def _get_multiparts(response):
"""
From this
'multipart/parallel; boundary="874e43d27ec6d83f30f37841bdaf90c7"; charset=utf-8'
get this
--874e43d27ec6d83f30f37841bdaf90c7
"""
boundary = None
for part in response.headers.get('Content-Type', '').split(';'):
... | From this
'multipart/parallel; boundary="874e43d27ec6d83f30f37841bdaf90c7"; charset=utf-8'
get this
--874e43d27ec6d83f30f37841bdaf90c7 | entailment |
def parse_image_response(self, response):
"""
Parse multiple objects from the RETS feed. A lot of string methods are used to handle the response before
encoding it back into bytes for the object.
:param response: The response from the feed
:return: list of SingleObjectParser
... | Parse multiple objects from the RETS feed. A lot of string methods are used to handle the response before
encoding it back into bytes for the object.
:param response: The response from the feed
:return: list of SingleObjectParser | entailment |
def parse_image_response(self, response):
"""
Parse a single object from the RETS feed
:param response: The response from the RETS server
:return: Object
"""
if 'xml' in response.headers.get('Content-Type'):
# Got an XML response, likely an error code.
... | Parse a single object from the RETS feed
:param response: The response from the RETS server
:return: Object | entailment |
def auth(self):
"""
Auth is used to call the AUTH API of CricketAPI.
Access token required for every request call to CricketAPI.
Auth functional will post user Cricket API app details to server
and return the access token.
Return:
Access token
... | Auth is used to call the AUTH API of CricketAPI.
Access token required for every request call to CricketAPI.
Auth functional will post user Cricket API app details to server
and return the access token.
Return:
Access token | entailment |
def get_response(self, url, params={}, method="get"):
"""
It will return json response based on given url, params and methods.
Arg:
params: 'dictionary'
url: 'url' format
method: default 'get', support method 'post'
Return:
json data ... | It will return json response based on given url, params and methods.
Arg:
params: 'dictionary'
url: 'url' format
method: default 'get', support method 'post'
Return:
json data | entailment |
def get_active_token(self):
"""
Getting the valid access token.
Access token expires every 24 hours, It will expires then it will
generate a new token.
Return:
active access token
"""
expire_time = self.store_handler.has_value("expires")
... | Getting the valid access token.
Access token expires every 24 hours, It will expires then it will
generate a new token.
Return:
active access token | entailment |
def get_match(self, match_key, card_type="full_card"):
"""
Calling the Match API.
Arg:
match_key: key of the match
card_type: optional, default to full_card. Accepted values are
micro_card, summary_card & full_card.
Return:
json data
... | Calling the Match API.
Arg:
match_key: key of the match
card_type: optional, default to full_card. Accepted values are
micro_card, summary_card & full_card.
Return:
json data | entailment |
def get_recent_matches(self, card_type="micro_card"):
"""
Calling the Recent Matches API.
Arg:
card_type: optional, default to micro_card. Accepted values are
micro_card & summary_card.
Return:
json data
"""
recent_matches_url = self.api... | Calling the Recent Matches API.
Arg:
card_type: optional, default to micro_card. Accepted values are
micro_card & summary_card.
Return:
json data | entailment |
def get_player_stats(self, player_key, board_key):
"""
Calling the Player Stats API
Args:
player_key: Key of the player
board_key: key of the board
Return:
json data
"""
player_stats_url = self.api_path + 'player/' + player_key + '/leag... | Calling the Player Stats API
Args:
player_key: Key of the player
board_key: key of the board
Return:
json data | entailment |
def get_ball_by_ball(self, match_key, over_key=None):
"""
match_key: key of the match
over_key : key of the over
Return:
json data:
"""
if over_key:
ball_by_ball_url = "{base_path}match/{match_key}/balls/{over_key}/".format(base_path=self.... | match_key: key of the match
over_key : key of the over
Return:
json data: | entailment |
def get_recent_season_matches(self, season_key):
"""
Calling specific season recent matches.
Arg:
season_key: key of the season.
Return:
json date
"""
season_recent_matches_url = self.api_path + "season/" + season_key + "/recent_matches/"
r... | Calling specific season recent matches.
Arg:
season_key: key of the season.
Return:
json date | entailment |
def get_recent_seasons(self):
"""
Calling the Recent Season API.
Return:
json data
"""
recent_seasons_url = self.api_path + "recent_seasons/"
response = self.get_response(recent_seasons_url)
return response | Calling the Recent Season API.
Return:
json data | entailment |
def get_schedule(self, date=None):
"""
Calling the Schedule API.
Return:
json data
"""
schedule_url = self.api_path + "schedule/"
params = {}
if date:
params['date'] = date
response = self.get_response(schedule_url, params)
... | Calling the Schedule API.
Return:
json data | entailment |
def get_season_schedule(self, season_key):
"""
Calling specific season schedule
Arg:
season_key: key of the season
Return:
json data
"""
schedule_url = self.api_path + "season/" + season_key + "/schedule/"
response = self.get_response(sched... | Calling specific season schedule
Arg:
season_key: key of the season
Return:
json data | entailment |
def get_season(self, season_key, card_type="micro_card"):
"""
Calling Season API.
Arg:
season_key: key of the season
card_type: optional, default to micro_card. Accepted values are
micro_card & summary_card
Return:
json data
"""
... | Calling Season API.
Arg:
season_key: key of the season
card_type: optional, default to micro_card. Accepted values are
micro_card & summary_card
Return:
json data | entailment |
def get_season_stats(self, season_key):
"""
Calling Season Stats API.
Arg:
season_key: key of the season
Return:
json data
"""
season_stats_url = self.api_path + "season/" + season_key + "/stats/"
response = self.get_response(season_stats_u... | Calling Season Stats API.
Arg:
season_key: key of the season
Return:
json data | entailment |
def get_season_team(self, season_key, season_team_key,stats_type=None):
"""
Calling Season teams API
Arg:
season_key: key of the season
Return:
json data
"""
params = {"stats_type": stats_type}
season_team_url = self.api_path + 'season/' +... | Calling Season teams API
Arg:
season_key: key of the season
Return:
json data | entailment |
def get_season_points(self, season_key):
"""
Calling Season Points API.
Arg:
season_key: key of the season
Return:
json data
"""
season_points_url = self.api_path + "season/" + season_key + "/points/"
response = self.get_response(season_poi... | Calling Season Points API.
Arg:
season_key: key of the season
Return:
json data | entailment |
def get_season_player_stats(self, season_key, player_key):
"""
Calling Season Player Stats API.
Arg:
season_key: key of the season
player_key: key of the player
Return:
json data
"""
season_player_stats_url = self.api_path + "season/" + ... | Calling Season Player Stats API.
Arg:
season_key: key of the season
player_key: key of the player
Return:
json data | entailment |
def get_overs_summary(self, match_key):
"""
Calling Overs Summary API
Arg:
match_key: key of the match
Return:
json data
"""
overs_summary_url = self.api_path + "match/" + match_key + "/overs_summary/"
response = self.get_response(overs_summ... | Calling Overs Summary API
Arg:
match_key: key of the match
Return:
json data | entailment |
def get_news_aggregation(self):
"""
Calling News Aggregation API
Return:
json data
"""
news_aggregation_url = self.api_path + "news_aggregation" + "/"
response = self.get_response(news_aggregation_url)
return response | Calling News Aggregation API
Return:
json data | entailment |
def get_fantasy_credits(self, match_key):
"""
Calling Fantasy Credit API
Arg:
match_key: key of the match
Return:
json data
"""
fantasy_credit_url = self.api_path_v3 + "fantasy-match-credits/" + match_key + "/"
response = self.get_respons... | Calling Fantasy Credit API
Arg:
match_key: key of the match
Return:
json data | entailment |
def get_fantasy_points(self, match_key):
"""
Calling Fantasy Points API
Arg:
match_key: key of the match
Return:
json data
"""
fantasy_points_url = self.api_path_v3 + "fantasy-match-points/" + match_key + "/"
response = self.get_response(... | Calling Fantasy Points API
Arg:
match_key: key of the match
Return:
json data | entailment |
def main(self):
"""
Generates an output string by replacing the keywords in the format
string with the corresponding values from a submission dictionary.
"""
self.manage_submissions()
out_string = self.options['format']
# Pop until we get something which len(titl... | Generates an output string by replacing the keywords in the format
string with the corresponding values from a submission dictionary. | entailment |
def login(self):
"""
Logs into Reddit in order to display a personalised front page.
"""
data = {'user': self.options['username'], 'passwd':
self.options['password'], 'api_type': 'json'}
response = self.client.post('http://www.reddit.com/api/login', data=data)
... | Logs into Reddit in order to display a personalised front page. | entailment |
def manage_submissions(self):
"""
If there are no or only one submissions left, get new submissions.
This function manages URL creation and the specifics for front page
or subreddit mode.
"""
if not hasattr(self, 'submissions') or len(self.submissions) == 1:
s... | If there are no or only one submissions left, get new submissions.
This function manages URL creation and the specifics for front page
or subreddit mode. | entailment |
def get_submissions(self, url):
"""
Connects to Reddit and gets a JSON representation of submissions.
This JSON data is then processed and returned.
url: A url that requests for submissions should be sent to.
"""
response = self.client.get(url, params={'limit': self.opti... | Connects to Reddit and gets a JSON representation of submissions.
This JSON data is then processed and returned.
url: A url that requests for submissions should be sent to. | entailment |
def main(self):
"""
A compulsary function that gets the output of the cmus-remote -Q command
and converts it to unicode in order for it to be processed and finally
output.
"""
try:
# Setting stderr to subprocess.STDOUT seems to stop the error
# mes... | A compulsary function that gets the output of the cmus-remote -Q command
and converts it to unicode in order for it to be processed and finally
output. | entailment |
def convert_cmus_output(self, cmus_output):
"""
Change the newline separated string of output data into
a dictionary which can then be used to replace the strings in the config
format.
cmus_output: A string with information about cmus that is newline
seperated. Running c... | Change the newline separated string of output data into
a dictionary which can then be used to replace the strings in the config
format.
cmus_output: A string with information about cmus that is newline
seperated. Running cmus-remote -Q in a terminal will show you what
you're de... | entailment |
def convert_time(self, time):
"""
A helper function to convert seconds into hh:mm:ss for better
readability.
time: A string representing time in seconds.
"""
time_string = str(datetime.timedelta(seconds=int(time)))
if time_string.split(':')[0] == '0':
... | A helper function to convert seconds into hh:mm:ss for better
readability.
time: A string representing time in seconds. | entailment |
def output(self, full_text, short_text):
"""
Output all of the options and data for a segment.
full_text: A string representing the data that should be output to i3bar.
short_text: A more concise version of full_text, in case there is minimal
room on the i3bar.
"""
... | Output all of the options and data for a segment.
full_text: A string representing the data that should be output to i3bar.
short_text: A more concise version of full_text, in case there is minimal
room on the i3bar. | entailment |
def on_click(self, event):
"""
A function that should be overwritten by a plugin that wishes to react
to events, if it wants to perform any action other than running the
supplied command related to a button.
event: A dictionary passed from i3bar (after being decoded from JSON)
... | A function that should be overwritten by a plugin that wishes to react
to events, if it wants to perform any action other than running the
supplied command related to a button.
event: A dictionary passed from i3bar (after being decoded from JSON)
that has the folowing format:
e... | entailment |
def url_reverse(request):
"""
Reverse the requested URL (passed via GET / POST as `url_name` parameter)
:param request: Request object
:return: The reversed path
"""
if request.method in ('GET', 'POST'):
data = getattr(request, request.method)
url_name = data.get('url_name')
... | Reverse the requested URL (passed via GET / POST as `url_name` parameter)
:param request: Request object
:return: The reversed path | entailment |
def url_image(request, image_id, thumb_options=None, width=None, height=None):
"""
Converts a filer image ID in a complete path
:param request: Request object
:param image_id: Filer image ID
:param thumb_options: ThumbnailOption ID
:param width: user-provided width
:param height: user-provi... | Converts a filer image ID in a complete path
:param request: Request object
:param image_id: Filer image ID
:param thumb_options: ThumbnailOption ID
:param width: user-provided width
:param height: user-provided height
:return: JSON serialized URL components ('url', 'width', 'height') | entailment |
def thumbnail_options(request):
"""
Returns the requested ThumbnailOption as JSON
:param request: Request object
:return: JSON serialized ThumbnailOption
"""
response_data = [{'id': opt.pk, 'name': opt.name} for opt in ThumbnailOption.objects.all()]
return http.HttpResponse(json.dumps(respo... | Returns the requested ThumbnailOption as JSON
:param request: Request object
:return: JSON serialized ThumbnailOption | entailment |
def serve_image(request, image_id, thumb_options=None, width=None, height=None):
"""
returns the content of an image sized according to the parameters
:param request: Request object
:param image_id: Filer image ID
:param thumb_options: ThumbnailOption ID
:param width: user-provided width
:p... | returns the content of an image sized according to the parameters
:param request: Request object
:param image_id: Filer image ID
:param thumb_options: ThumbnailOption ID
:param width: user-provided width
:param height: user-provided height
:return: JSON serialized URL components ('url', 'width'... | entailment |
def _touch_dir(self, path):
"""
A helper function to create a directory if it doesn't exist.
path: A string containing a full path to the directory to be created.
"""
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
... | A helper function to create a directory if it doesn't exist.
path: A string containing a full path to the directory to be created. | entailment |
def reload(self):
"""
Reload the configuration from the file. This is in its own function
so that it can be called at any time by another class.
"""
self._conf = configparser.ConfigParser()
# Preserve the case of sections and keys.
self._conf.optionxform = str
... | Reload the configuration from the file. This is in its own function
so that it can be called at any time by another class. | entailment |
def _replace_data_types(dictionary):
"""
Replaces strings with appropriate data types (int, boolean).
Also replaces the human readable logging levels with the integer form.
dictionary: A dictionary returned from the config file.
"""
logging_levels = {'NONE': 0, 'NULL': 0... | Replaces strings with appropriate data types (int, boolean).
Also replaces the human readable logging levels with the integer form.
dictionary: A dictionary returned from the config file. | entailment |
def main():
"""Command line interface for the ``rotate-backups`` program."""
coloredlogs.install(syslog=True)
# Command line option defaults.
rotation_scheme = {}
kw = dict(include_list=[], exclude_list=[])
parallel = False
use_sudo = False
# Internal state.
selected_locations = []
... | Command line interface for the ``rotate-backups`` program. | entailment |
def get_battery_state(self, prop):
"""
Return the first line from the file located at battery_path/prop as a
string.
"""
with open(os.path.join(self.options['battery_path'], prop), 'r') as f:
return f.readline().strip() | Return the first line from the file located at battery_path/prop as a
string. | entailment |
def coerce_location(value, **options):
"""
Coerce a string to a :class:`Location` object.
:param value: The value to coerce (a string or :class:`Location` object).
:param options: Any keyword arguments are passed on to
:func:`~executor.contexts.create_context()`.
:returns: A :cl... | Coerce a string to a :class:`Location` object.
:param value: The value to coerce (a string or :class:`Location` object).
:param options: Any keyword arguments are passed on to
:func:`~executor.contexts.create_context()`.
:returns: A :class:`Location` object. | entailment |
def coerce_retention_period(value):
"""
Coerce a retention period to a Python value.
:param value: A string containing the text 'always', a number or
an expression that can be evaluated to a number.
:returns: A number or the string 'always'.
:raises: :exc:`~exceptions.ValueError` ... | Coerce a retention period to a Python value.
:param value: A string containing the text 'always', a number or
an expression that can be evaluated to a number.
:returns: A number or the string 'always'.
:raises: :exc:`~exceptions.ValueError` when the string can't be coerced. | entailment |
def load_config_file(configuration_file=None, expand=True):
"""
Load a configuration file with backup directories and rotation schemes.
:param configuration_file: Override the pathname of the configuration file
to load (a string or :data:`None`).
:param expand: :data:`Tru... | Load a configuration file with backup directories and rotation schemes.
:param configuration_file: Override the pathname of the configuration file
to load (a string or :data:`None`).
:param expand: :data:`True` to expand filename patterns to their matches,
:dat... | entailment |
def rotate_backups(directory, rotation_scheme, **options):
"""
Rotate the backups in a directory according to a flexible rotation scheme.
.. note:: This function exists to preserve backwards compatibility with
older versions of the `rotate-backups` package where all of the
logic... | Rotate the backups in a directory according to a flexible rotation scheme.
.. note:: This function exists to preserve backwards compatibility with
older versions of the `rotate-backups` package where all of the
logic was exposed as a single function. Please refer to the
do... | entailment |
def rotate_concurrent(self, *locations, **kw):
"""
Rotate the backups in the given locations concurrently.
:param locations: One or more values accepted by :func:`coerce_location()`.
:param kw: Any keyword arguments are passed on to :func:`rotate_backups()`.
This function uses ... | Rotate the backups in the given locations concurrently.
:param locations: One or more values accepted by :func:`coerce_location()`.
:param kw: Any keyword arguments are passed on to :func:`rotate_backups()`.
This function uses :func:`rotate_backups()` to prepare rotation
commands for t... | entailment |
def rotate_backups(self, location, load_config=True, prepare=False):
"""
Rotate the backups in a directory according to a flexible rotation scheme.
:param location: Any value accepted by :func:`coerce_location()`.
:param load_config: If :data:`True` (so by default) the rotation scheme
... | Rotate the backups in a directory according to a flexible rotation scheme.
:param location: Any value accepted by :func:`coerce_location()`.
:param load_config: If :data:`True` (so by default) the rotation scheme
and other options can be customized by the user in
... | entailment |
def load_config_file(self, location):
"""
Load a rotation scheme and other options from a configuration file.
:param location: Any value accepted by :func:`coerce_location()`.
:returns: The configured or given :class:`Location` object.
"""
location = coerce_location(loca... | Load a rotation scheme and other options from a configuration file.
:param location: Any value accepted by :func:`coerce_location()`.
:returns: The configured or given :class:`Location` object. | entailment |
def collect_backups(self, location):
"""
Collect the backups at the given location.
:param location: Any value accepted by :func:`coerce_location()`.
:returns: A sorted :class:`list` of :class:`Backup` objects (the
backups are sorted by their date).
:raises: :e... | Collect the backups at the given location.
:param location: Any value accepted by :func:`coerce_location()`.
:returns: A sorted :class:`list` of :class:`Backup` objects (the
backups are sorted by their date).
:raises: :exc:`~exceptions.ValueError` when the given directory does... | entailment |
def group_backups(self, backups):
"""
Group backups collected by :func:`collect_backups()` by rotation frequencies.
:param backups: A :class:`set` of :class:`Backup` objects.
:returns: A :class:`dict` whose keys are the names of rotation
frequencies ('hourly', 'daily',... | Group backups collected by :func:`collect_backups()` by rotation frequencies.
:param backups: A :class:`set` of :class:`Backup` objects.
:returns: A :class:`dict` whose keys are the names of rotation
frequencies ('hourly', 'daily', etc.) and whose values are
dictiona... | entailment |
def apply_rotation_scheme(self, backups_by_frequency, most_recent_backup):
"""
Apply the user defined rotation scheme to the result of :func:`group_backups()`.
:param backups_by_frequency: A :class:`dict` in the format generated by
:func:`group_backups()`.
... | Apply the user defined rotation scheme to the result of :func:`group_backups()`.
:param backups_by_frequency: A :class:`dict` in the format generated by
:func:`group_backups()`.
:param most_recent_backup: The :class:`~datetime.datetime` of the most
... | entailment |
def find_preservation_criteria(self, backups_by_frequency):
"""
Collect the criteria used to decide which backups to preserve.
:param backups_by_frequency: A :class:`dict` in the format generated by
:func:`group_backups()` which has been
... | Collect the criteria used to decide which backups to preserve.
:param backups_by_frequency: A :class:`dict` in the format generated by
:func:`group_backups()` which has been
processed by :func:`apply_rotation_scheme()`.
:returns:... | entailment |
def mount_point(self):
"""
The pathname of the mount point of :attr:`directory` (a string or :data:`None`).
If the ``stat --format=%m ...`` command that is used to determine the
mount point fails, the value of this property defaults to :data:`None`.
This enables graceful degrada... | The pathname of the mount point of :attr:`directory` (a string or :data:`None`).
If the ``stat --format=%m ...`` command that is used to determine the
mount point fails, the value of this property defaults to :data:`None`.
This enables graceful degradation on e.g. Mac OS X whose ``stat``
... | entailment |
def ensure_exists(self):
"""Make sure the location exists."""
if not self.context.is_directory(self.directory):
# This can also happen when we don't have permission to one of the
# parent directories so we'll point that out in the error message
# when it seems applica... | Make sure the location exists. | entailment |
def ensure_readable(self):
"""Make sure the location exists and is readable."""
self.ensure_exists()
if not self.context.is_readable(self.directory):
if self.context.have_superuser_privileges:
msg = "The directory %s isn't readable!"
raise ValueError(m... | Make sure the location exists and is readable. | entailment |
def ensure_writable(self):
"""Make sure the directory exists and is writable."""
self.ensure_exists()
if not self.context.is_writable(self.directory):
if self.context.have_superuser_privileges:
msg = "The directory %s isn't writable!"
raise ValueError(... | Make sure the directory exists and is writable. | entailment |
def match(self, location):
"""
Check if the given location "matches".
:param location: The :class:`Location` object to try to match.
:returns: :data:`True` if the two locations are on the same system and
the :attr:`directory` can be matched as a filename pattern or
... | Check if the given location "matches".
:param location: The :class:`Location` object to try to match.
:returns: :data:`True` if the two locations are on the same system and
the :attr:`directory` can be matched as a filename pattern or
a literal match on the normalize... | entailment |
def setup_file_logger(filename, formatting, log_level):
"""
A helper function for creating a file logger.
Accepts arguments, as it is used in Status and LoggingWriter.
"""
logger = logging.getLogger()
# If a stream handler has been attached, remove it.
if logger.handlers:
logger.remo... | A helper function for creating a file logger.
Accepts arguments, as it is used in Status and LoggingWriter. | entailment |
def output_to_bar(self, message, comma=True):
"""
Outputs data to stdout, without buffering.
message: A string containing the data to be output.
comma: Whether or not a comma should be placed at the end of the output.
"""
if comma:
message += ','
sys.... | Outputs data to stdout, without buffering.
message: A string containing the data to be output.
comma: Whether or not a comma should be placed at the end of the output. | entailment |
def reload(self):
"""
Reload the installed plugins and the configuration file. This is called
when either the plugins or config get updated.
"""
logging.debug('Reloading config file as files have been modified.')
self.config.plugin, self.config.general = self.config.reloa... | Reload the installed plugins and the configuration file. This is called
when either the plugins or config get updated. | entailment |
def run_plugins(self):
"""
Creates a thread for each plugin and lets the thread_manager handle it.
"""
for obj in self.loader.objects:
# Reserve a slot in the output_dict in order to ensure that the
# items are in the correct order.
self.output_dict[ob... | Creates a thread for each plugin and lets the thread_manager handle it. | entailment |
def run(self):
"""
Monitors if the config file or plugins are updated. Also outputs the
JSON data generated by the plugins, without needing to poll the threads.
"""
self.run_plugins()
while True:
# Reload plugins and config if either the config file or plugin
... | Monitors if the config file or plugins are updated. Also outputs the
JSON data generated by the plugins, without needing to poll the threads. | entailment |
def _remove_empty_output(self):
"""
If plugins haven't been initialised and therefore not sending output or
their output is None, there is no reason to take up extra room on the
bar.
"""
output = []
for key in self.output_dict:
if self.output_dict[key]... | If plugins haven't been initialised and therefore not sending output or
their output is None, there is no reason to take up extra room on the
bar. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.