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 in_check_as_result(self, pos, move):
""" Finds if playing my move would make both kings meet. :type: pos: Board :type: move: Move :rtype: bool """ |
test = cp(pos)
test.update(move)
test_king = test.get_king(move.color)
return self.loc_adjacent_to_opponent_king(test_king.location, test) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loc_adjacent_to_opponent_king(self, location, position):
""" Finds if 2 kings are touching given the position of one of the kings. :type: location: Location ... |
for fn in self.cardinal_directions:
try:
if isinstance(position.piece_at_square(fn(location)), King) and \
position.piece_at_square(fn(location)).color != self.color:
return True
except IndexError:
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 add(self, func, position):
""" Adds all 8 cardinal directions as moves for the King if legal. :type: function: function :type: position: Board :rtype: gen ""... |
try:
if self.loc_adjacent_to_opponent_king(func(self.location), position):
return
except IndexError:
return
if position.is_square_empty(func(self.location)):
yield self.create_move(func(self.location), notation_const.MOVEMENT)
elif 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 _rook_legal_for_castle(self, rook):
""" Decides if given rook exists, is of this color, and has not moved so it is eligible to castle. :type: rook: Rook :rty... |
return rook is not None and \
type(rook) is Rook and \
rook.color == self.color and \
not rook.has_moved |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _empty_not_in_check(self, position, direction):
""" Checks if set of squares in between ``King`` and ``Rook`` are empty and safe for the king to castle. :typ... |
def valid_square(square):
return position.is_square_empty(square) and \
not self.in_check(position, square)
return valid_square(direction(self.location, 1)) and \
valid_square(direction(self.location, 2)) |
<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_castle(self, position):
""" Adds kingside and queenside castling moves if legal :type: position: Board """ |
if self.has_moved or self.in_check(position):
return
if self.color == color.white:
rook_rank = 0
else:
rook_rank = 7
castle_type = {
notation_const.KING_SIDE_CASTLE: {
"rook_file": 7,
"direction": lambda 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 possible_moves(self, position):
""" Generates list of possible moves :type: position: Board :rtype: list """ |
# Chain used to combine multiple generators
for move in itertools.chain(*[self.add(fn, position) for fn in self.cardinal_directions]):
yield move
for move in self.add_castle(position):
yield move |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def in_check(self, position, location=None):
""" Finds if the king is in check or if both kings are touching. :type: position: Board :return: bool """ |
location = location or self.location
for piece in position:
if piece is not None and piece.color != self.color:
if not isinstance(piece, King):
for move in piece.possible_moves(position):
if move.end_loc == location:
... |
<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_keep_alive(sock, idle=10, interval=5, fails=5):
"""Sets the keep-alive setting for the peer socket. :param sock: Socket to be configured. :param idle: In... |
import sys
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
if sys.platform in ('linux', 'linux2'):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, idle)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval)
sock.setsockopt(socket.IPPROTO_TCP, socke... |
<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_default(cls):
""" Creates a ``Board`` with the standard chess starting position. :rtype: Board """ |
return cls([
# First rank
[Rook(white, Location(0, 0)), Knight(white, Location(0, 1)), Bishop(white, Location(0, 2)),
Queen(white, Location(0, 3)), King(white, Location(0, 4)), Bishop(white, Location(0, 5)),
Knight(white, Location(0, 6)), Rook(white, Location(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def material_advantage(self, input_color, val_scheme):
""" Finds the advantage a particular side possesses given a value scheme. :type: input_color: Color :type:... |
if self.get_king(input_color).in_check(self) and self.no_moves(input_color):
return -100
if self.get_king(-input_color).in_check(self) and self.no_moves(-input_color):
return 100
return sum([val_scheme.val(piece, input_color) for piece in 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 advantage_as_result(self, move, val_scheme):
""" Calculates advantage after move is played :type: move: Move :type: val_scheme: PieceValues :rtype: double ""... |
test_board = cp(self)
test_board.update(move)
return test_board.material_advantage(move.color, val_scheme) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _calc_all_possible_moves(self, input_color):
""" Returns list of all possible moves :type: input_color: Color :rtype: list """ |
for piece in self:
# Tests if square on the board is not empty
if piece is not None and piece.color == input_color:
for move in piece.possible_moves(self):
test = cp(self)
test_move = Move(end_loc=move.end_loc,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def runInParallel(*fns):
""" Runs multiple processes in parallel. :type: fns: def """ |
proc = []
for fn in fns:
p = Process(target=fn)
p.start()
proc.append(p)
for p in proc:
p.join() |
<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_piece(self, piece):
""" Finds Location of the first piece that matches piece. If none is found, Exception is raised. :type: piece: Piece :rtype: Locatio... |
for i, _ in enumerate(self.position):
for j, _ in enumerate(self.position):
loc = Location(i, j)
if not self.is_square_empty(loc) and \
self.piece_at_square(loc) == piece:
return loc
raise ValueError("{} \nPiece 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 place_piece_at_square(self, piece, location):
""" Places piece at given get_location :type: piece: Piece :type: location: Location """ |
self.position[location.rank][location.file] = piece
piece.location = location |
<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_piece(self, initial, final):
""" Moves piece from one location to another :type: initial: Location :type: final: Location """ |
self.place_piece_at_square(self.piece_at_square(initial), final)
self.remove_piece_at_square(initial) |
<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, move):
""" Updates position by applying selected move :type: move: Move """ |
if move is None:
raise TypeError("Move cannot be type None")
if self.king_loc_dict is not None and isinstance(move.piece, King):
self.king_loc_dict[move.color] = move.end_loc
# Invalidates en-passant
for square in self:
pawn = square
if ... |
<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_subgraphs(self, g):
if not isinstance(g, CGRContainer):
raise InvalidData('only CGRContainer acceptable')
r_group = []
x_group = {}
r_group_clones = []
newcomponents = []
''' search bond breaks and creations
'''
components, lost_bon... |
<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_substitution_paths(g):
""" get atoms paths from detached atom to attached :param g: CGRContainer :return: tuple of atoms numbers """ |
for n, nbrdict in g.adjacency():
for m, l in combinations(nbrdict, 2):
nms = nbrdict[m]['sp_bond']
nls = nbrdict[l]['sp_bond']
if nms == (1, None) and nls == (None, 1):
yield m, n, l
elif nms == (None, 1) and nls ==... |
<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_crud(self, model_data, object_type, results):
""" Creates a menu entry for given model data. Updates results in place. Args: model_data: Model data. obj... |
model = model_registry.get_model(model_data['name'])
field_name = model_data.get('field')
verbose_name = model_data.get('verbose_name', model.Meta.verbose_name_plural)
category = model_data.get('category', settings.DEFAULT_OBJECT_CATEGORY_NAME)
wf_dict = {"text": verbose_name,
... |
<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_workflow_menus(self):
""" Creates menu entries for custom workflows. Returns: Dict of list of dicts (``{'':[{}],}``). Menu entries. """ |
results = defaultdict(list)
from zengine.lib.cache import WFSpecNames
for name, title, category in WFSpecNames().get_or_set():
if self.current.has_permission(name) and category != 'hidden':
wf_dict = {
"text": title,
"wf": name... |
<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):
""" Creates connection to RabbitMQ server """ |
if self.connecting:
log.info('PikaClient: Already connecting to RabbitMQ')
return
log.info('PikaClient: Connecting to RabbitMQ')
self.connecting = True
self.connection = TornadoConnection(NON_BLOCKING_MQ_PARAMS,
stop_... |
<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_connected(self, connection):
""" AMQP connection callback. Creates input channel. Args: connection: AMQP connection """ |
log.info('PikaClient: connected to RabbitMQ')
self.connected = True
self.in_channel = self.connection.channel(self.on_channel_open) |
<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_channel_open(self, channel):
""" Input channel creation callback Queue declaration done here Args: channel: input channel """ |
self.in_channel.exchange_declare(exchange='input_exc', type='topic', durable=True)
channel.queue_declare(callback=self.on_input_queue_declare, queue=self.INPUT_QUEUE_NAME) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wsgi_app(self, request):
"""Incoming request handler. :param request: Werkzeug request object """ |
try:
if request.method != 'POST':
abort(400)
try:
# Python 2.7 compatibility
data = request.data
if isinstance(data, str):
body = json.loads(data)
else:
body = json.... |
<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, force=False):
""" close opened file :param force: force closing of externally opened file or buffer """ |
if self.__write:
self.write = self.__write_adhoc
self.__write = False
if not self._is_buffer or force:
self._file.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def aromatize(self):
""" convert structure to aromatic form :return: number of processed rings """ |
rings = [x for x in self.sssr if 4 < len(x) < 7]
if not rings:
return 0
total = 0
while True:
c = self._quinonize(rings, 'order')
if c:
total += c
elif total:
break
c = self._aromatize(rings, 'o... |
<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, *args, **kwargs):
""" write close tag of MRV file and close opened file :param force: force closing of externally opened file or buffer """ |
if not self.__finalized:
self._file.write('</cml>')
self.__finalized = True
super().close(*args, **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 write(self, data):
""" write single molecule or reaction into file """ |
self._file.write('<cml>')
self.__write(data)
self.write = self.__write |
<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_tasks(current):
""" List task invitations of current user .. code-block:: python # request: { 'view': '_zops_get_tasks', 'state': string, # one of these:... |
# TODO: Also return invitations for user's other roles
# TODO: Handle automatic role switching
STATE_DICT = {
'active': [20, 30],
'future': 10,
'finished': 40,
'expired': 90
}
state = STATE_DICT[current.input['state']]
if isinstance(state, list):
queryse... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reduce_memory_usage(df):
"""reduce memory usage of the dataframe - convert runIDs to categorical - downcast ints and floats """ |
usage_pre = df.memory_usage(deep=True).sum()
if "runIDs" in df:
df.loc[:, "runIDs"] = df.loc[:, "runIDs"].astype("category")
df_int = df.select_dtypes(include=['int'])
df_float = df.select_dtypes(include=['float'])
df.loc[:, df_int.columns] = df_int.apply(pd.to_numeric, downcast='unsigned')... |
<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_existance(f):
"""Check if the file supplied as input exists.""" |
if not opath.isfile(f):
logging.error("Nanoget: File provided doesn't exist or the path is incorrect: {}".format(f))
sys.exit("File provided doesn't exist or the path is incorrect: {}".format(f)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_user_roles(self):
""" Lists user roles as selectable except user's current role. """ |
_form = JsonForm(current=self.current, title=_(u"Switch Role"))
_form.help_text = "Your current role: %s %s" % (self.current.role.unit.name,
self.current.role.abstract_role.name)
switch_roles = self.get_user_switchable_roles()
_for... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def change_user_role(self):
""" Changes user's role from current role to chosen role. """ |
# Get chosen role_key from user form.
role_key = self.input['form']['role_options']
# Assign chosen switch role key to user's last_login_role_key field
self.current.user.last_login_role_key = role_key
self.current.user.save()
auth = AuthBackend(self.current)
# 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 json_dumps(self, obj):
"""Serializer for consistency""" |
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': ')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def safe_filename(self, otype, oid):
"""Santize obj name into fname and verify doesn't already exist""" |
permitted = set(['_', '-', '(', ')'])
oid = ''.join([c for c in oid if c.isalnum() or c in permitted])
while oid.find('--') != -1:
oid = oid.replace('--', '-')
ext = 'json'
ts = datetime.now().strftime("%Y%m%dT%H%M%S")
fname = ''
is_new = 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 write_pkg_to_file(self, name, objects, path='.', filename=None):
"""Write a list of related objs to file""" |
# Kibana uses an array of docs, do the same
# as opposed to a dict of docs
pkg_objs = []
for _, obj in iteritems(objects):
pkg_objs.append(obj)
sorted_pkg = sorted(pkg_objs, key=lambda k: k['_id'])
output = self.json_dumps(sorted_pkg) + '\n'
if filena... |
<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_dashboard_full(self, db_name):
"""Get DB and all objs needed to duplicate it""" |
objects = {}
dashboards = self.get_objects("type", "dashboard")
vizs = self.get_objects("type", "visualization")
searches = self.get_objects("type", "search")
if db_name not in dashboards:
return None
self.pr_inf("Found dashboard: " + db_name)
objects... |
<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_node(self, node):
""" Overrides ProcessParser.parse_node Parses and attaches the inputOutput tags that created by Camunda Modeller Args: node: xml task... |
spec = super(CamundaProcessParser, self).parse_node(node)
spec.data = self._parse_input_data(node)
spec.data['lane_data'] = self._get_lane_properties(node)
spec.defines = spec.data
service_class = node.get(full_attr('assignee'))
if service_class:
self.parsed_... |
<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_lane_properties(self, node):
""" Parses the given XML node Args: node (xml):
XML node. .. code-block:: xml <bpmn2:lane id="Lane_8" name="Lane 8"> <bpmn... |
lane_name = self.get_lane(node.get('id'))
lane_data = {'name': lane_name}
for a in self.xpath(".//bpmn:lane[@name='%s']/*/*/" % lane_name):
lane_data[a.attrib['name']] = a.attrib['value'].strip()
return lane_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 package_in_memory(cls, workflow_name, workflow_files):
""" Generates wf packages from workflow diagrams. Args: workflow_name: Name of wf workflow_files: Diag... |
s = StringIO()
p = cls(s, workflow_name, meta_data=[])
p.add_bpmn_files_by_glob(workflow_files)
p.create_package()
return s.getvalue() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compose(self, data):
""" condense reaction container to CGR. see init for details about cgr_type :param data: ReactionContainer :return: CGRContainer """ |
g = self.__separate(data) if self.__cgr_type in (1, 2, 3, 4, 5, 6) else self.__condense(data)
g.meta.update(data.meta)
return g |
<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_atom(self, atom, _map=None):
""" new atom addition """ |
if _map is None:
_map = max(self, default=0) + 1
elif _map in self._node:
raise KeyError('atom with same number exists')
attr_dict = self.node_attr_dict_factory()
if isinstance(atom, str):
attr_dict.element = atom
elif isinstance(atom, int):
... |
<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_bond(self, atom1, atom2, bond):
""" implementation of bond addition """ |
if atom1 == atom2:
raise KeyError('atom loops impossible')
if atom1 not in self._node or atom2 not in self._node:
raise KeyError('atoms not found')
if atom1 in self._adj[atom2]:
raise KeyError('atoms already bonded')
attr_dict = self.edge_attr_dict_f... |
<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_bond(self, n, m):
""" implementation of bond removing """ |
self.remove_edge(n, m)
self.flush_cache() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def augmented_substructure(self, atoms, dante=False, deep=1, meta=False, as_view=True):
""" create substructure containing atoms and their neighbors :param atoms... |
nodes = [set(atoms)]
for i in range(deep):
n = {y for x in nodes[-1] for y in self._adj[x]} | nodes[-1]
if n in nodes:
break
nodes.append(n)
if dante:
return [self.substructure(a, meta, as_view) for a in nodes]
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 split(self, meta=False):
""" split disconnected structure to connected substructures :param meta: copy metadata to each substructure :return: list of substru... |
return [self.substructure(c, meta, False) for c in connected_components(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 bonds(self):
""" iterate other all bonds """ |
seen = set()
for n, m_bond in self._adj.items():
seen.add(n)
for m, bond in m_bond.items():
if m not in seen:
yield n, m, bond |
<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_subclass(name):
""" need for cyclic import solving """ |
return next(x for x in BaseContainer.__subclasses__() if x.__name__ == name) |
<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_make_pool(http, proxy_info):
"""Creates a urllib3.PoolManager object that has SSL verification enabled and uses the certifi certificates.""" |
if not http.ca_certs:
http.ca_certs = _certifi_where_for_ssl_version()
ssl_disabled = http.disable_ssl_certificate_validation
cert_reqs = 'CERT_REQUIRED' if http.ca_certs and not ssl_disabled else None
if isinstance(proxy_info, collections.Callable):
proxy_info = proxy_info()
if... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def patch(make_pool=_default_make_pool):
"""Monkey-patches httplib2.Http to be httplib2shim.Http. This effectively makes all clients of httplib2 use urlilb3. It'... |
setattr(httplib2, '_HttpOriginal', httplib2.Http)
httplib2.Http = Http
Http._make_pool = make_pool |
<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_ipv6(addr):
"""Checks if a given address is an IPv6 address.""" |
try:
socket.inet_pton(socket.AF_INET6, addr)
return True
except socket.error:
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 _certifi_where_for_ssl_version():
"""Gets the right location for certifi certifications for the current SSL version. Older versions of SSL don't support the ... |
if not ssl:
return
if ssl.OPENSSL_VERSION_INFO < (1, 0, 2):
warnings.warn(
'You are using an outdated version of OpenSSL that '
'can\'t use stronger root certificates.')
return certifi.old_where()
return certifi.where() |
<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_exception(e):
"""Maps an exception from urlib3 to httplib2.""" |
if isinstance(e, urllib3.exceptions.MaxRetryError):
if not e.reason:
return e
e = e.reason
message = e.args[0] if e.args else ''
if isinstance(e, urllib3.exceptions.ResponseError):
if 'too many redirects' in message:
return httplib2.RedirectLimit(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 exit(self, signal=None, frame=None):
""" Properly close the AMQP connections """ |
self.input_channel.close()
self.client_queue.close()
self.connection.close()
log.info("Worker exiting")
sys.exit(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 connect(self):
""" make amqp connection and create channels and queue binding """ |
self.connection = pika.BlockingConnection(BLOCKING_MQ_PARAMS)
self.client_queue = ClientQueue()
self.input_channel = self.connection.channel()
self.input_channel.exchange_declare(exchange=self.INPUT_EXCHANGE,
type='topic',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear_queue(self):
""" clear outs all messages from INPUT_QUEUE_NAME """ |
def remove_message(ch, method, properties, body):
print("Removed message: %s" % body)
self.input_channel.basic_consume(remove_message, queue=self.INPUT_QUEUE_NAME, no_ack=True)
try:
self.input_channel.start_consuming()
except (KeyboardInterrupt, SystemExit):
... |
<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(self):
""" actual consuming of incoming works starts here """ |
self.input_channel.basic_consume(self.handle_message,
queue=self.INPUT_QUEUE_NAME,
no_ack=True
)
try:
self.input_channel.start_consuming()
except (KeyboardInter... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_message(self, ch, method, properties, body):
""" this is a pika.basic_consumer callback handles client inputs, runs appropriate workflows and views Ar... |
input = {}
headers = {}
try:
self.sessid = method.routing_key
input = json_decode(body)
data = input['data']
# since this comes as "path" we dont know if it's view or workflow yet
# TODO: just a workaround till we modify ui to
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync_wf_cache(current):
""" BG Job for storing wf state to DB """ |
wf_cache = WFCache(current)
wf_state = wf_cache.get() # unicode serialized json to dict, all values are unicode
if 'role_id' in wf_state:
# role_id inserted by engine, so it's a sign that we get it from cache not db
try:
wfi = WFInstance.objects.get(key=current.input['token'])
... |
<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_description(self):
""" Tries to get WF description from 'collabration' or 'process' or 'pariticipant' Returns str: WF description """ |
paths = ['bpmn:collaboration/bpmn:participant/bpmn:documentation',
'bpmn:collaboration/bpmn:documentation',
'bpmn:process/bpmn:documentation']
for path in paths:
elm = self.root.find(path, NS)
if elm is not None and elm.text:
ret... |
<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_tasks(self):
""" will create a WFInstance per object and per TaskInvitation for each role and WFInstance """ |
roles = self.get_roles()
if self.task_type in ["A", "D"]:
instances = self.create_wf_instances(roles=roles)
self.create_task_invitation(instances)
elif self.task_type in ["C", "B"]:
instances = self.create_wf_instances()
self.create_task_invitat... |
<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_model_objects(model, wfi_role=None, **kwargs):
""" Fetches model objects by filtering with kwargs If wfi_role is specified, then we expect kwargs contain... |
query_dict = {}
for k, v in kwargs.items():
if isinstance(v, list):
query_dict[k] = [str(x) for x in v]
else:
parse = str(v).split('.')
if parse[0] == 'role' and wfi_role:
query_dict[k] = wfi_role
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post_save(self):
"""can be removed when a proper task manager admin interface implemented""" |
if self.run:
self.run = False
self.create_tasks()
self.save() |
<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_other_invitations(self):
""" When one person use an invitation, we should delete other invitations """ |
# TODO: Signal logged-in users to remove the task from their task list
self.objects.filter(instance=self.instance).exclude(key=self.key).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 save(self, wf_state):
""" write wf state to DB through MQ >> Worker >> _zops_sync_wf_cache Args: wf_state dict: wf state """ |
self.wf_state = wf_state
self.wf_state['role_id'] = self.current.role_id
self.set(self.wf_state)
if self.wf_state['name'] not in settings.EPHEMERAL_WORKFLOWS:
self.publish(job='_zops_sync_wf_cache',
token=self.db_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 send_to_prv_exchange(self, user_id, message=None):
""" Send messages through logged in users private exchange. Args: user_id string: User key message dict: M... |
exchange = 'prv_%s' % user_id.lower()
msg = json.dumps(message, cls=ZEngineJSONEncoder)
log.debug("Sending following users \"%s\" exchange:\n%s " % (exchange, msg))
self.get_channel().publish(exchange=exchange, routing_key='', body=msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decompose(self):
""" decompose CGR to pair of Molecules, which represents reactants and products state of reaction :return: tuple of two molecules """ |
mc = self._get_subclass('MoleculeContainer')
reactants = mc()
products = mc()
for n, atom in self.atoms():
reactants.add_atom(atom._reactant, n)
products.add_atom(atom._product, n)
for n, m, bond in self.bonds():
if bond._reactant is not 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 size_history(self,size_data):
"""Return the a DataFrame, indexed by day, with columns containing story size for each issue. In addition, columns are soted by... |
def my_merge(df1, df2):
# http://stackoverflow.com/questions/34411495/pandas-merge-several-dataframes
res = pd.merge(df1, df2, how='outer', left_index=True, right_index=True)
cols = sorted(res.columns)
pairs = []
for col1, col2 in zip(cols[:-1], cols... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def histogram(self, cycle_data, bins=10):
"""Return histogram data for the cycle times in `cycle_data`. Returns a dictionary with keys `bin_values` and `bin_edge... |
values, edges = np.histogram(cycle_data['cycle_time'].astype('timedelta64[D]').dropna(), bins=bins)
index = []
for i, v in enumerate(edges):
if i == 0:
continue
index.append("%.01f to %.01f" % (edges[i - 1], edges[i],))
return pd.Series(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 scatterplot(self, cycle_data):
"""Return scatterplot data for the cycle times in `cycle_data`. Returns a data frame containing only those items in `cycle_dat... |
columns = list(cycle_data.columns)
columns.remove('cycle_time')
columns.remove('completed_timestamp')
columns = ['completed_timestamp', 'cycle_time'] + columns
data = (
cycle_data[columns]
.dropna(subset=['cycle_time', 'completed_timestamp'])
... |
<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_ready(self, topic_name):
'''
Is NSQ running and have space to receive messages?
'''
url = 'http://%s/stats?format=json&topic=%s' % (self.nsqd_http_address, topic_name)
#Cheacking for ephmeral channels
if '#' in topic_name:
topic_name, tag =topic_name.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 centers_list(self):
""" get a list of lists of atoms of reaction centers """ |
center = set()
adj = defaultdict(set)
for n, atom in self.atoms():
if atom._reactant != atom._product:
center.add(n)
for n, m, bond in self.bonds():
if bond._reactant != bond._product:
adj[n].add(m)
adj[m].add(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 _matcher(self, other):
""" CGRContainer < CGRContainer """ |
if isinstance(other, CGRContainer):
return GraphMatcher(other, self, lambda x, y: x == y, lambda x, y: x == y)
raise TypeError('only cgr-cgr possible') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __plain_bfs(adj, source):
"""modified NX fast BFS node generator""" |
seen = set()
nextlevel = {source}
while nextlevel:
thislevel = nextlevel
nextlevel = set()
for v in thislevel:
if v not in seen:
yield v
seen.add(v)
nextlevel.update(adj[v]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def token(self):
""" Returns authorization token provided by Cocaine. The real meaning of the token is determined by its type. For example OAUTH2 token will have... |
if self._token is None:
token_type = os.getenv(TOKEN_TYPE_KEY, '')
token_body = os.getenv(TOKEN_BODY_KEY, '')
self._token = _Token(token_type, token_body)
return self._token |
<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(self):
""" Send a message lazy formatted with args. External log attributes can be passed via named attribute `extra`, like in logging from the standar... |
buff = BytesIO()
while True:
msgs = list()
try:
msg = yield self.queue.get()
# we need to connect first, as we issue verbosity request just after connection
# and channels should strictly go in ascending order
if 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 moves_in_direction(self, direction, position):
""" Finds moves in a given direction :type: direction: lambda :type: position: Board :rtype: list """ |
current_square = self.location
while True:
try:
current_square = direction(current_square)
except IndexError:
return
if self.contains_opposite_color_piece(current_square, position):
yield self.create_move(current_squa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def possible_moves(self, position):
""" Returns all possible rook moves. :type: position: Board :rtype: list """ |
for move in itertools.chain(*[self.moves_in_direction(fn, position) for fn in self.cross_fn]):
yield move |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def overlap_status(a, b):
"""Check overlap between two arrays. Parameters a, b : array-like Arrays to check. Assumed to be in the same unit. Returns ------- resu... |
# Get the endpoints
a1, a2 = a.min(), a.max()
b1, b2 = b.min(), b.max()
# Do the comparison
if a1 >= b1 and a2 <= b2:
result = 'full'
elif a2 < b1 or b2 < a1:
result = 'none'
else:
result = 'partial'
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 validate_totalflux(totalflux):
"""Check integrated flux for invalid values. Parameters totalflux : float Integrated flux. Raises ------ synphot.exceptions.Sy... |
if totalflux <= 0.0:
raise exceptions.SynphotError('Integrated flux is <= 0')
elif np.isnan(totalflux):
raise exceptions.SynphotError('Integrated flux is NaN')
elif np.isinf(totalflux):
raise exceptions.SynphotError('Integrated flux is infinite') |
<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_wavelengths(wavelengths):
"""Check wavelengths for ``synphot`` compatibility. Wavelengths must satisfy these conditions: * valid unit type, if given... |
if isinstance(wavelengths, u.Quantity):
units.validate_wave_unit(wavelengths.unit)
wave = wavelengths.value
else:
wave = wavelengths
if np.isscalar(wave):
wave = [wave]
wave = np.asarray(wave)
# Check for zeroes
if np.any(wave <= 0):
raise exceptions.Z... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_wavelengths(minwave=500, maxwave=26000, num=10000, delta=None, log=True, wave_unit=u.AA):
"""Generate wavelength array to be used for spectrum sampl... |
wave_unit = units.validate_unit(wave_unit)
if delta is not None:
num = None
waveset_str = 'Min: {0}, Max: {1}, Num: {2}, Delta: {3}, Log: {4}'.format(
minwave, maxwave, num, delta, log)
# Log space
if log:
logmin = np.log10(minwave)
logmax = np.log10(maxwave)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_data(cdbs_root, verbose=True, dry_run=False):
"""Download CDBS data files to given root directory. Download is skipped if a data file already exists... |
from .config import conf # Avoid potential circular import
if not os.path.exists(cdbs_root):
os.makedirs(cdbs_root, exist_ok=True)
if verbose: # pragma: no cover
print('Created {}'.format(cdbs_root))
elif not os.path.isdir(cdbs_root):
raise OSError('{} must be a direc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def main(loop):
"""Demonstrate functionality of PyVLX.""" |
pyvlx = PyVLX('pyvlx.yaml', loop=loop)
# Alternative:
# pyvlx = PyVLX(host="192.168.2.127", password="velux123", loop=loop)
# Runing scenes:
await pyvlx.load_scenes()
await pyvlx.scenes["All Windows Closed"].run()
# Changing position of windows:
await pyvlx.load_nodes()
await pyvl... |
<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(self, node):
"""Add Node, replace existing node if node with node_id is present.""" |
if not isinstance(node, Node):
raise TypeError()
for i, j in enumerate(self.__nodes):
if j.node_id == node.node_id:
self.__nodes[i] = node
return
self.__nodes.append(node) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def load(self, node_id=None):
"""Load nodes from KLF 200, if no node_id is specified all nodes are loaded.""" |
if node_id is not None:
await self._load_node(node_id=node_id)
else:
await self._load_all_nodes() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def _load_node(self, node_id):
"""Load single node via API.""" |
get_node_information = GetNodeInformation(pyvlx=self.pyvlx, node_id=node_id)
await get_node_information.do_api_call()
if not get_node_information.success:
raise PyVLXException("Unable to retrieve node information")
notification_frame = get_node_information.notification_frame... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def _load_all_nodes(self):
"""Load all nodes via API.""" |
get_all_nodes_information = GetAllNodesInformation(pyvlx=self.pyvlx)
await get_all_nodes_information.do_api_call()
if not get_all_nodes_information.success:
raise PyVLXException("Unable to retrieve node information")
self.clear()
for notification_frame in get_all_nod... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
"""Create loop task.""" |
self.run_task = self.pyvlx.loop.create_task(
self.loop()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def stop(self):
"""Stop heartbeat.""" |
self.stopped = True
self.loop_event.set()
# Waiting for shutdown of loop()
await self.stopped_event.wait() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def loop(self):
"""Pulse every timeout seconds until stopped.""" |
while not self.stopped:
self.timeout_handle = self.pyvlx.connection.loop.call_later(
self.timeout_in_seconds, self.loop_timeout)
await self.loop_event.wait()
if not self.stopped:
self.loop_event.clear()
await self.pulse()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def pulse(self):
"""Send get state request to API to keep the connection alive.""" |
get_state = GetState(pyvlx=self.pyvlx)
await get_state.do_api_call()
if not get_state.success:
raise PyVLXException("Unable to send get 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 string_to_bytes(string, size):
"""Convert string to bytes add padding.""" |
if len(string) > size:
raise PyVLXException("string_to_bytes::string_to_large")
encoded = bytes(string, encoding='utf-8')
return encoded + bytes(size-len(encoded)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bytes_to_string(raw):
"""Convert bytes to string.""" |
ret = bytes()
for byte in raw:
if byte == 0x00:
return ret.decode("utf-8")
ret += bytes([byte])
return ret.decode("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:
async def house_status_monitor_disable(pyvlx):
"""Disable house status monitor.""" |
status_monitor_disable = HouseStatusMonitorDisable(pyvlx=pyvlx)
await status_monitor_disable.do_api_call()
if not status_monitor_disable.success:
raise PyVLXException("Unable disable house status monitor.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def BitmathType(bmstring):
"""An 'argument type' for integrations with the argparse module. For more information, see https://docs.python.org/2/library/argparse.... |
try:
argvalue = bitmath.parse_string(bmstring)
except ValueError:
raise argparse.ArgumentTypeError("'%s' can not be parsed into a valid bitmath object" %
bmstring)
else:
return argvalue |
<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_apiv2():
""" Setup apiv2 when using PyQt4 and Python2. """ |
# setup PyQt api to version 2
if sys.version_info[0] == 2:
logging.getLogger(__name__).debug(
'setting up SIP API to version 2')
import sip
try:
sip.setapi("QString", 2)
sip.setapi("QVariant", 2)
except ValueError:
logging.getLogge... |
<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_config(cls, pyvlx, item):
"""Read roller shutter from config.""" |
name = item['name']
ident = item['id']
subtype = item['subtype']
typeid = item['typeId']
return cls(pyvlx, ident, name, subtype, typeid) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.