output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Returns a set of constraints that define fermionic ladder operators. | Explain what the following Python 3 code does
def bosonic_constraints(a):
substitutions = {}
for i, ai in enumerate(a):
substitutions[ai * Dagger(ai)] = 1.0 + Dagger(ai) * ai
for aj in a[i+1:]:
# substitutions[ai*Dagger(aj)] = -Dagger(ai)*aj
substitutions[ai*Dagger(aj)] =... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a set of constraints that define fermionic ladder operators. | Can you generate the documentation for the following Python 3 function
def fermionic_constraints(a):
substitutions = {}
for i, ai in enumerate(a):
substitutions[ai ** 2] = 0
substitutions[Dagger(ai) ** 2] = 0
substitutions[ai * Dagger(ai)] = 1.0 - Dagger(ai) * ai
for aj in a[i+1:... | You are a Python code generator, capable of creating scripts from specifications. |
Returns a set of constraints that define Pauli spin operators. | Make a summary of the following Python 3 code
def pauli_constraints(X, Y, Z):
substitutions = {}
n_vars = len(X)
for i in range(n_vars):
# They square to the identity
substitutions[X[i] * X[i]] = 1
substitutions[Y[i] * Y[i]] = 1
substitutions[Z[i] * Z[i]] = 1
# Antic... | As a Python code composer, you craft elegant and concise scripts. |
Generates symbolic variables that behave like measurements. | Can you tell what is the following Python 3 function doing
def generate_measurements(party, label):
measurements = []
for i in range(len(party)):
measurements.append(generate_operators(label + '%s' % i, party[i] - 1,
hermitian=True))
return measurements | You are a Python code generator, capable of creating scripts from specifications. |
def projective_measurement_constraints(*parties):
"""Return a set of constraints that define projective measurements.
:param parties: Measurements of different parties.
:type A: list or tuple of list of list of
:class:`sympy.physics.quantum.operator.HermitianOperator`.
:returns: substitut... | Create a Python 3 function for
returning a set of constraints that define projective measurements. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def define_objective_with_I(I, *args):
"""Define a polynomial using measurements and an I matrix describing a Bell
inequality.
:param I: The I matrix of a Bell inequality in the Collins-Gisin notation.
:type I: list of list of int.
:param args: Either the measurements of Alice and Bob or a `Probabi... | Create a Python 3 function for
defining a polynomial using measurements and an I matrix describing a Bell etic inequality. | You are a Python code generator, capable of creating scripts from specifications. |
Returns the correlators between the probabilities of two parties. | Can you generate the documentation for the following Python 3 function
def correlator(A, B):
correlators = []
for i in range(len(A)):
correlator_row = []
for j in range(len(B)):
corr = 0
for k in range(len(A[i])):
for l in range(len(B[j])):
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the maximum violation of a two - party Bell inequality. | Make a summary of the following Python 3 code
def maximum_violation(A_configuration, B_configuration, I, level, extra=None):
P = Probability(A_configuration, B_configuration)
objective = define_objective_with_I(I, P)
if extra is None:
extramonomials = []
else:
extramonomials = P.get_extr... | You are a Python code analyst, evaluating scripts for potential improvements. |
A sorted python2 / 3 stable formatting of a dictionary. | Can you generate the documentation for the following Python 3 function
def stable_format_dict(d):
inner = ', '.join('{}: {}'.format(repr(k)[1:]
if repr(k).startswith(u"u'") or repr(k).startswith(u'u"')
else repr(k),
... | You are a Python code generator, capable of creating scripts from specifications. |
def interval_overlap(a, b, x, y):
"""Returns by how much two intervals overlap
assumed that a <= b and x <= y"""
if b <= x or a >= y:
return 0
elif x <= a <= y:
return min(b, y) - a
elif x <= b <= y:
return b - max(a, x)
elif a >= x and b <= y:
return b - a
e... | How would you implement a function in Python 3 that
returns by how much two intervals overlap a and b. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a slice of a string that is width - aware. | Make a summary of the following Python 3 code
def width_aware_slice(s, start, end, replacement_char=u' '):
# type: (Text, int, int, Text)
"""
>>> width_aware_slice(u'a\uff25iou', 0, 2)[1] == u' '
True
"""
divides = [0]
for c in s:
divides.append(divides[-1] + wcswidth(c))
new_ch... | As a Python code composer, you craft elegant and concise scripts. |
Returns a list of lines split on the last possible space of each line. | Here you have a function in Python 3, explain what it does
def linesplit(string, columns):
# type: (Union[Text, FmtStr], int) -> List[FmtStr]
"""Returns a list of lines, split on the last possible space of each line.
Split spaces will be removed. Whitespaces will be normalized to one space.
Spaces will... | As a python code expert, you are capable of creating scripts from specifications. |
def normalize_slice(length, index):
"Fill in the Nones in a slice."
is_int = False
if isinstance(index, int):
is_int = True
index = slice(index, index+1)
if index.start is None:
index = slice(0, index.stop, index.step)
if index.stop is None:
index = slice(index.start,... | Can you create a Python 3 function that
fills in the Nones in a slice. | You are a Python code generator, capable of creating scripts from specifications. |
Parse the arguments into a dictionary by turning them into kwargs | Can you generate a brief explanation for the following Python 3 code
def parse_args(args, kwargs):
if 'style' in kwargs:
args += (kwargs['style'],)
del kwargs['style']
for arg in args:
if not isinstance(arg, (bytes, unicode)):
raise ValueError("args must be strings:" + repr(a... | You are a Python code generator, capable of creating scripts from specifications. |
def color_str(self):
"Return an escape-coded string to write to the terminal."
s = self.s
for k, v in sorted(self.atts.items()):
# (self.atts sorted for the sake of always acting the same.)
if k not in xforms:
# Unsupported SGR code
continu... | Implement a Python 3 function for
returning an escape - coded string to write to the terminal. | As a Python code composer, you craft elegant and concise scripts. |
FmtStr repr is build by concatenating these. | Make a summary of the following Python 3 code
def repr_part(self):
def pp_att(att):
if att == 'fg': return FG_NUMBER_TO_COLOR[self.atts[att]]
elif att == 'bg': return 'on_' + BG_NUMBER_TO_COLOR[self.atts[att]]
else: return att
atts_out = dict((k, v) for (k, v) in self... | You are a Python code generator, capable of creating scripts from specifications. |
def request(self, max_width):
# type: (int) -> Optional[Tuple[int, Chunk]]
"""Requests a sub-chunk of max_width or shorter. Returns None if no chunks left."""
if max_width < 1:
raise ValueError('requires positive integer max_width')
s = self.chunk.s
length = len(s)
... | Create a Python 3 function to
request a sub - chunk of max_width or shorter. Returns None if no more chunks are available. Returns None if no more chunks are available. Returns None if no more chunks are available. Returns None if no more chunks are available. | You are a Python code generator, capable of creating scripts from specifications. |
def copy_with_new_str(self, new_str):
"""Copies the current FmtStr's attributes while changing its string."""
# What to do when there are multiple Chunks with conflicting atts?
old_atts = dict((att, value) for bfs in self.chunks
for (att, value) in bfs.atts.items())
r... | Write a Python 3 script for
copying the current FmtStr s attributes while changing its string. | You are a Python code architect, reviewing and designing scalable and efficient code |
def setitem(self, startindex, fs):
"""Shim for easily converting old __setitem__ calls"""
return self.setslice_with_length(startindex, startindex+1, fs, len(self)) | Can you implement a function in Python 3 that
shims for easily converting old __setitem__ calls | As a python code expert, you are capable of creating scripts from specifications. |
def setslice_with_length(self, startindex, endindex, fs, length):
"""Shim for easily converting old __setitem__ calls"""
if len(self) < startindex:
fs = ' '*(startindex - len(self)) + fs
if len(self) > endindex:
fs = fs + ' '*(endindex - startindex - len(fs))
... | Implement a Python 3 function for
shimming for easily converting old __setitem__ calls | You are a Python code generator, capable of creating scripts from specifications. |
Returns a new FmtStr with the input string spliced into the FmtStr at start and end. | How would you explain what the following Python 3 function does
def splice(self, new_str, start, end=None):
if len(new_str) == 0:
return self
new_fs = new_str if isinstance(new_str, FmtStr) else fmtstr(new_str)
assert len(new_fs.chunks) > 0, (new_fs.chunks, new_fs)
new_compon... | As a python code expert, you are capable of creating scripts from specifications. |
Returns a new FmtStr with the same content but new formatting | How would you explain what the following Python 3 function does
def copy_with_new_atts(self, **attributes):
return FmtStr(*[Chunk(bfs.s, bfs.atts.extend(attributes))
for bfs in self.chunks]) | You are a Python code analyst, evaluating scripts for potential improvements. |
Joins an iterable yielding strings or FmtStrs with self as separator | Can you generate the documentation for the following Python 3 function
def join(self, iterable):
before = []
chunks = []
for i, s in enumerate(iterable):
chunks.extend(before)
before = self.chunks
if isinstance(s, FmtStr):
chunks.extend(s.chunk... | As a Python code analyst, you investigate and solve complex coding mysteries |
Split based on seperator optionally using a regex
| Can you tell what is the following Python 3 function doing
def split(self, sep=None, maxsplit=None, regex=False):
if maxsplit is not None:
raise NotImplementedError('no maxsplit yet')
s = self.s
if sep is None:
sep = r'\s+'
elif not regex:
sep = re.esc... | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a list of lines split on newline characters and include line boundaries. | Can you tell what is the following Python 3 function doing
def splitlines(self, keepends=False):
lines = self.split('\n')
return [line+'\n' for line in lines] if keepends else (
lines if lines[-1] else lines[:-1]) | As a Python code analyst, you investigate and solve complex coding mysteries |
def width_at_offset(self, n):
"""Returns the horizontal position of character n of the string"""
#TODO make more efficient?
width = wcswidth(self.s[:n])
assert width != -1
return width | Implement a function in Python 3 to
return the horizontal position of the character n of the string | You are a Python code architect, reviewing and designing scalable and efficient code |
def shared_atts(self):
"""Gets atts shared among all nonzero length component Chunk"""
#TODO cache this, could get ugly for large FmtStrs
atts = {}
first = self.chunks[0]
for att in sorted(first.atts):
#TODO how to write this without the '???'?
if all(fs.a... | How would you code a function in Python 3 to
get atts shared among all nonzero length component Chunks | As a Python code composer, you craft elegant and concise scripts. |
Returns a new FmtStr with the same content but some attributes removed | Can you generate a brief explanation for the following Python 3 code
def new_with_atts_removed(self, *attributes):
return FmtStr(*[Chunk(bfs.s, bfs.atts.remove(*attributes))
for bfs in self.chunks]) | As a python code expert, you are capable of creating scripts from specifications. |
def divides(self):
"""List of indices of divisions between the constituent chunks."""
acc = [0]
for s in self.chunks:
acc.append(acc[-1] + len(s))
return acc | Write a Python 3 function that can
list of indices of divisions between the constituent chunks. | As a python code expert, you are capable of creating scripts from specifications. |
def width_aware_slice(self, index):
"""Slice based on the number of columns it would take to display the substring."""
if wcswidth(self.s) == -1:
raise ValueError('bad values for width aware slicing')
index = normalize_slice(self.width, index)
counter = 0
parts = []
... | How would you code a function in Python 3 to
return a slice based on the number of columns it would take to display the substring. | As a Python code analyst, you investigate and solve complex coding mysteries |
def width_aware_splitlines(self, columns):
# type: (int) -> Iterator[FmtStr]
"""Split into lines, pushing doublewidth characters at the end of a line to the next line.
When a double-width character is pushed to the next line, a space is added to pad out the line.
"""
if columns ... | Implement a Python 3 function for
splitting into lines pushing double - width characters at the end of a line to the next line. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _getitem_normalized(self, index):
"""Builds the more compact fmtstrs by using fromstr( of the control sequences)"""
index = normalize_slice(len(self), index)
counter = 0
output = ''
for fs in self.chunks:
if index.start < counter + len(fs) and index.stop > counter... | How would you code a function in Python 3 to
build the more compact fmtstrs by using fromstr of the control sequences. | You are a Python code architect, reviewing and designing scalable and efficient code |
Calculates the block_struct array for the output file. | Can you generate the documentation for the following Python 3 function
def _calculate_block_structure(self, inequalities, equalities,
momentinequalities, momentequalities,
extramomentmatrix, removeequalities,
block_... | You are a Python code architect, reviewing and designing scalable and efficient code |
Process a single monomial when building the moment matrix. | Can you generate a brief explanation for the following Python 3 code
def _process_monomial(self, monomial, n_vars):
coeff, monomial = monomial.as_coeff_Mul()
k = 0
# Have we seen this monomial before?
conjugate = False
try:
# If yes, then we improve sparsity by reusin... | You are a Python code generator, capable of creating scripts from specifications. |
This function returns a dense vector representation of a polynomial. This function is also intended to be used by the trace function of the polynomial. This function is also intended to be used by the pushing_facvar_sparse function. | Make a summary of the following Python 3 code
def __get_trace_facvar(self, polynomial):
facvar = [0] * (self.n_vars + 1)
F = {}
for i in range(self.matrix_var_dim):
for j in range(self.matrix_var_dim):
for key, value in \
polynomial[i, j].as_co... | You are a Python code generator, capable of creating scripts from specifications. |
def set_objective(self, objective, extraobjexpr=None):
"""Set or change the objective function of the polynomial optimization
problem.
:param objective: Describes the objective function.
:type objective: :class:`sympy.core.expr.Expr`
:param extraobjexpr: Optional parameter of a ... | Implement a function in Python 3 to
set or change the objective function of the polynomial optimization. | You are a Python code architect, reviewing and designing scalable and efficient code |
Calculates the block_struct array for the output file. | How would you explain what the following Python 3 function does
def _calculate_block_structure(self, inequalities, equalities,
momentinequalities, momentequalities,
extramomentmatrix, removeequalities,
block_struct=... | As a python code expert, you are capable of creating scripts from specifications. |
def write_to_file(self, filename, filetype=None):
"""Write the relaxation to a file.
:param filename: The name of the file to write to. The type can be
autodetected from the extension: .dat-s for SDPA,
.task for mosek, .csv for human readable format, or... | How would you implement a function in Python 3 that
writes the relaxation to a file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_outerframe_skip_importlib_frame(level):
"""
There's a bug in Python3.4+, see http://bugs.python.org/issue23773,
remove this and use sys._getframe(3) when bug is fixed
"""
if sys.version_info < (3, 4):
return sys._getframe(level)
else:
curre... | Implement a Python 3 function for
returning the outerframe of the given level skipping importlib frames. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def public_api(self,url):
''' template function of public api'''
try :
url in api_urls
return ast.literal_eval(requests.get(base_url + api_urls.get(url)).text)
except Exception as e:
print(e) | Can you create a Python 3 function that
templates function of public api | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the processed text the next token and unprocessed text. | How would you explain what the following Python 3 function does
def peel_off_esc_code(s):
p = r"""(?P<front>.*?)
(?P<seq>
(?P<csi>
(?:[]\[)
|
["""+'\x9b' + r"""])
(?P<private>)
(?P<numbers>
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a key pressed from bytes_ or None meaning it s an incomplete sequence of bytes. | Can you generate a brief explanation for the following Python 3 code
def get_key(bytes_, encoding, keynames='curtsies', full=False):
if not all(isinstance(c, type(b'')) for c in bytes_):
raise ValueError("get key expects bytes, got %r" % bytes_) # expects raw bytes
if keynames not in ['curtsies', 'curse... | As a Python code analyst, you investigate and solve complex coding mysteries |
Whether seq bytes might create a char in encoding if more bytes were added | Here you have a function in Python 3, explain what it does
def could_be_unfinished_char(seq, encoding):
if decodable(seq, encoding):
return False # any sensible encoding surely doesn't require lookahead (right?)
# (if seq bytes encoding a character, adding another byte shouldn't also encode somethin... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a pretty representation of an Event or keypress | Here you have a function in Python 3, explain what it does
def pp_event(seq):
if isinstance(seq, Event):
return str(seq)
# Get the original sequence back if seq is a pretty name already
rev_curses = dict((v, k) for k, v in CURSES_NAMES.items())
rev_curtsies = dict((v, k) for k, v in CURTSIES_N... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return a string of random nouns up to max number | Explain what the following Python 3 code does
def create_nouns(max=2):
nouns = []
for noun in range(0, max):
nouns.append(random.choice(noun_list))
return " ".join(nouns) | You are a Python code architect, reviewing and designing scalable and efficient code |
def create_date(past=False, max_years_future=10, max_years_past=10):
"""
Create a random valid date
If past, then dates can be in the past
If into the future, then no more than max_years into the future
If it's not, then it can't be any older than max_years_past
"""
if past:
start = ... | Write a Python 3 script to
create a random valid date based on the given parameters | As a Python code analyst, you investigate and solve complex coding mysteries |
def create_birthday(min_age=18, max_age=80):
"""
Create a random birthday fomr someone between the ages of min_age and max_age
"""
age = random.randint(min_age, max_age)
start = datetime.date.today() - datetime.timedelta(days=random.randint(0, 365))
return start - datetime.timedelta(days=age * 3... | Implement a function in Python 3 to
create a random birthday fomr someone between the ages of min_age and max_age | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a random password in a random language | Given the following Python 3 function, write the documentation
def create_pw(length=8, digits=2, upper=2, lower=2):
seed(time())
lowercase = string.ascii_lowercase
uppercase = string.ascii_uppercase
letters = string.ascii_letters
password = list(
chain(
(choice(uppercase) for _... | As a Python code composer, you craft elegant and concise scripts. |
Run through some simple examples
| Can you generate the documentation for the following Python 3 function
def show_examples():
first, last = create_name()
add = create_street()
zip, city, state = create_city_state_zip()
phone = create_phone(zip)
print(first, last)
print(add)
print("{0:s} {1:s} {2:s}".format(city, state, zip))... | As a Python code analyst, you investigate and solve complex coding mysteries |
This function converts a row of a Mosek matrix into the lower - triangular index of the C and C j. | Can you generate a brief explanation for the following Python 3 code
def convert_to_mosek_index(block_struct, row_offsets, block_offsets, row):
block_index, i, j = convert_row_to_sdpa_index(block_struct, row_offsets,
row)
offset = block_offsets[block_index]
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Converts the entire sparse representation of the Fi constraint matrices
to sparse MOSEK matrices. | Can you tell what is the following Python 3 function doing
def convert_to_mosek_matrix(sdp):
barci = []
barcj = []
barcval = []
barai = []
baraj = []
baraval = []
for k in range(sdp.n_vars):
barai.append([])
baraj.append([])
baraval.append([])
row_offsets = [0]
... | You are a Python code generator, capable of creating scripts from specifications. |
Convert an SDP relaxation to a MOSEK task. | Given the following Python 3 function, write the documentation
def convert_to_mosek(sdp):
import mosek
# Cheat when variables are complex and convert with PICOS
if sdp.complex_matrix:
from .picos_utils import convert_to_picos
Problem = convert_to_picos(sdp).to_real()
Problem._make_mo... | As a python code expert, you are capable of creating scripts from specifications. |
def _add_text(self, text):
"""
If ``text`` is not empty, append a new Text node to the most recent
pending node, if there is any, or to the new nodes, if there are no
pending nodes.
"""
if text:
if self.pending_nodes:
self.pending_nodes[-1].app... | Implement a function in Python 3 to
add a new Text node to the most recent NoCOOKIE. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns an FSArray of the maximum size of the provided FmtStrs_or_strings or width and height of the number of strings provided. | Can you tell what is the following Python 3 function doing
def fsarray(strings, *args, **kwargs):
strings = list(strings)
if 'width' in kwargs:
width = kwargs['width']
del kwargs['width']
if strings and max(len(s) for s in strings) > width:
raise ValueError("Those strings wo... | You are a Python code architect, reviewing and designing scalable and efficient code |
def diff(cls, a, b, ignore_formatting=False):
"""Returns two FSArrays with differences underlined"""
def underline(x): return u'\x1b[4m%s\x1b[0m' % (x,)
def blink(x): return u'\x1b[5m%s\x1b[0m' % (x,)
a_rows = []
b_rows = []
max_width = max([len(row) for row in a] + [len(... | How would you implement a function in Python 3 that
returns two FSArrays with differences underlined | You are a Python code architect, reviewing and designing scalable and efficient code |
create new order function | Make a summary of the following Python 3 code
def create(self,rate, amount, order_type, pair):
''' create new order function
:param rate: float
:param amount: float
:param order_type: str; set 'buy' or 'sell'
:param pair: str; set 'btc_jpy'
'''
nonce = nounce()
... | As a Python code analyst, you investigate and solve complex coding mysteries |
cancel the order with the specified order_id | Can you generate the documentation for the following Python 3 function
def cancel(self,order_id):
''' cancel the specified order
:param order_id: order_id to be canceled
'''
url= 'https://coincheck.com/api/exchange/orders/' + order_id
headers = make_header(url,access_key=self.acc... | You are a Python code generator, capable of creating scripts from specifications. |
def _length_hint(obj):
"""Returns the length hint of an object."""
try:
return len(obj)
except TypeError:
try:
get_hint = type(obj).__length_hint__
except AttributeError:
return None
try:
hint = get_hint(obj)
except TypeError:
... | Implement a function in Python 3 to
return the length hint of an object. | As a python code expert, you are capable of creating scripts from specifications. |
def pager(text, color=None):
"""Decide what method to use for paging through text."""
stdout = _default_text_stdout()
if not isatty(sys.stdin) or not isatty(stdout):
return _nullpager(stdout, text, color)
if 'PAGER' in os.environ:
if WIN:
return _tempfilepager(text, os.enviro... | How would you implement a function in Python 3 that
decides what method to use for paging through text. | You are a Python code generator, capable of creating scripts from specifications. |
def from_int(cls, retries, redirect=True, default=None):
""" Backwards-compatibility for the old retries format."""
if retries is None:
retries = default if default is not None else cls.DEFAULT
if isinstance(retries, Retry):
return retries
redirect = bool(redire... | Write a Python 3 script to
convert a retries value to a Retry object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_backoff_time(self):
""" Formula for computing the current backoff
:rtype: float
"""
if self._observed_errors <= 1:
return 0
backoff_value = self.backoff_factor * (2 ** (self._observed_errors - 1))
return min(self.BACKOFF_MAX, backoff_value) | How would you implement a function in Python 3 that
returns the current backoff time. | As a Python code analyst, you investigate and solve complex coding mysteries |
Is this method retryable? | Can you tell what is the following Python 3 function doing
def is_forced_retry(self, method, status_code):
if self.method_whitelist and method.upper() not in self.method_whitelist:
return False
return self.status_forcelist and status_code in self.status_forcelist | As a Python code composer, you craft elegant and concise scripts. |
def convert_type(ty, default=None):
"""Converts a callable or python ty into the most appropriate param
ty.
"""
if isinstance(ty, tuple):
return Tuple(ty)
if isinstance(ty, ParamType):
return ty
guessed_type = False
if ty is None and default is not None:
ty = type(def... | Create a Python 3 function for
converting a callable or python ty into the most appropriate param ty. | You are a Python code analyst, evaluating scripts for potential improvements. |
Writes a usage line into the buffer. | Can you tell what is the following Python 3 function doing
def write_usage(self, prog, args='', prefix='Usage: '):
prefix = '%*s%s' % (self.current_indent, prefix, prog)
self.write(prefix)
text_width = max(self.width - self.current_indent - term_len(prefix), 10)
indent = ' ' * (term_len... | As a python code expert, you are capable of creating scripts from specifications. |
def in_(ctx, topics, yes, as_, enter):
"""Set the current topics to `topics`
Environment:
BE_PROJECT: First topic
BE_CWD: Current `be` working directory
BE_TOPICS: Arguments to `in`
BE_DEVELOPMENTDIR: Absolute path to current development directory
BE_PROJECTROOT: Absolut... | Can you implement a function in Python 3 that
sets the current topics to topics | As a Python code translator, you convert algorithms and pseudocode into Python. |
def new(preset, name, silent, update):
"""Create new default preset
\b
Usage:
$ be new ad
"blue_unicorn" created
$ be new film --name spiderman
"spiderman" created
"""
if self.isactive():
lib.echo("Please exit current preset before starting a new")
... | How would you code a function in Python 3 to
create a new empty file in the current project | As a Python code analyst, you investigate and solve complex coding mysteries |
Update a local preset | Make a summary of the following Python 3 code
def update(preset, clean):
if self.isactive():
lib.echo("ERROR: Exit current project first")
sys.exit(lib.USER_ERROR)
presets = _extern.github_presets()
if preset not in presets:
sys.stdout.write("\"%s\" not found" % preset)
sy... | As a python code expert, you are capable of creating scripts from specifications. |
Utility sub - command for tab completion
| Can you tell what is the following Python 3 function doing
def tab(topics, complete):
# Discard `be tab`
topics = list(topics)[2:]
# When given an incomplete argument,
# the argument is *sometimes* returned twice (?)
# .. note:: Seen in Git Bash on Windows
# $ be in giant [TAB]
# -> ['gian... | You are a Python code generator, capable of creating scripts from specifications. |
def activate():
"""Enter into an environment with support for tab-completion
This command drops you into a subshell, similar to the one
generated via `be in ...`, except no topic is present and
instead it enables tab-completion for supported shells.
See documentation for further information.
h... | Can you create a Python 3 function that
enters into an environment with support for tab - completion | You are a Python code analyst, evaluating scripts for potential improvements. |
List contents of current context. | Can you tell what is the following Python 3 function doing
def ls(topics):
if self.isactive():
lib.echo("ERROR: Exit current project first")
sys.exit(lib.USER_ERROR)
# List projects
if len(topics) == 0:
for project in lib.list_projects(root=_extern.cwd()):
lib.echo("- %... | As a python code expert, you are capable of creating scripts from specifications. |
Create a directory with the template for the current environment | Here you have a function in Python 3, explain what it does
def mkdir(dir, enter):
if not os.path.exists(dir):
os.makedirs(dir) | As a Python code composer, you craft elegant and concise scripts. |
List presets available on the current project | Given the following Python 3 function, write the documentation
def preset_ls(remote):
if self.isactive():
lib.echo("ERROR: Exit current project first")
sys.exit(lib.USER_ERROR)
if remote:
presets = _extern.github_presets()
else:
presets = _extern.local_presets()
if not... | You are a Python code analyst, evaluating scripts for potential improvements. |
Find preset from hub
| Given the following Python 3 function, write the documentation
def preset_find(query):
if self.isactive():
lib.echo("ERROR: Exit current project first")
sys.exit(lib.USER_ERROR)
found = _extern.github_presets().get(query)
if found:
lib.echo(found)
else:
lib.echo("Unable... | You are a Python code architect, reviewing and designing scalable and efficient code |
def dump():
"""Print current environment
Environment is outputted in a YAML-friendly format
\b
Usage:
$ be dump
Prefixed:
- BE_TOPICS=hulk bruce animation
- ...
"""
if not self.isactive():
lib.echo("ERROR: Enter a project first")
sys.exit(lib.U... | Can you create a Python 3 function that
prints current environment and redirected environment variables | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the Requests tuple auth for a given url from netrc. | Make a summary of the following Python 3 code
def get_netrc_auth(url):
try:
from netrc import netrc, NetrcParseError
netrc_path = None
for f in NETRC_FILES:
try:
loc = os.path.expanduser('~/{0}'.format(f))
except KeyError:
# os.path.... | As a python code expert, you are capable of creating scripts from specifications. |
Returns a CookieJar from a key - value dictionary. | Given the following Python 3 function, write the documentation
def add_dict_to_cookiejar(cj, cookie_dict):
cj2 = cookiejar_from_dict(cookie_dict)
cj.update(cj2)
return cj | You are a Python code analyst, evaluating scripts for potential improvements. |
def should_bypass_proxies(url):
"""
Returns whether we should bypass proxies or not.
"""
get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())
# First check whether no_proxy is defined. If it is, check that the URL
# we're getting isn't in the no_proxy list.
no_proxy = get_pr... | How would you code a function in Python 3 to
return whether we should bypass proxies on this URL. | As a python code expert, you are capable of creating scripts from specifications. |
def default_user_agent(name="python-requests"):
"""Return a string representing the default user agent."""
_implementation = platform.python_implementation()
if _implementation == 'CPython':
_implementation_version = platform.python_version()
elif _implementation == 'PyPy':
_implementat... | How would you code a function in Python 3 to
return a string representing the default user agent. | You are a Python code architect, reviewing and designing scalable and efficient code |
def to_native_string(string, encoding='ascii'):
"""
Given a string object, regardless of type, returns a representation of that
string in the native string type, encoding and decoding where necessary.
This assumes ASCII unless told otherwise.
"""
out = None
if isinstance(string, builtin_str... | Can you create a Python 3 function that
gives a string object regardless of type returns a representation of that string in the native string type encoding and decoding where necessary. | As a Python code composer, you craft elegant and concise scripts. |
Internal handler for the bash completion support. | Here you have a function in Python 3, explain what it does
def _bashcomplete(cmd, prog_name, complete_var=None):
if complete_var is None:
complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper()
complete_instr = os.environ.get(complete_var)
if not complete_instr:
return
fro... | You are a Python code analyst, evaluating scripts for potential improvements. |
def invoke(*args, **kwargs):
"""Invokes a command callback in exactly the way it expects. There
are two ways to invoke this method:
1. the first argument can be a callback and all other arguments and
keyword arguments are forwarded directly to the function.
2. the first a... | Can you implement a function in Python 3 that
invokes a command callback in exactly the way it expects. | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function is called by the command line parser when a new context is created. | How would you explain what the following Python 3 function does
def make_context(self, info_name, args, parent=None, **extra):
for key, value in iteritems(self.context_settings):
if key not in extra:
extra[key] = value
ctx = Context(self, info_name=info_name, parent=parent, *... | You are a Python code architect, reviewing and designing scalable and efficient code |
def make_parser(self, ctx):
"""Creates the underlying option parser for this command."""
parser = OptionParser(ctx)
parser.allow_interspersed_args = ctx.allow_interspersed_args
parser.ignore_unknown_options = ctx.ignore_unknown_options
for param in self.get_params(ctx):
... | Can you write a function in Python 3 where it
creates the underlying option parser for this command. | As a python code expert, you are capable of creating scripts from specifications. |
def format_help_text(self, ctx, formatter):
"""Writes the help text to the formatter if it exists."""
if self.help:
formatter.write_paragraph()
with formatter.indentation():
formatter.write_text(self.help) | Write a Python 3 script for
writing the help text to the formatter if it exists. | As a python code expert, you are capable of creating scripts from specifications. |
Registers another command with this group. | Here you have a function in Python 3, explain what it does
def add_command(self, cmd, name=None):
name = name or cmd.name
if name is None:
raise TypeError('Command has no name.')
self.commands[name] = cmd | You are a Python code architect, reviewing and designing scalable and efficient code |
Decorator to pass the object on the object on the object context. | How would you explain what the following Python 3 function does
def pass_obj(f):
@pass_context
def new_func(*args, **kwargs):
ctx = args[0]
return ctx.invoke(f, ctx.obj, *args[1:], **kwargs)
return update_wrapper(new_func, f) | You are a Python code generator, capable of creating scripts from specifications. |
Decorator to add an option to the command. | Can you generate a brief explanation for the following Python 3 code
def option(*param_decls, **attrs):
def decorator(f):
if 'help' in attrs:
attrs['help'] = inspect.cleandoc(attrs['help'])
OptionClass = attrs.pop('cls', Option)
_param_memo(f, OptionClass(param_decls, **attrs))
... | As a python code expert, you are capable of creating scripts from specifications. |
def version_option(version=None, *param_decls, **attrs):
"""Adds a ``--version`` option which immediately ends the program
printing out the version number. This is implemented as an eager
option that prints the version and exits the program in the callback.
:param version: the version number to show. ... | How would you code a function in Python 3 to
add a option to be applied to a single command line command line. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _basic_auth_str(username, password):
"""Returns a Basic Auth string."""
authstr = 'Basic ' + to_native_string(
b64encode(('%s:%s' % (username, password)).encode('latin1')).strip()
)
return authstr | Write a Python 3 function that can
return a Basic Auth string. | You are a Python code architect, reviewing and designing scalable and efficient code |
List all the items in the external datastore. | Can you tell what is the following Python 3 function doing
def ls(*topic, **kwargs):
context = dump()
root = kwargs.get("root") or context.get("cwd") or os.getcwd()
backend = kwargs.get("backend", os.listdir)
absolute = kwargs.get("absolute", True)
content = {
0: "projects",
1: "i... | As a Python code composer, you craft elegant and concise scripts. |
Dump current environment as a dictionary | Can you generate the documentation for the following Python 3 function
def dump(context=os.environ):
output = {}
for key, value in context.iteritems():
if not key.startswith("BE_"):
continue
output[key[3:].lower()] = value
return output | As a python code expert, you are capable of creating scripts from specifications. |
Return the be current working directory | Can you generate a brief explanation for the following Python 3 code
def cwd():
cwd = os.environ.get("BE_CWD")
if cwd and not os.path.isdir(cwd):
sys.stderr.write("ERROR: %s is not a directory" % cwd)
sys.exit(lib.USER_ERROR)
return cwd or os.getcwd().replace("\\", "/") | You are a Python code analyst, evaluating scripts for potential improvements. |
def write_script(script, tempdir):
"""Write script to a temporary directory
Arguments:
script (list): Commands which to put into a file
Returns:
Absolute path to script
"""
name = "script" + self.suffix
path = os.path.join(tempdir, name)
with open(path, "w") as f:
... | Write a Python 3 function for
writing a list of commands to a temporary directory and returns the absolute path to the script | As a python code expert, you are capable of creating scripts from specifications. |
Write aliases to temporary directory | Can you generate a brief explanation for the following Python 3 code
def write_aliases(aliases, tempdir):
platform = lib.platform()
if platform == "unix":
home_alias = "cd $BE_DEVELOPMENTDIR"
else:
home_alias = "cd %BE_DEVELOPMENTDIR%"
aliases["home"] = home_alias
tempdir = os.pat... | As a Python code analyst, you investigate and solve complex coding mysteries |
Physically delete local preset | Can you generate a brief explanation for the following Python 3 code
def remove_preset(preset):
preset_dir = os.path.join(presets_dir(), preset)
try:
shutil.rmtree(preset_dir)
except IOError:
lib.echo("\"%s\" did not exist" % preset) | You are a Python code architect, reviewing and designing scalable and efficient code |
Wrapper for requests. get | Explain what the following Python 3 code does
def get(path, **kwargs):
token = os.environ.get(BE_GITHUB_API_TOKEN)
if token:
kwargs["headers"] = {
"Authorization": "token %s" % token
}
try:
response = requests.get(path, verify=False, **kwargs)
if response.status_... | As a Python code composer, you craft elegant and concise scripts. |
Evaluate whether gist is a be package | Can you generate a brief explanation for the following Python 3 code
def _gist_is_preset(repo):
_, gistid = repo.split("/")
gist_template = "https://api.github.com/gists/{}"
gist_path = gist_template.format(gistid)
response = get(gist_path)
if response.status_code == 404:
return False
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _repo_is_preset(repo):
"""Evaluate whether GitHub repository is a be package
Arguments:
gist (str): username/id pair e.g. mottosso/be-ad
"""
package_template = "https://raw.githubusercontent.com"
package_template += "/{repo}/master/package.json"
package_path = package_template.for... | How would you implement a function in Python 3 that
evaluates whether GitHub repository is a be package | As a Python code translator, you convert algorithms and pseudocode into Python. |
def github_presets():
"""Return remote presets hosted on GitHub"""
addr = ("https://raw.githubusercontent.com"
"/mottosso/be-presets/master/presets.json")
response = get(addr)
if response.status_code == 404:
lib.echo("Could not connect with preset database")
sys.exit(lib.PRO... | Can you create a Python 3 function that
returns remote presets hosted on GitHub | You are a Python code generator, capable of creating scripts from specifications. |
Copy contents of preset into new project_dir | Can you generate the documentation for the following Python 3 function
def copy_preset(preset_dir, project_dir):
os.makedirs(project_dir)
package_file = os.path.join(preset_dir, "package.json")
with open(package_file) as f:
package = json.load(f)
for fname in os.listdir(preset_dir):
s... | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.