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 _txtinfo_to_python(self, data):
""" Converts txtinfo format to python """ |
self._format = 'txtinfo'
# find interesting section
lines = data.split('\n')
try:
start = lines.index('Table: Topology') + 2
except ValueError:
raise ParserError('Unrecognized format')
topology_lines = [line for line in lines[start:] if 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 _get_primary_address(self, mac_address, node_list):
""" Uses the _get_aggregated_node_list structure to find the primary mac address associated to a secondar... |
for local_addresses in node_list:
if mac_address in local_addresses:
return local_addresses[0]
return mac_address |
<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_aggregated_node_list(self, data):
""" Returns list of main and secondary mac addresses. """ |
node_list = []
for node in data:
local_addresses = [node['primary']]
if 'secondary' in node:
local_addresses += node['secondary']
node_list.append(local_addresses)
return node_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_alfred_vis(self, data):
""" Converts a alfred-vis JSON object to a NetworkX Graph object which is then returned. Additionally checks for "source_vesio... |
# initialize graph and list of aggregated nodes
graph = self._init_graph()
if 'source_version' in data:
self.version = data['source_version']
if 'vis' not in data:
raise ParserError('Parse error, "vis" key not found')
node_list = self._get_aggregated_node... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def json(self, dict=False, **kwargs):
""" Outputs NetJSON format """ |
try:
graph = self.graph
except AttributeError:
raise NotImplementedError()
return _netjson_networkgraph(self.protocol,
self.version,
self.revision,
self.metric,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def diff(old, new):
""" Returns differences of two network topologies old and new in NetJSON NetworkGraph compatible format """ |
protocol = new.protocol
version = new.version
revision = new.revision
metric = new.metric
# calculate differences
in_both = _find_unchanged(old.graph, new.graph)
added_nodes, added_edges = _make_diff(old.graph, new.graph, in_both)
removed_nodes, removed_edges = _make_diff(new.graph, old... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_diff(old, new, both):
""" calculates differences between topologies 'old' and 'new' returns a tuple with two network graph objects the first graph cont... |
# make a copy of old topology to avoid tampering with it
diff_edges = new.copy()
not_different = [tuple(edge) for edge in both]
diff_edges.remove_edges_from(not_different)
# repeat operation with nodes
diff_nodes = new.copy()
not_different = []
for new_node in new.nodes():
if ne... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_unchanged(old, new):
""" returns edges that are in both old and new """ |
edges = []
old_edges = [set(edge) for edge in old.edges()]
new_edges = [set(edge) for edge in new.edges()]
for old_edge in old_edges:
if old_edge in new_edges:
edges.append(set(old_edge))
return edges |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_changed(old, new, both):
""" returns links that have changed cost """ |
# create two list of sets of old and new edges including cost
old_edges = []
for edge in old.edges(data=True):
# skip links that are not in both
if set((edge[0], edge[1])) not in both:
continue
# wrap cost in tuple so it will be recognizable
cost = (edge[2]['weig... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, data):
""" Converts a BMX6 b6m JSON to a NetworkX Graph object which is then returned. """ |
# initialize graph and list of aggregated nodes
graph = self._init_graph()
if len(data) != 0:
if "links" not in data[0]:
raise ParserError('Parse error, "links" key not found')
# loop over topology section and create networkx graph
# this data structu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, data):
""" Converts a CNML structure to a NetworkX Graph object which is then returned. """ |
graph = self._init_graph()
# loop over links and create networkx graph
# Add only working nodes with working links
for link in data.get_inner_links():
if link.status != libcnml.libcnml.Status.WORKING:
continue
interface_a, interface_b = link.getLi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, data):
""" Converts a dict representing an OLSR 0.6.x topology to a NetworkX Graph object, which is then returned. Additionally checks for "confi... |
graph = self._init_graph()
if 'topology' not in data:
raise ParserError('Parse error, "topology" key not found')
elif 'mid' not in data:
raise ParserError('Parse error, "mid" key not found')
# determine version and revision
if 'config' in 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 _txtinfo_to_jsoninfo(self, data):
""" converts olsr 1 txtinfo format to jsoninfo """ |
# replace INFINITE with inf, which is convertible to float
data = data.replace('INFINITE', 'inf')
# find interesting section
lines = data.split('\n')
# process links in topology section
try:
start = lines.index('Table: Topology') + 2
end = 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 check_for_launchpad(old_vendor, name, urls):
"""Check if the project is hosted on launchpad. :param name: str, name of the project :param urls: set, urls to ... |
if old_vendor != "pypi":
# XXX This might work for other starting vendors
# XXX but I didn't check. For now only allow
# XXX pypi -> launchpad.
return ''
for url in urls:
try:
return re.match(r"https?://launchpad.net/([\w.\-]+)",
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_switch_vendor(old_vendor, name, urls, _depth=0):
"""Check if the project should switch vendors. E.g project pushed on pypi, but changelog on launchpad.... |
if _depth > 3:
# Protect against recursive things vendors here.
return ""
new_name = check_for_launchpad(old_vendor, name, urls)
if new_name:
return "launchpad", new_name
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 check_pil(func):
""" PIL module checking decorator. """ |
def __wrapper(*args, **kwargs):
root = kwargs.get('root')
if not Image:
if root and root.get_opt('warn'):
warn("Images manipulation require PIL")
return 'none'
return func(*args, **kwargs)
return __wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _mix(color1, color2, weight=0.5, **kwargs):
""" Mixes two colors together. """ |
weight = float(weight)
c1 = color1.value
c2 = color2.value
p = 0.0 if weight < 0 else 1.0 if weight > 1 else weight
w = p * 2 - 1
a = c1[3] - c2[3]
w1 = ((w if (w * a == -1) else (w + a) / (1 + w * a)) + 1) / 2.0
w2 = 1 - w1
q = [w1, w1, w1, p]
r = [w2, w2, w2, 1 - p]
retur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _hsla(h, s, l, a, **kwargs):
""" HSL with alpha channel color value. """ |
res = colorsys.hls_to_rgb(float(h), float(l), float(s))
return ColorValue([x * 255.0 for x in res] + [float(a)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _hue(color, **kwargs):
""" Get hue value of HSL color. """ |
h = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[0]
return NumberValue(h * 360.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 _lightness(color, **kwargs):
""" Get lightness value of HSL color. """ |
l = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[1]
return NumberValue((l * 100, '%')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _saturation(color, **kwargs):
""" Get saturation value of HSL color. """ |
s = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[2]
return NumberValue((s * 100, '%')) |
<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(path, cache=None, precache=False):
""" Parse from file. """ |
parser = Stylesheet(cache)
return parser.load(path, precache=precache) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, target):
""" Parse nested rulesets and save it in cache. """ |
if isinstance(target, ContentNode):
if target.name:
self.parent = target
self.name.parse(self)
self.name += target.name
target.ruleset.append(self)
self.root.cache['rset'][str(self.name).split()[0]].add(self)
super(Ruleset,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, target):
""" Parse nested declaration. """ |
if not isinstance(target, Node):
parent = ContentNode(None, None, [])
parent.parse(target)
target = parent
super(Declaration, self).parse(target)
self.name = str(self.data[0])
while isinstance(target, Declaration):
self.name = '-'.join((s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, target):
""" Update root and parent context. """ |
super(VarDefinition, self).parse(target)
if isinstance(self.parent, ParseNode):
self.parent.ctx.update({self.name: self.expression.value})
self.root.set_var(self) |
<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_var(self, vardef):
""" Set variable to global stylesheet context. """ |
if not(vardef.default and self.cache['ctx'].get(vardef.name)):
self.cache['ctx'][vardef.name] = vardef.expression.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_opt(self, name, value):
""" Set option. """ |
self.cache['opts'][name] = value
if name == 'compress':
self.cache['delims'] = self.def_delims if not value else (
'',
'',
'') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, cache):
""" Update self cache from other. """ |
self.cache['delims'] = cache.get('delims')
self.cache['opts'].update(cache.get('opts'))
self.cache['rset'].update(cache.get('rset'))
self.cache['mix'].update(cache.get('mix'))
map(self.set_var, cache['ctx'].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 scan(src):
""" Scan scss from string and return nodes. """ |
assert isinstance(src, (unicode_, bytes_))
try:
nodes = STYLESHEET.parseString(src, parseAll=True)
return nodes
except ParseBaseException:
err = sys.exc_info()[1]
print(err.line, file=sys.stderr)
print(" " * (err.column - 1) + "^", fil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loads(self, src):
""" Compile css from scss string. """ |
assert isinstance(src, (unicode_, bytes_))
nodes = self.scan(src.strip())
self.parse(nodes)
return ''.join(map(str, nodes)) |
<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, f, precache=None):
""" Compile scss from file. File is string path of file object. """ |
precache = precache or self.get_opt('cache') or False
nodes = None
if isinstance(f, file_):
path = os.path.abspath(f.name)
else:
path = os.path.abspath(f)
f = open(f)
cache_path = os.path.splitext(path)[0] + '.ccss'
if precache and ... |
<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_config(filename, filepath=''):
""" Loads config file Parameters filename: str Filename of config file (incl. file extension filepath: str Absolute path ... |
FILE = path.join(filepath, filename)
try:
cfg.read(FILE)
global _loaded
_loaded = True
except:
print("configfile not found.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def emoji(string):
'''emot.emoji is use to detect emoji from text
>>> text = "I love python 👨 :-)"
>>> emot.emoji(text)
>>> {'value': ['👨'], 'mean': [':man:'], 'location': [[14, 14]], 'flag': True}
'''
__entities = {}
__value = []
__mean = []
__location = []
flag =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def emoticons(string):
'''emot.emoticons is use to detect emoticons from text
>>> text = "I love python 👨 :-)"
>>> emot.emoticons(text)
>>> {'value': [':-)'], 'location': [[16, 19]], 'mean': ['Happy face smiley'], 'flag': True}
'''
__entities = []
flag = True
try:
p... |
<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_app(self, app, add_context_processor=True):
""" Initialize with app configuration """ |
# Check if login manager has been initialized
if not hasattr(app, 'login_manager'):
self.login_manager.init_app(
app,
add_context_processor=add_context_processor)
# Clear flashed messages since we redirect to auth immediately
self.login_mana... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login_url(self, params=None, **kwargs):
""" Return login url with params encoded in state Available Google auth server params: response_type: code, token pro... |
kwargs.setdefault('response_type', 'code')
kwargs.setdefault('access_type', 'online')
if 'prompt' not in kwargs:
kwargs.setdefault('approval_prompt', 'auto')
scopes = kwargs.pop('scopes', self.scopes.split(','))
if USERINFO_PROFILE_SCOPE not in scopes:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unauthorized_callback(self):
""" Redirect to login url with next param set as request.url """ |
return redirect(self.login_url(params=dict(next=request.url))) |
<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_access_token(self, refresh_token):
""" Use a refresh token to obtain a new access token """ |
token = requests.post(GOOGLE_OAUTH2_TOKEN_URL, data=dict(
refresh_token=refresh_token,
grant_type='refresh_token',
client_id=self.client_id,
client_secret=self.client_secret,
)).json()
if not token or token.get('error'):
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 oauth2callback(self, view_func):
""" Decorator for OAuth2 callback. Calls `GoogleLogin.login` then passes results to `view_func`. """ |
@wraps(view_func)
def decorated(*args, **kwargs):
params = {}
# Check sig
if 'state' in request.args:
params.update(**self.parse_state(request.args.get('state')))
if params.pop('sig', None) != make_secure_token(**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 complete(text, state):
""" Auto complete scss constructions in interactive mode. """ |
for cmd in COMMANDS:
if cmd.startswith(text):
if not state:
return cmd
else:
state -= 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 validate_args(self):
""" Validates arguments. """ |
from ..mixins import ModelMixin
for arg in ("instance", "decider", "identifier", "fields", "default_language"):
if getattr(self, arg) is None:
raise AttributeError("%s must not be None" % arg)
if not isinstance(self.instance, (ModelMixin,)):
raise Impro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def active_language(self):
""" Returns active language. """ |
# Current instance language (if user uses activate_language() method)
if self._language is not None:
return self._language
# Current site language (translation.get_language())
current = utils.get_language()
if current in self.supported_languages:
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 translation_instances(self):
""" Returns translation instances. """ |
return [
instance
for k, v in six.iteritems(self.instance._linguist_translations)
for instance in v.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 get_cache( self, instance, translation=None, language=None, field_name=None, field_value=None, ):
""" Returns translation from cache. """ |
is_new = bool(instance.pk is None)
try:
cached_obj = instance._linguist_translations[field_name][language]
if not cached_obj.field_name:
cached_obj.field_name = field_name
if not cached_obj.language:
cached_obj.language = language
... |
<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_cache( self, instance=None, translation=None, language=None, field_name=None, field_value=None, ):
""" Add a new translation into the cache. """ |
if instance is not None and translation is not None:
cached_obj = CachedTranslation.from_object(translation)
instance._linguist_translations[translation.field_name][
translation.language
] = cached_obj
return cached_obj
if instance is Non... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _filter_or_exclude(self, negate, *args, **kwargs):
""" Overrides default behavior to handle linguist fields. """ |
from .models import Translation
new_args = self.get_cleaned_args(args)
new_kwargs = self.get_cleaned_kwargs(kwargs)
translation_args = self.get_translation_args(args)
translation_kwargs = self.get_translation_kwargs(kwargs)
has_linguist_args = self.has_linguist_args(a... |
<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_linguist_kwargs(self, kwargs):
""" Parses the given kwargs and returns True if they contain linguist lookups. """ |
for k in kwargs:
if self.is_linguist_lookup(k):
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 has_linguist_args(self, args):
""" Parses the given args and returns True if they contain linguist lookups. """ |
linguist_args = []
for arg in args:
condition = self._get_linguist_condition(arg)
if condition:
linguist_args.append(condition)
return bool(linguist_args) |
<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_translation_args(self, args):
""" Returns linguist args from model args. """ |
translation_args = []
for arg in args:
condition = self._get_linguist_condition(arg, transform=True)
if condition:
translation_args.append(condition)
return translation_args |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_linguist_lookup(self, lookup):
""" Returns true if the given lookup is a valid linguist lookup. """ |
field = utils.get_field_name_from_lookup(lookup)
# To keep default behavior with "FieldError: Cannot resolve keyword".
if (
field not in self.concrete_field_names
and field in self.linguist_field_names
):
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 _get_linguist_condition(self, condition, reverse=False, transform=False):
""" Parses Q tree and returns linguist lookups or model lookups if reverse is True.... |
# We deal with a node
if isinstance(condition, Q):
children = []
for child in condition.children:
parsed = self._get_linguist_condition(
condition=child, reverse=reverse, transform=transform
)
if parsed is not N... |
<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_cleaned_args(self, args):
""" Returns positional arguments for related model query. """ |
if not args:
return args
cleaned_args = []
for arg in args:
condition = self._get_linguist_condition(arg, True)
if condition:
cleaned_args.append(condition)
return cleaned_args |
<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_cleaned_kwargs(self, kwargs):
""" Returns concrete field lookups. """ |
cleaned_kwargs = kwargs.copy()
if kwargs is not None:
for k in kwargs:
if self.is_linguist_lookup(k):
del cleaned_kwargs[k]
return cleaned_kwargs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def with_translations(self, **kwargs):
""" Prefetches translations. Takes three optional keyword arguments: * ``field_names``: ``field_name`` values for SELECT I... |
force = kwargs.pop("force", False)
if self._prefetch_translations_done and force is False:
return self
self._prefetched_translations_cache = utils.get_grouped_translations(
self, **kwargs
)
self._prefetch_translations_done = True
return self._... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def available_languages(self):
""" Returns available languages. """ |
from .models import Translation
return (
Translation.objects.filter(
identifier=self.linguist_identifier, object_id=self.pk
)
.values_list("language", flat=True)
.distinct()
.order_by("language")
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_translations(self, language=None):
""" Deletes related translations. """ |
from .models import Translation
return Translation.objects.delete_translations(obj=self, language=language) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def override_language(self, language):
""" Context manager to override the instance language. """ |
previous_language = self._linguist.language
self._linguist.language = language
yield
self._linguist.language = previous_language |
<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_meta(meta):
""" Validates Linguist Meta attribute. """ |
if not isinstance(meta, (dict,)):
raise TypeError('Model Meta "linguist" must be a dict')
required_keys = ("identifier", "fields")
for key in required_keys:
if key not in meta:
raise KeyError('Model Meta "linguist" dict requires %s to be defined', key)
if not isinstance(m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default_value_setter(field):
""" When setting to the name of the field itself, the value in the current language will be set. """ |
def default_value_func_setter(self, value):
localized_field = utils.build_localized_field_name(
field, self._linguist.active_language
)
setattr(self, localized_field, value)
return default_value_func_setter |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def field_factory(base_class):
""" Takes a field base class and wrap it with ``TranslationField`` class. """ |
from .fields import TranslationField
class TranslationFieldField(TranslationField, base_class):
pass
TranslationFieldField.__name__ = "Translation%s" % base_class.__name__
return TranslationFieldField |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_translation_field(translated_field, language):
""" Takes the original field, a given language, a decider model and return a Field class for model. """ |
cls_name = translated_field.__class__.__name__
if not isinstance(translated_field, tuple(SUPPORTED_FIELDS.keys())):
raise ImproperlyConfigured("%s is not supported by Linguist." % cls_name)
translation_class = field_factory(translated_field.__class__)
kwargs = get_translation_class_kwargs(tra... |
<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 the drone.
:raises RuntimeError: if the drone is connected or closed already.
'''
if self.connected:
raise RuntimeError(
'{} is connected already'.format(self.__class__.__name__))
if self.closed:
r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def close(self):
'''
Exit all threads and disconnect the drone.
This method has no effect if the drone is closed already or not
connected yet.
'''
if not self.connected:
return
if self.closed:
return
self.closed = True
self... |
<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_flags(self, **flags):
'''
Set the flags of this argument.
Example: ``int_param._set_flags(a=1, b=2, c=4, d=8)``
'''
self._flags = enum.IntEnum('_flags', flags)
self.__dict__.update(self._flags.__members__)
self._patch_flag_doc() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_translations(sender, instance, **kwargs):
""" Deletes related instance's translations when instance is deleted. """ |
if issubclass(sender, (ModelMixin,)):
instance._linguist.decider.objects.filter(
identifier=instance.linguist_identifier, object_id=instance.pk
).delete() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw_tree(node, child_iter=lambda n: n.children, text_str=str):
"""Support asciitree 0.2 API. This function solely exist to not break old code (using asciitr... |
return LeftAligned(traverse=Traversal(get_text=text_str,
get_children=child_iter),
draw=LegacyStyle())(node) |
<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_language():
""" Returns an active language code that is guaranteed to be in settings.SUPPORTED_LANGUAGES. """ |
lang = _get_language()
if not lang:
return get_fallback_language()
langs = [l[0] for l in settings.SUPPORTED_LANGUAGES]
if lang not in langs and "-" in lang:
lang = lang.split("-")[0]
if lang in langs:
return lang
return settings.DEFAULT_LANGUAGE |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def activate_language(instances, language):
""" Activates the given language for the given instances. """ |
language = (
language if language in get_supported_languages() else get_fallback_language()
)
for instance in instances:
instance.activate_language(language) |
<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_class(class_path, setting_name=None):
""" Loads a class given a class_path. The setting value may be a string or a tuple. The setting_name parameter is ... |
if not isinstance(class_path, six.string_types):
try:
class_path, app_label = class_path
except:
if setting_name:
raise exceptions.ImproperlyConfigured(
CLASS_PATH_ERROR % (setting_name, setting_name)
)
else:
... |
<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_translation_lookup(identifier, field, value):
""" Mapper that takes a language field, its value and returns the related lookup for Translation model. """ |
# Split by transformers
parts = field.split("__")
# Store transformers
transformers = parts[1:] if len(parts) > 1 else None
# defaults to "title" and default language
field_name = parts[0]
language = get_fallback_language()
name_parts = parts[0].split("_")
if len(name_parts) > 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 get_grouped_translations(instances, **kwargs):
""" Takes instances and returns grouped translations ready to be set in cache. """ |
grouped_translations = collections.defaultdict(list)
if not instances:
return grouped_translations
if not isinstance(instances, collections.Iterable):
instances = [instances]
if isinstance(instances, QuerySet):
model = instances.model
else:
model = instances[0]._m... |
<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_free_udp_port():
'''
Get a free UDP port.
Note this is vlunerable to race conditions.
'''
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 0))
addr = sock.getsockname()
sock.close()
return addr[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 get_available_languages(self, obj):
""" Returns available languages for current object. """ |
return obj.available_languages if obj is not None else self.model.objects.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 languages_column(self, obj):
""" Adds languages columns. """ |
languages = self.get_available_languages(obj)
return '<span class="available-languages">{0}</span>'.format(
" ".join(languages)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prefetch_translations(instances, **kwargs):
""" Prefetches translations for the given instances. Can be useful for a list of instances. """ |
from .mixins import ModelMixin
if not isinstance(instances, collections.Iterable):
instances = [instances]
populate_missing = kwargs.get("populate_missing", True)
grouped_translations = utils.get_grouped_translations(instances, **kwargs)
# In the case of no translations objects
if no... |
<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_translations(self, obj, language=None):
""" Shorcut method to retrieve translations for a given object. """ |
lookup = {"identifier": obj.linguist_identifier, "object_id": obj.pk}
if language is not None:
lookup["language"] = language
return self.get_queryset().filter(**lookup) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def takeoff(self):
'''
Sends the takeoff command.
'''
self.send(at.REF(at.REF.input.start)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def emergency(self):
'''
Sends the emergency command.
'''
self.send(at.REF(at.REF.input.select)) |
<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(
self, *,
forward=0, backward=0,
left=0, right=0,
up=0, down=0,
cw=0, ccw=0):
'''
Moves the drone.
To move the drone forward at 0.8x speed:
>>> drone.move(forward=0.8)
To move the drone right at 0.5x speed an... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode(number, checksum=False, split=0):
"""Encode an integer into a symbol string. A ValueError is raised on invalid input. If checksum is set to True, a ch... |
number = int(number)
if number < 0:
raise ValueError("number '%d' is not a positive integer" % number)
split = int(split)
if split < 0:
raise ValueError("split '%d' is not a positive integer" % split)
check_symbol = ''
if checksum:
check_symbol = encode_symbols[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 decode(symbol_string, checksum=False, strict=False):
"""Decode an encoded symbol string. If checksum is set to True, the string is assumed to have a trailing... |
symbol_string = normalize(symbol_string, strict=strict)
if checksum:
symbol_string, check_symbol = symbol_string[:-1], symbol_string[-1]
number = 0
for symbol in symbol_string:
number = number * base + decode_symbols[symbol]
if checksum:
check_value = decode_symbols[check_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize(symbol_string, strict=False):
"""Normalize an encoded symbol string. Normalization provides error correction and prepares the string for decoding. ... |
if isinstance(symbol_string, string_types):
if not PY3:
try:
symbol_string = symbol_string.encode('ascii')
except UnicodeEncodeError:
raise ValueError("string should only contain ASCII characters")
else:
raise TypeError("string is of inval... |
<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_requires():
""" Return required packages Plus any version tests and warnings """ |
from pkg_resources import parse_version
required = ['cython>=0.24.0']
numpy_requirement = 'numpy>=1.7.1'
try:
import numpy
except Exception:
required.append(numpy_requirement)
else:
if parse_version(numpy.__version__) < parse_version('1.7.1'):
required.appen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_block_context(template, context):
"""Populate the block context with BlockNodes from parent templates.""" |
# Ensure there's a BlockContext before rendering. This allows blocks in
# ExtendsNodes to be found by sub-templates (allowing {{ block.super }} and
# overriding sub-blocks to work).
if BLOCK_CONTEXT_KEY not in context.render_context:
context.render_context[BLOCK_CONTEXT_KEY] = BlockContext()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _render_template_block_nodelist(nodelist, block_name, context):
"""Recursively iterate over a node to find the wanted block.""" |
# Attempt to find the wanted block in the current template.
for node in nodelist:
# If the wanted block was found, return it.
if isinstance(node, BlockNode):
# No matter what, add this block to the rendering context.
context.render_context[BLOCK_CONTEXT_KEY].push(node.n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_block_to_string(template_name, block_name, context=None):
""" Loads the given template_name and renders the given block with the given dictionary as c... |
# Like render_to_string, template_name can be a string or a list/tuple.
if isinstance(template_name, (tuple, list)):
t = loader.select_template(template_name)
else:
t = loader.get_template(template_name)
# Create the context instance.
context = context or {}
# The Django back... |
<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_host_path(root, path, instance=None):
""" Generates the host path for a container volume. If the given path is a dictionary, uses the entry of the instan... |
r_val = resolve_value(path)
if isinstance(r_val, dict):
r_instance = instance or 'default'
r_path = resolve_value(r_val.get(r_instance))
if not r_path:
raise ValueError("No path defined for instance {0}.".format(r_instance))
else:
r_path = r_val
r_root = reso... |
<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_actions(self, actions):
""" Runs the given lists of attached actions and instance actions on the client. :param actions: Actions to apply. :type actions:... |
policy = self._policy
for action in actions:
config_id = action.config_id
config_type = config_id.config_type
client_config = policy.clients[action.client_name]
client = client_config.get_client()
c_map = policy.container_maps[config_id.map_na... |
<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_client(cls, client):
""" Constructs a configuration object from an existing client instance. If the client has already been created with a configuration... |
if hasattr(client, 'client_configuration'):
return client.client_configuration
kwargs = {'client': client}
for attr in cls.init_kwargs:
if hasattr(client, attr):
kwargs[attr] = getattr(client, attr)
if hasattr(client, 'api_version'):
k... |
<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_init_kwargs(self):
""" Generates keyword arguments for creating a new Docker client instance. :return: Keyword arguments as defined through this configur... |
init_kwargs = {}
for k in self.init_kwargs:
if k in self.core_property_set:
init_kwargs[k] = getattr(self, k)
elif k in self:
init_kwargs[k] = self[k]
return init_kwargs |
<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_client(self):
""" Retrieves or creates a client instance from this configuration object. If instantiated from this configuration, the resulting object is... |
client = self._client
if not client:
self._client = client = self.client_constructor(**self.get_init_kwargs())
client.client_configuration = self
# Client might update the version number after construction.
updated_version = getattr(client, 'api_version',... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exec_commands(self, action, c_name, run_cmds, **kwargs):
""" Runs a single command inside a container. :param action: Action configuration. :type action: doc... |
client = action.client
exec_results = []
for run_cmd in run_cmds:
cmd = run_cmd.cmd
cmd_user = run_cmd.user
log.debug("Creating exec command in container %s with user %s: %s.", c_name, cmd_user, cmd)
ec_kwargs = self.get_exec_create_kwargs(action,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exec_container_commands(self, action, c_name, **kwargs):
""" Runs all configured commands of a container configuration inside the container instance. :param ... |
config_cmds = action.config.exec_commands
if not config_cmds:
return None
return self.exec_commands(action, c_name, run_cmds=config_cmds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_path(path, replace_space, replace_sep, expandvars, expanduser):
""" Performs `os.path` replacement operations on a path string. :param path: Path str... |
r_path = path
if expandvars:
r_path = os.path.expandvars(r_path)
if expanduser:
r_path = os.path.expanduser(r_path)
if replace_sep and os.sep != posixpath.sep:
r_path = r_path.replace(os.path.sep, posixpath.sep)
if replace_space:
r_path = r_path.replace(' ', '\\ ')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_command(cmd, shell=False):
""" Converts a command line to the notation as used in a Dockerfile ``CMD`` and ``ENTRYPOINT`` command. In shell notation, ... |
def _split_cmd():
line = None
for part in cmd.split(' '):
line = part if line is None else '{0} {1}'.format(line, part)
if part[-1] != '\\':
yield line
line = None
if line is not None:
yield line
if cmd in ([], ''):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_expose(expose):
""" Converts a port number or multiple port numbers, as used in the Dockerfile ``EXPOSE`` command, to a tuple. :param: Port numbers, c... |
if isinstance(expose, six.string_types):
return expose,
elif isinstance(expose, collections.Iterable):
return map(six.text_type, expose)
return six.text_type(expose), |
<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_file(self, src_path, dst_path=None, ctx_path=None, replace_space=True, expandvars=False, expanduser=False, remove_final=False):
""" Adds a file to the Do... |
if dst_path is None:
head, tail = os.path.split(src_path)
if not tail:
# On trailing backslashes.
tail = os.path.split(head)[1]
if not tail:
ValueError("Could not generate target path from input '{0}'; needs to be speci... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, input_str):
""" Adds content to the Dockerfile. :param input_str: Content. :type input_str: unicode | str """ |
self.check_not_finalized()
if isinstance(input_str, six.binary_type):
self.fileobj.write(input_str)
else:
self.fileobj.write(input_str.encode('utf-8')) |
<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_dependency(self, item, resolve_parent, parents):
""" Merge dependencies of current configuration with further dependencies; in this instance, it means ... |
dep = []
for parent_key in parents:
if item == parent_key:
raise CircularDependency(item, True)
if parent_key.config_type == ItemType.CONTAINER:
parent_dep = resolve_parent(parent_key)
if item in parent_dep:
rai... |
<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_map(stream, name=None, check_integrity=True, check_duplicates=True):
""" Loads a ContainerMap configuration from a YAML document stream. :param stream: ... |
map_dict = yaml.safe_load(stream)
if isinstance(map_dict, dict):
map_name = name or map_dict.pop('name', None)
if not map_name:
raise ValueError("No map name provided, and none found in YAML stream.")
return ContainerMap(map_name, map_dict, check_integrity=check_integrity, c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.