text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_etree(tree):
"""Constructs an executable form a given ElementTree structure. :param tree: :type tree: xml.etree.ElementTree.ElementTree :rtype: Executable """ |
exe = Executable(tree)
exe.category = tree.findtext('category')
exe.version = tree.findtext('version')
exe.title = tree.findtext('title') or exe.name
exe.description = tree.findtext('description')
exe.license = tree.findtext('license') or "unknown"
exe.contributor = tree.findtext('contributor')
for ps in tree.iterfind("parameters"):
assert isinstance(ps, ET.Element)
paras = ParameterGroup(
ps.findtext("label"),
ps.findtext("description"),
ps.attrib.get('advanced', "false") == "true",
filter(lambda x: x is not None,
map(Parameter.from_xml_node, list(ps))))
exe.parameter_groups.append(paras)
return exe |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def NoExclusions(self):
"""Determine that there are no exclusion criterion in play :return: True if there is no real boundary specification of any kind. Simple method allowing parsers to short circuit the determination of missingness, which can be moderately compute intensive. """ |
if len(self.start_bounds) + len(self.target_rs) + len(self.ignored_rs) == 0:
return BoundaryCheck.chrom == -1
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_address(self, host, port):
"""Add host and port attributes""" |
self.host = host
self.port = port |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self, host=None, port=None):
"""Connects to given host address and port.""" |
host = self.host if host is None else host
port = self.port if port is None else port
self.socket.connect(host, port) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_file_message(self, filename):
"""Send message inside the given file.""" |
data = self._readFile(filename)
self.print_debug_message(data)
self.socket.send(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_message(self, message):
"""Send a given message to the remote host.""" |
self.print_debug_message(message)
self.socket.send(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modified_after(first_path, second_path):
"""Returns True if first_path's mtime is higher than second_path's mtime.""" |
try:
first_mtime = os.stat(first_path).st_mtime
except EnvironmentError:
return False
try:
second_mtime = os.stat(second_path).st_mtime
except EnvironmentError:
return True
return first_mtime > second_mtime |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_packet(self, packet, ip, port):
""" React to incoming packet :param packet: Packet to handle :type packet: T >= paps.si.app.message.APPMessage :param ip: Client ip address :type ip: unicode :param port: Client port :type port: int :rtype: None """ |
msg_type = packet.header.message_type
if msg_type == MsgType.JOIN:
self._do_join_packet(packet, ip, port)
elif msg_type == MsgType.UNJOIN:
self._do_unjoin_packet(packet, ip, port)
elif msg_type == MsgType.UPDATE:
self._do_update_packet(packet, ip, port) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_join_packet(self, packet, ip, port):
""" React to join packet - add a client to this server :param packet: Packet from client that wants to join :type packet: paps.si.app.message.APPJoinMessage :param ip: Client ip address :type ip: unicode :param port: Client port :type port: int :rtype: None """ |
self.debug("()")
device_id = packet.header.device_id
key = u"{}:{}".format(ip, port)
if device_id == Id.REQUEST:
device_id = self._new_device_id(key)
client = self._clients.get(device_id, {})
data = {}
if packet.payload:
try:
data = packet.payload
except:
data = {}
client['device_id'] = device_id
client['key'] = key
people = []
try:
for index, person_dict in enumerate(data['people']):
person = Person()
person.from_dict(person_dict)
person.id = u"{}.{}".format(device_id, person.id)
# To get original id -> id.split('.')[0]
people.append(person)
self.changer.on_person_new(people)
except:
self.exception("Failed to update people")
return
# Original ids (without device id)
client['people'] = people
# Add config to client data?
client_dict = dict(client)
del client_dict['people']
self._send_packet(ip, port, APPConfigMessage(payload=client_dict))
self._clients[device_id] = client
self._key2deviceId[key] = device_id |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_unjoin_packet(self, packet, ip, port):
""" React to unjoin packet - remove a client from this server :param packet: Packet from client that wants to join :type packet: paps.si.app.message.APPJoinMessage :param ip: Client ip address :type ip: unicode :param port: Client port :type port: int :rtype: None """ |
self.debug("()")
device_id = packet.header.device_id
if device_id <= Id.SERVER:
self.error("ProtocolViolation: Invalid device id")
return
client = self._clients.get(device_id)
if not client:
self.error("ProtocolViolation: Client is not registered")
return
key = u"{}:{}".format(ip, port)
if client['key'] != key:
self.error(
u"ProtocolViolation: Client key ({}) has changed: {}".format(
client['key'], key
)
)
return
# Packet info seems ok
try:
self.changer.on_person_leave(client['people'])
except:
self.exception("Failed to remove people")
return
# Forget client?
del self._clients[device_id]
del self._key2deviceId[key]
del client |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _new_device_id(self, key):
""" Generate a new device id or return existing device id for key :param key: Key for device :type key: unicode :return: The device id :rtype: int """ |
device_id = Id.SERVER + 1
if key in self._key2deviceId:
return self._key2deviceId[key]
while device_id in self._clients:
device_id += 1
return device_id |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_multicast_socket(self):
""" Init multicast socket :rtype: None """ |
self.debug("()")
# Create a UDP socket
self._multicast_socket = socket.socket(
socket.AF_INET,
socket.SOCK_DGRAM
)
# Allow reuse of addresses
self._multicast_socket.setsockopt(
socket.SOL_SOCKET,
socket.SO_REUSEADDR,
1
)
# Set multicast interface to local_ip
self._multicast_socket.setsockopt(
socket.IPPROTO_IP,
socket.IP_MULTICAST_IF,
socket.inet_aton(self._multicast_ip)
)
# Set multicast time-to-live
# Should keep our multicast packets from escaping the local network
self._multicast_socket.setsockopt(
socket.IPPROTO_IP,
socket.IP_MULTICAST_TTL,
self._multicast_ttl
)
self._add_membership_multicast_socket()
# Bind socket
if platform.system().lower() == "darwin":
self._multicast_socket.bind(("0.0.0.0", self._multicast_bind_port))
else:
self._multicast_socket.bind(
(self._multicast_ip, self._multicast_bind_port)
)
self._listening.append(self._multicast_socket) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _shutdown_multicast_socket(self):
""" Shutdown multicast socket :rtype: None """ |
self.debug("()")
self._drop_membership_multicast_socket()
self._listening.remove(self._multicast_socket)
self._multicast_socket.close()
self._multicast_socket = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_membership_multicast_socket(self):
""" Make membership request to multicast :rtype: None """ |
self._membership_request = socket.inet_aton(self._multicast_group) \
+ socket.inet_aton(self._multicast_ip)
# Send add membership request to socket
# See http://www.tldp.org/HOWTO/Multicast-HOWTO-6.html
# for explanation of sockopts
self._multicast_socket.setsockopt(
socket.IPPROTO_IP,
socket.IP_ADD_MEMBERSHIP,
self._membership_request
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _drop_membership_multicast_socket(self):
""" Drop membership to multicast :rtype: None """ |
# Leave group
self._multicast_socket.setsockopt(
socket.IPPROTO_IP,
socket.IP_DROP_MEMBERSHIP,
self._membership_request
)
self._membership_request = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def evert(iterable: Iterable[Dict[str, Tuple]]) -> Iterable[Iterable[Dict[str, Any]]]:
'''Evert dictionaries with tuples.
Iterates over the list of dictionaries and everts them with their tuple
values. For example:
``[ { 'a': ( 1, 2, ), }, ]``
becomes
``[ ( { 'a': 1, }, ), ( { 'a', 2, }, ) ]``
The resulting iterable contains the same number of tuples as the
initial iterable had tuple elements. The number of dictionaries is the same
as the cartesian product of the initial iterable's tuple elements.
Parameters
----------
:``iterable``: list of dictionaries whose values are tuples
Return Value(s)
---------------
All combinations of the choices in the dictionaries.
'''
keys = list(itertools.chain.from_iterable([ _.keys() for _ in iterable ]))
for values in itertools.product(*[ list(*_.values()) for _ in iterable ]):
yield [ dict(( pair, )) for pair in zip(keys, values) ] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def extend(base: Dict[Any, Any], extension: Dict[Any, Any]) -> Dict[Any, Any]:
'''Extend base by updating with the extension.
**Arguments**
:``base``: dictionary to have keys updated or added
:``extension``: dictionary to update base with
**Return Value(s)**
Resulting dictionary from updating base with extension.
'''
_ = copy.deepcopy(base)
_.update(extension)
return _ |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def merge(base: Dict[Any, Any], extension: Dict[Any, Any]) -> Dict[Any, Any]:
'''Merge extension into base recursively.
**Argumetnts**
:``base``: dictionary to overlay values onto
:``extension``: dictionary to overlay with
**Return Value(s)**
Resulting dictionary from overlaying extension on base.
'''
_ = copy.deepcopy(base)
for key, value in extension.items():
if isinstance(value, Dict) and key in _:
_[key] = merge(_[key], value)
else:
_[key] = value
return _ |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def import_directory(module_basename: str, directory: str, sort_key = None) -> None:
'''Load all python modules in directory and directory's children.
Parameters
----------
:``module_basename``: module name prefix for loaded modules
:``directory``: directory to load python modules from
:``sort_key``: function to sort module names with before loading
'''
logger.info('loading submodules of %s', module_basename)
logger.info('loading modules from %s', directory)
filenames = itertools.chain(*[ [ os.path.join(_[0], filename) for filename in _[2] ] for _ in os.walk(directory) if len(_[2]) ])
modulenames = _filenames_to_modulenames(filenames, module_basename, directory)
for modulename in sorted(modulenames, key = sort_key):
try:
importlib.import_module(modulename)
except ImportError:
logger.warning('failed loading %s', modulename)
logger.exception('module loading failure')
else:
logger.info('successfully loaded %s', modulename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _filenames_to_modulenames(filenames: Iterable[str], modulename_prefix: str, filename_prefix: str = '') -> Iterable[str]:
'''Convert given filenames to module names.
Any filename that does not have a corresponding module name will be dropped
from the result (i.e. __init__.py).
Parameters
----------
:``filename_prefix``: a prefix to drop from all filenames (typically a
common directory); defaults to ''
:``filenames``: the filenames to transform into module names
:``modulename_prefix``: a prefix to add to all module names
Return Value(s)
---------------
A list of modulenames corresponding to all filenames (for legal module names).
'''
modulenames = [] # type: Iterable[str]
for filename in filenames:
if not filename.endswith('.py'):
continue
name = filename
name = name.replace(filename_prefix, '')
name = name.replace('__init__.py', '')
name = name.replace('.py', '')
name = name.replace('/', '.')
name = name.strip('.')
if not len(name):
continue
if not modulename_prefix.endswith('.'):
modulename_prefix += '.'
name = modulename_prefix + name
known_symbols = set()
name = '.'.join([ _ for _ in name.split('.') if _ not in known_symbols and not known_symbols.add(_) ])
if len(name):
modulenames.append(name)
return modulenames |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_any_event(self, event):
"""Called whenever a FS event occurs.""" |
self.updated = True
if self._changed:
self._changed() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def log(prefix = ''):
'''Add start and stop logging messages to the function.
Parameters
----------
:``prefix``: a prefix for the function name (optional)
'''
function = None
if inspect.isfunction(prefix):
prefix, function = '', prefix
def _(function):
@functools.wraps(function, assigned = functools.WRAPPER_ASSIGNMENTS + ( '__file__', ))
def wrapper(*args, **kwargs):
name, my_args = function.__name__, args
if inspect.ismethod(function):
name = function.__self__.__class__.__name__ + '.' + function.__name__
elif len(args):
members = dict(inspect.getmembers(args[0], predicate = lambda _: inspect.ismethod(_) and _.__name__ == function.__name__))
logger.debug('members.keys(): %s', members.keys())
if len(members):
name, my_args = args[0].__class__.__name__ + '.' + function.__name__, args[1:]
format_args = (
prefix + name,
', '.join(list(map(str, my_args)) + [ ' = '.join(map(str, item)) for item in kwargs.items() ]),
)
logger.info('STARTING: %s(%s)', *format_args)
try:
return function(*args, **kwargs)
except:
logger.exception('EXCEPTION: %s(%s)', *format_args)
raise
finally:
logger.info('STOPPING: %s(%s)', *format_args)
return wrapper
if function is not None:
_ = _(function)
return _ |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spec(self):
"""Return a dict with values that can be fed directly into SelectiveRowGenerator""" |
return dict(
headers=self.header_lines,
start=self.start_line,
comments=self.comment_lines,
end=self.end_line
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def picture(self, row):
"""Create a simplified character representation of the data row, which can be pattern matched with a regex """ |
template = '_Xn'
types = (type(None), binary_type, int)
def guess_type(v):
try:
v = text_type(v).strip()
except ValueError:
v = binary_type(v).strip()
#v = v.decode('ascii', 'replace').strip()
if not bool(v):
return type(None)
for t in (float, int, binary_type, text_type):
try:
return type(t(v))
except:
pass
def p(e):
tm = t = None
try:
t = guess_type(e)
tm = self.type_map.get(t, t)
return template[types.index(tm)]
except ValueError as e:
raise ValueError("Type '{}'/'{}' not in the types list: {} ({})".format(t, tm, types, e))
return ''.join(p(e) for e in row) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coalesce_headers(cls, header_lines):
"""Collects headers that are spread across multiple lines into a single row""" |
header_lines = [list(hl) for hl in header_lines if bool(hl)]
if len(header_lines) == 0:
return []
if len(header_lines) == 1:
return header_lines[0]
# If there are gaps in the values of a line, copy them forward, so there
# is some value in every position
for hl in header_lines:
last = None
for i in range(len(hl)):
hli = text_type(hl[i])
if not hli.strip():
hl[i] = last
else:
last = hli
headers = [' '.join(text_type(col_val).strip() if col_val else '' for col_val in col_set)
for col_set in zip(*header_lines)]
headers = [slugify(h.strip()) for h in headers]
return headers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map_recursive(function, iterable):
""" Apply function recursively to every item or value of iterable and returns a new iterable object with the results. """ |
if isiterable(iterable):
dataOut = iterable.__class__()
for i in iterable:
if isinstance(dataOut, dict):
dataOut[i] = map_recursive(function, iterable[i])
else:
# convert to list and append
if not isinstance(dataOut, list):
dataOut = list(dataOut)
dataOut.append(map_recursive(function, i))
return dataOut
return function(iterable) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_card(self, index=-1, cache=True, remove=True):
""" Retrieve a card any number of cards from the top. Returns a ``Card`` object loaded from a library if one is specified otherwise just it will simply return its code. If `index` is not set then the top card will be retrieved. If cache is set to True (the default) it will tell the library to cache the returned card for faster look-ups in the future. If remove is true then the card will be removed from the deck before returning it. """ |
if len(self.cards) < index:
return None
retriever = self.cards.pop if remove else self.cards.__getitem__
code = retriever(index)
if self.library:
return self.library.load_card(code, cache)
else:
return code |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def top_cards(self, number=1, cache=True, remove=True):
""" Retrieve the top number of cards as ``Librarian.Card`` objects in a list in order of top to bottom most card. Uses the decks ``.get_card`` and passes along the cache and remove arguments. """ |
getter = partial(self.get_card(cache=cache, remove=remove))
return [getter(index=i) for i in range(number)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_top_cards(self, other, number=1):
""" Move the top `number` of cards to the top of some `other` deck. By default only one card will be moved if `number` is not specified. """ |
other.cards.append(reversed(self.cards[-number:])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def contians_attribute(self, attribute):
""" Returns how many cards in the deck have the specified attribute. This method requires a library to be stored in the deck instance and will return `None` if there is no library. """ |
if self.library is None:
return 0
load = self.library.load_card
matches = 0
for code in self.cards:
card = load(code)
if card.has_attribute(attribute):
matches += 1
return matches |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def contains_info(self, key, value):
""" Returns how many cards in the deck have the specified value under the specified key in their info data. This method requires a library to be stored in the deck instance and will return `None` if there is no library. """ |
if self.library is None:
return 0
load = self.library.load_card
matches = 0
for code in self.cards:
card = load(code)
if card.get_info(key) == value:
matches += 1
return matches |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self):
"""Connect to MQTT server and wait for server to acknowledge""" |
if not self.connect_attempted:
self.connect_attempted = True
self.client.connect(self.host, port=self.port)
self.client.loop_start()
while not self.connected:
log.info('waiting for MQTT connection...')
time.sleep(1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish(self, topic, message):
"""Publish an MQTT message to a topic.""" |
self.connect()
log.info('publish {}'.format(message))
self.client.publish(topic, message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_abilities():
"""Visit Bulbapedia and pull names and descriptions from the table, 'list of Abilities.' Save as JSON.""" |
page = requests.get('http://bulbapedia.bulbagarden.net/wiki/Ability')
soup = bs4.BeautifulSoup(page.text)
table = soup.find("table", {"class": "sortable"})
tablerows = [tr for tr in table.children if tr != '\n'][1:]
abilities = {}
for tr in tablerows:
cells = tr.find_all('td')
ability_name = cells[1].get_text().strip().replace(' ', '-').lower()
ability_desc = unicode(cells[2].get_text().strip())
abilities[ability_name] = ability_desc
srcpath = path.dirname(__file__)
with io.open(path.join(srcpath, 'abilities.json'), 'w', encoding='utf-8') as f:
f.write(json.dumps(abilities, ensure_ascii=False)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_from_techshop_ws(tws_url):
"""Scrapes data from techshop.ws.""" |
r = requests.get(tws_url)
if r.status_code == 200:
data = BeautifulSoup(r.text, "lxml")
else:
data = "There was an error while accessing data on techshop.ws."
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_client_id(self, id):
"""Returns True if we have a client with a certain integer identifier""" |
return self.query(Client).filter(Client.id==id).count() != 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def client(self, id):
"""Returns the client object in the database given a certain id. Raises an error if that does not exist.""" |
return self.query(Client).filter(Client.id==id).one() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def protocol_names(self):
"""Returns all registered protocol names""" |
l = self.protocols()
retval = [str(k.name) for k in l]
return retval |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_protocol(self, name):
"""Tells if a certain protocol is available""" |
return self.query(Protocol).filter(Protocol.name==name).count() != 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def protocol(self, name):
"""Returns the protocol object in the database given a certain name. Raises an error if that does not exist.""" |
return self.query(Protocol).filter(Protocol.name==name).one() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup(__pkg: ModuleType) -> Tuple[Callable[[str], str], Callable[[str, str, int], str]]: """Configure ``gettext`` for given package. Args: __pkg: Package to use as location for :program:`gettext` files Returns: :program:`gettext` functions for singular and plural translations """ |
package_locale = path.join(path.dirname(__pkg.__file__), 'locale')
gettext.install(__pkg.__name__, package_locale)
return gettext.gettext, gettext.ngettext |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(sub_command, quiet=False, no_edit=False, no_verify=False):
"""Run a git command Prefix that sub_command with "git " then run the command in shell If quiet if True then do not log results If no_edit is True then prefix the git command with "GIT_EDITOR=true" (which does not wait on user's editor) If the command gives a non-zero status, raise a GitError exception """ |
if _working_dirs[0] != '.':
git_command = 'git -C "%s"' % _working_dirs[0]
else:
git_command = 'git'
edit = 'GIT_EDITOR=true' if no_edit else ''
verify = 'GIT_SSL_NO_VERIFY=true' if no_verify else ''
command = '%s %s %s %s' % (verify, edit, git_command, sub_command)
if not quiet:
logger.info('$ %s', command)
status_, output = getstatusoutput(command)
if status_:
if quiet:
logger.info('$ %s', command)
logger.error('\n%s', output)
if 'unknown revision' in output:
raise UnknownRevision(command, status_, output)
elif 'remote ref does not exist' in output:
raise NoRemoteRef(command, status_, output)
elif 'no such commit' in output:
raise NoSuchCommit(command, status_, output)
elif 'reference already exists' in output:
raise ExistingReference(command, status_, output)
elif re.search('Resolved|CONFLICT|Recorded preimage', output):
raise ResolveError(command, status_, output)
elif re.search('branch named.*already exists', output):
raise ExistingBranch(command, status, output)
raise GitError(command, status_, output)
elif output and not quiet:
logger.info('\n%s', output)
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def branches(remotes=False):
"""Return a list of all local branches in the repo If remotes is true then also include remote branches Note: the normal '*' indicator for current branch is removed this method just gives a list of branch names Use branch() method to determine the current branch """ |
stdout = branch('--list %s' % (remotes and '-a' or ''), quiet=True)
return [_.lstrip('*').strip() for _ in stdout.splitlines()] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def branches_containing(commit):
"""Return a list of branches conatining that commit""" |
lines = run('branch --contains %s' % commit).splitlines()
return [l.lstrip('* ') for l in lines] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conflicted(path_to_file):
"""Whether there are any conflict markers in that file""" |
for line in open(path_to_file, 'r'):
for marker in '>="<':
if line.startswith(marker * 8):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def config(key, value, local=True):
"""Set that config key to that value Unless local is set to False: only change local config """ |
option = local and '--local' or ''
run('config %s "%s" "%s"' % (option, key, value)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clone(url, path=None, remove=True):
"""Clone a local repo from that URL to that path If path is not given, then use the git default: same as repo name If path is given and remove is True then the path is removed before cloning Because this is run from a script it is assumed that user should be Admin so set config user values for the GitLab Admin """ |
clean = True
if path and os.path.isdir(path):
if not remove:
clean = False
else:
shutil.rmtree(path)
if clean:
stdout = run('clone %s %s' % (url, path or ''))
into = stdout.splitlines()[0].split("'")[1]
path_to_clone = os.path.realpath(into)
else:
path_to_clone = path
old_dir = _working_dirs[0]
_working_dirs[0] = path_to_clone
config('user.name', 'Release Script')
config('user.email', 'gitlab@wwts.com')
_working_dirs[0] = old_dir
return path_to_clone |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def needs_abort():
"""A command to abort an operation in progress For example a merge, cherry-pick or rebase If one of these operations has left the repo conflicted then give a command to abandon the operation """ |
for line in status().splitlines():
if '--abort' in line:
for part in line.split('"'):
if '--abort' in part:
return part
elif 'All conflicts fixed but you are still merging' in line:
return 'git merge --abort'
elif 'You have unmerged paths.' in line:
return 'git merge --abort'
elif 'all conflicts fixed: run "git rebase --continue"' in line:
return 'git rebase --abort'
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_branches(branch1, branch2):
"""Runs git show-branch between the 2 branches, parse result""" |
def find_column(string):
"""Find first non space line in the prefix"""
result = 0
for c in string:
if c == ' ':
result += 1
return result
def parse_show_line(string):
"""Parse a typical line from git show-branch
>>> parse_show_line('+ [master^2] TOOLS-122 Add bashrc')
'+ ', 'master^2', 'TOOLS-122 Add bashrc'
"""
regexp = re.compile('(.*)\[(.*)] (.*)')
match = regexp.match(string)
if not match:
return None
prefix, commit, comment = match.groups()
return find_column(prefix), commit, comment
log = run('show-branch --sha1-name "%s" "%s"' % (branch1, branch2))
lines = iter(log.splitlines())
line = lines.next()
branches = {}
while line != '--':
column, branch, comment = parse_show_line(line)
branches[column] = [branch]
line = lines.next()
line = lines.next()
for line in lines:
column, commit, comment = parse_show_line(line)
branches[column].append((commit, comment))
return branches |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def checkout(branch, quiet=False, as_path=False):
"""Check out that branch Defaults to a quiet checkout, giving no stdout if stdout it wanted, call with quiet = False Defaults to checking out branches If as_path is true, then treat "branch" like a file, i.e. $ git checkout -- branch All errors will pass silently, just returning False except any messages about "you need to resolve your current index" These indicate that the repository is not in a normal state and action by a user is usually needed to resolve that So the exception is allowed to rise probably stopping the script """ |
try:
if as_path:
branch = '-- %s' % branch
run('checkout %s %s' % (quiet and '-q' or '', branch))
return True
except GitError as e:
if 'need to resolve your current index' in e.output:
raise
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def same_diffs(commit1, commit2):
"""Whether those 2 commits have the same change Run "git range-diff" against 2 commit ranges: 1. parent of commit1 to commit1 1. parent of commit2 to commit2 If the two produce the same diff then git will only show header lines Otherwise there will be lines after the header lines (and those lines will show the difference) """ |
def range_one(commit):
"""A git commit "range" to include only one commit"""
return '%s^..%s' % (commit, commit)
output = run('range-diff %s %s' % (range_one(commit1), range_one(commit2)))
lines = output.splitlines()
for i, line in enumerate(lines, 1):
if not line.startswith('%s: ' % i):
break
return not lines[i:] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def renew_local_branch(branch, start_point, remote=False):
"""Make a new local branch from that start_point start_point is a git "commit-ish", e.g branch, tag, commit If a local branch already exists it is removed If remote is true then push the new branch to origin """ |
if branch in branches():
checkout(start_point)
delete(branch, force=True, remote=remote)
result = new_local_branch(branch, start_point)
if remote:
publish(branch)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish(branch, full_force=False):
"""Publish that branch, i.e. push it to origin""" |
checkout(branch)
try:
push('--force --set-upstream origin', branch)
except ExistingReference:
if full_force:
push('origin --delete', branch)
push('--force --set-upstream origin', branch) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commit(message, add=False, quiet=False):
"""Commit with that message and return the SHA1 of the commit If add is truish then "$ git add ." first """ |
if add:
run('add .')
try:
stdout = run('commit -m %r' % str(message), quiet=quiet)
except GitError as e:
s = str(e)
if 'nothing to commit' in s or 'no changes added to commit' in s:
raise EmptyCommit(*e.inits())
raise
return re.split('[ \]]', stdout.splitlines()[0])[1] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pull(rebase=True, refspec=None):
"""Pull refspec from remote repository to local If refspec is left as None, then pull current branch The '--rebase' option is used unless rebase is set to false """ |
options = rebase and '--rebase' or ''
output = run('pull %s %s' % (options, refspec or ''))
return not re.search('up.to.date', output) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rebase(upstream, branch=None):
"""Rebase branch onto upstream If branch is empty, use current branch """ |
rebase_branch = branch and branch or current_branch()
with git_continuer(run, 'rebase --continue', no_edit=True):
stdout = run('rebase %s %s' % (upstream, rebase_branch))
return 'Applying' in stdout |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def tempfile_writer(target):
'''write cache data to a temporary location. when writing is
complete, rename the file to the actual location. delete
the temporary file on any error'''
tmp = target.parent / ('_%s' % target.name)
try:
with tmp.open('wb') as fd:
yield fd
except:
tmp.unlink()
raise
LOG.debug('rename %s -> %s', tmp, target)
tmp.rename(target) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def xform_key(self, key):
'''we transform cache keys by taking their sha1 hash so that
we don't need to worry about cache keys containing invalid
characters'''
newkey = hashlib.sha1(key.encode('utf-8'))
return newkey.hexdigest() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def invalidate(self, key):
'''Clear an item from the cache'''
path = self.path(self.xform_key(key))
try:
LOG.debug('invalidate %s (%s)', key, path)
path.unlink()
except OSError:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def invalidate_all(self):
'''Clear all items from the cache'''
LOG.debug('clearing cache')
appcache = str(self.get_app_cache())
for dirpath, dirnames, filenames in os.walk(appcache):
for name in filenames:
try:
pathlib.Path(dirpath, name).unlink()
except OSError:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def store_iter(self, key, content):
'''stores content in the cache by iterating over
content'''
cachekey = self.xform_key(key)
path = self.path(cachekey)
with tempfile_writer(path) as fd:
for data in content:
LOG.debug('writing chunk of %d bytes for %s',
len(data), key)
fd.write(data)
LOG.debug('%s stored in cache', key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def store_lines(self, key, content):
'''like store_iter, but appends a newline to each chunk of
content'''
return self.store_iter(
key,
(data + '\n'.encode('utf-8') for data in content)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def load_fd(self, key, noexpire=False):
'''Look up an item in the cache and return an open file
descriptor for the object. It is the caller's responsibility
to close the file descriptor.'''
cachekey = self.xform_key(key)
path = self.path(cachekey)
try:
stat = path.stat()
if not noexpire and stat.st_mtime < time.time() - self.lifetime:
LOG.debug('%s has expired', key)
path.unlink()
raise KeyError(key)
LOG.debug('%s found in cache', key)
return path.open('rb')
except OSError:
LOG.debug('%s not found in cache', key)
raise KeyError(key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def load_lines(self, key, noexpire=None):
'''Look up up an item in the cache and return a line iterator.
The underlying file will be closed once all lines have been
consumed.'''
return line_iterator(self.load_fd(key, noexpire=noexpire)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def load_iter(self, key, chunksize=None, noexpire=None):
'''Lookup an item in the cache and return an iterator
that reads chunksize bytes of data at a time. The underlying
file will be closed when all data has been read'''
return chunk_iterator(self.load_fd(key, noexpire=noexpire),
chunksize=chunksize) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def load(self, key, noexpire=None):
'''Lookup an item in the cache and return the raw content of
the file as a string.'''
with self.load_fd(key, noexpire=noexpire) as fd:
return fd.read() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_bool_param(params, name, value):
""" Set a boolean parameter if applicable. :param dict params: A dict containing API call parameters. :param str name: The name of the parameter to set. :param bool value: The value of the parameter. If ``None``, the field will not be set. If ``True`` or ``False``, the relevant field in ``params`` will be set to ``'true'`` or ``'false'``. Any other value will raise a `ValueError`. :returns: ``None`` """ |
if value is None:
return
if value is True:
params[name] = 'true'
elif value is False:
params[name] = 'false'
else:
raise ValueError("Parameter '%s' must be boolean or None, got %r." % (
name, value)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_str_param(params, name, value):
""" Set a string parameter if applicable. :param dict params: A dict containing API call parameters. :param str name: The name of the parameter to set. :param value: The value of the parameter. If ``None``, the field will not be set. If an instance of ``str``, the relevant field will be set. If an instance of ``unicode``, the relevant field will be set to the UTF-8 encoding. Any other value will raise a `ValueError`. :returns: ``None`` """ |
if value is None:
return
if isinstance(value, str):
params[name] = value
elif isinstance(value, unicode):
params[name] = value.encode('utf-8')
else:
raise ValueError("Parameter '%s' must be a string or None, got %r." % (
name, value)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_float_param(params, name, value, min=None, max=None):
""" Set a float parameter if applicable. :param dict params: A dict containing API call parameters. :param str name: The name of the parameter to set. :param float value: The value of the parameter. If ``None``, the field will not be set. If an instance of a numeric type or a string that can be turned into a ``float``, the relevant field will be set. Any other value will raise a `ValueError`. :param float min: If provided, values less than this will raise ``ValueError``. :param float max: If provided, values greater than this will raise ``ValueError``. :returns: ``None`` """ |
if value is None:
return
try:
value = float(str(value))
except:
raise ValueError(
"Parameter '%s' must be numeric (or a numeric string) or None,"
" got %r." % (name, value))
if min is not None and value < min:
raise ValueError(
"Parameter '%s' must not be less than %r, got %r." % (
name, min, value))
if max is not None and value > max:
raise ValueError(
"Parameter '%s' must not be greater than %r, got %r." % (
name, min, value))
params[name] = str(value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_int_param(params, name, value, min=None, max=None):
""" Set a int parameter if applicable. :param dict params: A dict containing API call parameters. :param str name: The name of the parameter to set. :param int value: The value of the parameter. If ``None``, the field will not be set. If an instance of a numeric type or a string that can be turned into a ``int``, the relevant field will be set. Any other value will raise a `ValueError`. :param int min: If provided, values less than this will raise ``ValueError``. :param int max: If provided, values greater than this will raise ``ValueError``. :returns: ``None`` """ |
if value is None:
return
try:
value = int(str(value))
except:
raise ValueError(
"Parameter '%s' must be an integer (or a string representation of"
" an integer) or None, got %r." % (name, value))
if min is not None and value < min:
raise ValueError(
"Parameter '%s' must not be less than %r, got %r." % (
name, min, value))
if max is not None and value > max:
raise ValueError(
"Parameter '%s' must not be greater than %r, got %r." % (
name, min, value))
params[name] = str(value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_list_param(params, name, value, min_len=None, max_len=None):
""" Set a list parameter if applicable. :param dict params: A dict containing API call parameters. :param str name: The name of the parameter to set. :param list value: The value of the parameter. If ``None``, the field will not be set. If an instance of ``set``, ``tuple``, or type that can be turned into a ``list``, the relevant field will be set. If ``dict``, will raise ``ValueError``. Any other value will raise a ``ValueError``. :param int min_len: If provided, values shorter than this will raise ``ValueError``. :param int max_len: If provided, values longer than this will raise ``ValueError``. """ |
if value is None:
return
if type(value) is dict:
raise ValueError(
"Parameter '%s' cannot be a dict." % name)
try:
value = list(value)
except:
raise ValueError(
"Parameter '%s' must be a list (or a type that can be turned into"
"a list) or None, got %r." % (name, value))
if min_len is not None and len(value) < min_len:
raise ValueError(
"Parameter '%s' must not be shorter than %r, got %r." % (
name, min_len, value))
if max_len is not None and len(value) > max_len:
raise ValueError(
"Parameter '%s' must not be longer than %r, got %r." % (
name, max_len, value))
list_str = ''
for item in value:
list_str += '%s,' % item
set_str_param(params, name, list_str) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def statuses_user_timeline(self, user_id=None, screen_name=None, since_id=None, count=None, max_id=None, trim_user=None, exclude_replies=None, contributor_details=None, include_rts=None):
""" Returns a list of the most recent tweets posted by the specified user. https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline Either ``user_id`` or ``screen_name`` must be provided. :param str user_id: The ID of the user to return tweets for. :param str screen_name: The screen name of the user to return tweets for. :param str since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. Tweets newer than this may not be returned due to certain API limits. :param int count: Specifies the number of tweets to try and retrieve, up to a maximum of 200. :param str max_id: Returns results with an ID less than (that is, older than) or equal to the specified ID. :param bool trim_user: When set to ``True``, the tweet's user object includes only the status author's numerical ID. :param bool exclude_replies: When set to ``True``, replies will not appear in the timeline. :param bool contributor_details: This parameter enhances the contributors element of the status response to include the screen_name of the contributor. By default only the user_id of the contributor is included. :param bool include_rts: When set to ``False``, retweets will not appear in the timeline. :returns: A list of tweet dicts. """ |
params = {}
set_str_param(params, 'user_id', user_id)
set_str_param(params, 'screen_name', screen_name)
set_str_param(params, 'since_id', since_id)
set_int_param(params, 'count', count)
set_str_param(params, 'max_id', max_id)
set_bool_param(params, 'trim_user', trim_user)
set_bool_param(params, 'exclude_replies', exclude_replies)
set_bool_param(params, 'contributor_details', contributor_details)
set_bool_param(params, 'include_rts', include_rts)
return self._get_api('statuses/user_timeline.json', params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def statuses_home_timeline(self, count=None, since_id=None, max_id=None, trim_user=None, exclude_replies=None, contributor_details=None, include_entities=None):
""" Returns a collection of the most recent Tweets and retweets posted by the authenticating user and the users they follow. https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline :param int count: Specifies the number of tweets to try and retrieve, up to a maximum of 200. :param str since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. Tweets newer than this may not be returned due to certain API limits. :param str max_id: Returns results with an ID less than (that is, older than) or equal to the specified ID. :param bool trim_user: When set to ``True``, the tweet's user object includes only the status author's numerical ID. :param bool exclude_replies: When set to ``True``, replies will not appear in the timeline. :param bool contributor_details: This parameter enhances the contributors element of the status response to include the screen_name of the contributor. By default only the user_id of the contributor is included. :param bool include_entities: When set to ``False``, the ``entities`` node will not be included. :returns: A list of tweet dicts. """ |
params = {}
set_int_param(params, 'count', count)
set_str_param(params, 'since_id', since_id)
set_str_param(params, 'max_id', max_id)
set_bool_param(params, 'trim_user', trim_user)
set_bool_param(params, 'exclude_replies', exclude_replies)
set_bool_param(params, 'contributor_details', contributor_details)
set_bool_param(params, 'include_entities', include_entities)
return self._get_api('statuses/home_timeline.json', params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def statuses_retweets(self, id, count=None, trim_user=None):
""" Returns a list of the most recent retweets of the Tweet specified by the id parameter. https://dev.twitter.com/docs/api/1.1/get/statuses/retweets/%3Aid :param str id: (*required*) The numerical ID of the desired tweet. :param int count: The maximum number of retweets to return. (Max 100) :param bool trim_user: When set to ``True``, the tweet's user object includes only the status author's numerical ID. :returns: A tweet dict. """ |
params = {'id': id}
set_int_param(params, 'count', count)
set_bool_param(params, 'trim_user', trim_user)
return self._get_api('statuses/retweets.json', params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def statuses_show(self, id, trim_user=None, include_my_retweet=None, include_entities=None):
""" Returns a single Tweet, specified by the id parameter. https://dev.twitter.com/docs/api/1.1/get/statuses/show/%3Aid :param str id: (*required*) The numerical ID of the desired tweet. :param bool trim_user: When set to ``True``, the tweet's user object includes only the status author's numerical ID. :param bool include_my_retweet: When set to ``True``, any Tweet returned that has been retweeted by the authenticating user will include an additional ``current_user_retweet`` node, containing the ID of the source status for the retweet. :param bool include_entities: When set to ``False``, the ``entities`` node will not be included. :returns: A tweet dict. """ |
params = {'id': id}
set_bool_param(params, 'trim_user', trim_user)
set_bool_param(params, 'include_my_retweet', include_my_retweet)
set_bool_param(params, 'include_entities', include_entities)
return self._get_api('statuses/show.json', params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def statuses_destroy(self, id, trim_user=None):
""" Destroys the status specified by the ID parameter. https://dev.twitter.com/docs/api/1.1/post/statuses/destroy/%3Aid :param str id: (*required*) The numerical ID of the desired tweet. :param bool trim_user: When set to ``True``, the return value's user object includes only the status author's numerical ID. :returns: A tweet dict containing the destroyed tweet. """ |
params = {'id': id}
set_bool_param(params, 'trim_user', trim_user)
return self._post_api('statuses/destroy.json', params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def statuses_update(self, status, in_reply_to_status_id=None, lat=None, long=None, place_id=None, display_coordinates=None, trim_user=None, media_ids=None):
""" Posts a tweet. https://dev.twitter.com/docs/api/1.1/post/statuses/update :param str status: (*required*) The text of your tweet, typically up to 140 characters. URL encode as necessary. t.co link wrapping may affect character counts. There are some special commands in this field to be aware of. For instance, preceding a message with "D " or "M " and following it with a screen name can create a direct message to that user if the relationship allows for it. :param str in_reply_to_status_id: The ID of an existing status that the update is in reply to. Note: This parameter will be ignored unless the author of the tweet this parameter references is mentioned within the status text. Therefore, you must include @username, where username is the author of the referenced tweet, within ``status``. :param float lat: The latitude of the location this tweet refers to. This parameter will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding long parameter. :param float long: The longitude of the location this tweet refers to. The valid ranges for longitude is -180.0 to +180.0 (East is positive) inclusive. This parameter will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding lat parameter. :param str place_id: A place in the world. These IDs can be retrieved from GET geo/reverse_geocode. (TODO: Reference method when it exists.) :param bool display_coordinates: Whether or not to put a pin on the exact coordinates a tweet has been sent from. :param bool trim_user: When set to ``True``, the return value's user object includes only the status author's numerical ID. :param list media_ids: A list of images previously uploaded to Twitter (referenced by their ``media_id``) that are to be embedded in the tweet. Maximum of four images. :returns: A tweet dict containing the posted tweet. """ |
params = {}
set_str_param(params, 'status', status)
set_str_param(params, 'in_reply_to_status_id', in_reply_to_status_id)
set_float_param(params, 'lat', lat, min=-90, max=90)
set_float_param(params, 'long', long, min=-180, max=180)
set_str_param(params, 'place_id', place_id)
set_bool_param(params, 'display_coordinates', display_coordinates)
set_bool_param(params, 'trim_user', trim_user)
set_list_param(params, 'media_ids', media_ids, max_len=4)
return self._post_api('statuses/update.json', params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def statuses_retweet(self, id, trim_user=None):
""" Retweets the status specified by the ID parameter. https://dev.twitter.com/docs/api/1.1/post/statuses/retweet/%3Aid :param str id: (*required*) The numerical ID of the desired tweet. :param bool trim_user: When set to ``True``, the return value's user object includes only the status author's numerical ID. :returns: A tweet dict containing the retweet. (Contains the retweeted tweet in the ``retweeted_status`` field.) """ |
params = {'id': id}
set_bool_param(params, 'trim_user', trim_user)
return self._post_api('statuses/retweet.json', params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def media_upload(self, media, additional_owners=None):
""" Uploads an image to Twitter for later embedding in tweets. https://dev.twitter.com/rest/reference/post/media/upload :param file media: The image file to upload (see the API docs for limitations). :param list additional_owners: A list of Twitter users that will be able to access the uploaded file and embed it in their tweets (maximum 100 users). :returns: A dict containing information about the file uploaded. (Contains the media id needed to embed the image in the ``media_id`` field). """ |
params = {}
set_list_param(
params, 'additional_owners', additional_owners, max_len=100)
return self._upload_media('media/upload.json', media, params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stream_filter(self, delegate, follow=None, track=None, locations=None, stall_warnings=None):
""" Streams public messages filtered by various parameters. https://dev.twitter.com/docs/api/1.1/post/statuses/filter At least one of ``follow``, ``track``, or ``locations`` must be provided. See the API documentation linked above for details on these parameters and the various limits on this API. :param delegate: A delegate function that will be called for each message in the stream and will be passed the message dict as the only parameter. The message dicts passed to this function may represent any message type and the delegate is responsible for any dispatch that may be required. (:mod:`txtwitter.messagetools` may be helpful here.) :param list follow: A list of user IDs, indicating the users to return statuses for in the stream. :param list track: List of keywords to track. :param list locations: List of location bounding boxes to track. XXX: Currently unsupported. :param bool stall_warnings: Specifies whether stall warnings should be delivered. :returns: An unstarted :class:`TwitterStreamService`. """ |
params = {}
if follow is not None:
params['follow'] = ','.join(follow)
if track is not None:
params['track'] = ','.join(track)
if locations is not None:
raise NotImplementedError(
"The `locations` parameter is not yet supported.")
set_bool_param(params, 'stall_warnings', stall_warnings)
svc = TwitterStreamService(
lambda: self._post_stream('statuses/filter.json', params),
delegate)
return svc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def userstream_user(self, delegate, stall_warnings=None, with_='followings', replies=None):
""" Streams messages for a single user. https://dev.twitter.com/docs/api/1.1/get/user The ``stringify_friend_ids`` parameter is always set to ``'true'`` for consistency with the use of string identifiers elsewhere. :param delegate: A delegate function that will be called for each message in the stream and will be passed the message dict as the only parameter. The message dicts passed to this function may represent any message type and the delegate is responsible for any dispatch that may be required. (:mod:`txtwitter.messagetools` may be helpful here.) :param bool stall_warnings: Specifies whether stall warnings should be delivered. :param str with_: If ``'followings'`` (the default), the stream will include messages from both the authenticated user and the authenticated user's followers. If ``'user'``, the stream will only include messages from (or mentioning) the autheticated user. All other values are invalid. (The underscore appended to the parameter name is to avoid conflicting with Python's ``with`` keyword.) :param str replies: If set to ``'all'``, replies to tweets will be included even if the authenticated user does not follow both parties. :returns: An unstarted :class:`TwitterStreamService`. """ |
params = {'stringify_friend_ids': 'true'}
set_bool_param(params, 'stall_warnings', stall_warnings)
set_str_param(params, 'with', with_)
set_str_param(params, 'replies', replies)
svc = TwitterStreamService(
lambda: self._get_userstream('user.json', params),
delegate)
return svc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def direct_messages(self, since_id=None, max_id=None, count=None, include_entities=None, skip_status=None):
""" Gets the 20 most recent direct messages received by the authenticating user. https://dev.twitter.com/docs/api/1.1/get/direct_messages :param str since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. :params str max_id: Returns results with an ID less than (that is, older than) or equal to the specified ID. :param int count: Specifies the number of direct messages to try and retrieve, up to a maximum of ``200``. The value of count is best thought of as a limit to the number of Tweets to return because suspended or deleted content is removed after the count has been applied. :param bool include_entities: The entities node will not be included when set to ``False``. :param bool skip_status: When set to ``True``, statuses will not be included in the returned user objects. :returns: A list of direct message dicts. """ |
params = {}
set_str_param(params, 'since_id', since_id)
set_str_param(params, 'max_id', max_id)
set_int_param(params, 'count', count)
set_bool_param(params, 'include_entities', include_entities)
set_bool_param(params, 'skip_status', skip_status)
return self._get_api('direct_messages.json', params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def direct_messages_sent(self, since_id=None, max_id=None, count=None, include_entities=None, page=None):
""" Gets the 20 most recent direct messages sent by the authenticating user. https://dev.twitter.com/docs/api/1.1/get/direct_messages/sent :param str since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. :params str max_id: Returns results with an ID less than (that is, older than) or equal to the specified ID. :param int count: Returns results with an ID less than (that is, older than) or equal to the specified ID. :param int page: Specifies the page of results to retrieve. :param bool include_entities: The entities node will not be included when set to ``False``. :returns: A list of direct message dicts. """ |
params = {}
set_str_param(params, 'since_id', since_id)
set_str_param(params, 'max_id', max_id)
set_int_param(params, 'count', count)
set_int_param(params, 'page', page)
set_bool_param(params, 'include_entities', include_entities)
return self._get_api('direct_messages/sent.json', params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def direct_messages_show(self, id):
""" Gets the direct message with the given id. https://dev.twitter.com/docs/api/1.1/get/direct_messages/show :param str id: (*required*) The ID of the direct message. :returns: A direct message dict. """ |
params = {}
set_str_param(params, 'id', id)
d = self._get_api('direct_messages/show.json', params)
d.addCallback(lambda dms: dms[0])
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def direct_messages_destroy(self, id, include_entities=None):
""" Destroys the direct message with the given id. https://dev.twitter.com/docs/api/1.1/post/direct_messages/destroy :param str id: (*required*) The ID of the direct message. :param bool include_entities: The entities node will not be included when set to ``False``. :returns: A direct message dict containing the destroyed direct message. """ |
params = {}
set_str_param(params, 'id', id)
set_bool_param(params, 'include_entities', include_entities)
return self._post_api('direct_messages/destroy.json', params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def direct_messages_new(self, text, user_id=None, screen_name=None):
""" Sends a new direct message to the given user from the authenticating user. https://dev.twitter.com/docs/api/1.1/post/direct_messages/new :param str text: (*required*) The text of your direct message. :param str user_id: The ID of the user who should receive the direct message. Required if ``screen_name`` isn't given. :param str screen_name: The screen name of the user who should receive the direct message. Required if ``user_id`` isn't given. :returns: A direct message dict containing the sent direct message. """ |
params = {}
set_str_param(params, 'text', text)
set_str_param(params, 'user_id', user_id)
set_str_param(params, 'screen_name', screen_name)
return self._post_api('direct_messages/new.json', params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def friendships_create(self, user_id=None, screen_name=None, follow=None):
""" Allows the authenticating users to follow the specified user. https://dev.twitter.com/docs/api/1.1/post/friendships/create :param str user_id: The screen name of the user for whom to befriend. Required if ``screen_name`` isn't given. :param str screen_name: The ID of the user for whom to befriend. Required if ``user_id`` isn't given. :param bool follow: Enable notifications for the target user. :returns: A dict containing the newly followed user. """ |
params = {}
set_str_param(params, 'user_id', user_id)
set_str_param(params, 'screen_name', screen_name)
set_bool_param(params, 'follow', follow)
return self._post_api('friendships/create.json', params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def friendships_destroy(self, user_id=None, screen_name=None):
""" Allows the authenticating user to unfollow the specified user. https://dev.twitter.com/docs/api/1.1/post/friendships/destroy :param str user_id: The screen name of the user for whom to unfollow. Required if ``screen_name`` isn't given. :param str screen_name: The ID of the user for whom to unfollow. Required if ``user_id`` isn't given. :returns: A dict containing the newly unfollowed user. """ |
params = {}
set_str_param(params, 'user_id', user_id)
set_str_param(params, 'screen_name', screen_name)
return self._post_api('friendships/destroy.json', params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def api_call(endpoint, args, payload):
""" Generic function to call the RO API """ |
headers = {'content-type': 'application/json; ; charset=utf-8'}
url = 'https://{}/{}'.format(args['--server'], endpoint)
attempt = 0
resp = None
while True:
try:
attempt += 1
resp = requests.post(
url, data=json.dumps(payload), headers=headers,
verify=args['--cacert']
)
resp.raise_for_status()
break
except (socket_timeout, requests.Timeout,
requests.ConnectionError, requests.URLRequired) as ex:
abort('{}'.format(ex))
except requests.HTTPError as ex:
warn('Requests HTTP error: {}'.format(ex))
if attempt >= 5:
abort('Too many HTTP errors.')
if resp is not None:
try:
return resp.json()
except ValueError:
abort('Unexpected response from server:\n\n{}'.format(resp.text))
else:
abort("Couldn't POST to Red October") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def benchmark(store, n=10000):
""" Increments an integer count n times. """ |
x = UpdatableItem(store=store, count=0)
for _ in xrange(n):
x.count += 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def progressbar(stream, prefix='Loading: ', width=0.5, **options):
""" Generator filter to print a progress bar. """ |
size = len(stream)
if not size:
return stream
if 'width' not in options:
if width <= 1:
width = round(shutil.get_terminal_size()[0] * width)
options['width'] = width
with ProgressBar(max=size, prefix=prefix, **options) as b:
b.set(0)
for i, x in enumerate(stream, 1):
yield x
b.set(i) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_week_dates(year, week, as_timestamp=False):
""" Get the dates or timestamp of a week in a year. param year: The year. param week: The week. param as_timestamp: Return values as timestamps. returns: The begin and end of the week as datetime.date or as timestamp. """ |
year = int(year)
week = int(week)
start_date = date(year, 1, 1)
if start_date.weekday() > 3:
start_date = start_date + timedelta(7 - start_date.weekday())
else:
start_date = start_date - timedelta(start_date.weekday())
dlt = timedelta(days=(week-1)*7)
start = start_date + dlt
end = start_date + dlt + timedelta(days=6)
if as_timestamp:
# Add the complete day
one_day = timedelta(days=1).total_seconds() - 0.000001
end_timestamp = time.mktime(end.timetuple()) + one_day
return time.mktime(start.timetuple()), end_timestamp
return start, end |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_year_week(timestamp):
"""Get the year and week for a given timestamp.""" |
time_ = datetime.fromtimestamp(timestamp)
year = time_.isocalendar()[0]
week = time_.isocalendar()[1]
return year, week |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_last_weeks(number_of_weeks):
"""Get the last weeks.""" |
time_now = datetime.now()
year = time_now.isocalendar()[0]
week = time_now.isocalendar()[1]
weeks = []
for i in range(0, number_of_weeks):
start = get_week_dates(year, week - i, as_timestamp=True)[0]
n_year, n_week = get_year_week(start)
weeks.append((n_year, n_week))
return weeks |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gevent_wait_callback(conn, timeout=None):
"""A wait callback useful to allow gevent to work with Psycopg.""" |
while 1:
state = conn.poll()
if state == extensions.POLL_OK:
break
elif state == extensions.POLL_READ:
wait_read(conn.fileno(), timeout=timeout)
elif state == extensions.POLL_WRITE:
wait_write(conn.fileno(), timeout=timeout)
else:
raise OperationalError(
"Bad result from poll: %r" % state) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conf(self):
"""Generate the Sphinx `conf.py` configuration file Returns: (str):
the contents of the `conf.py` file. """ |
return self.env.get_template('conf.py.j2').render(
metadata=self.metadata,
package=self.package) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makefile(self):
"""Generate the documentation Makefile. Returns: (str):
the contents of the `Makefile`. """ |
return self.env.get_template('Makefile.j2').render(
metadata=self.metadata,
package=self.package) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare_trees(dir1, dir2):
"""Parse two directories and return lists of unique files""" |
paths1 = DirPaths(dir1).walk()
paths2 = DirPaths(dir2).walk()
return unique_venn(paths1, paths2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def validate(self, data):
'''Validates a data dict against this schema.
Args:
data (dict): The data to be validated.
Raises:
ValidationError: If the data is invalid.
'''
try:
self._validator.validate(data)
except jsonschema.ValidationError as e:
six.raise_from(ValidationError.create_from(e), e) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_version(request, response):
"""Set version and revision to response """ |
settings = request.registry.settings
resolver = DottedNameResolver()
# get version config
version_header = settings.get(
'api.version_header',
'X-Version',
)
version_header_value = settings.get('api.version_header_value')
if callable(version_header_value):
version_header_value = version_header_value()
elif version_header_value:
version_header_value = resolver.resolve(version_header_value)
# get revision config
revision_header = settings.get(
'api.revision_header',
'X-Revision',
)
revision_header_value = settings.get('api.revision_header_value')
if callable(revision_header_value):
revision_header_value = revision_header_value()
elif revision_header_value:
revision_header_value = resolver.resolve(revision_header_value)
if version_header and version_header_value:
response.headers[str(version_header)] = str(version_header_value)
if revision_header and revision_header_value:
response.headers[str(revision_header)] = str(revision_header_value) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.