INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Helper function to detect rank loop in the solution matrix.
def find_solution_ranks(self, xmat=None, baselevel=0): """Helper function to detect rank loop in the solution matrix. :param sdpRelaxation: The SDP relaxation. :type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`. :param x_mat: Optional parameter providing the primal solution of the ...
Given a solution of the dual problem and a constraint of any type it returns the corresponding block in the dual solution. If it is an equality constraint that was converted to a pair of inequalities it returns a two - tuple of the matching dual blocks.
def get_dual(self, constraint, ymat=None): """Given a solution of the dual problem and a constraint of any type, it returns the corresponding block in the dual solution. If it is an equality constraint that was converted to a pair of inequalities, it returns a two-tuple of the matching d...
Write the relaxation to a file.
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 or .csv for human readable format. ...
Get the SDP relaxation of a noncommutative polynomial optimization problem.
def get_relaxation(self, level, objective=None, inequalities=None, equalities=None, substitutions=None, momentinequalities=None, momentequalities=None, momentsubstitutions=None, removeequalities=False, extramonomials=None, ...
Flatten a list of lists to a list.
def flatten(lol): """Flatten a list of lists to a list. :param lol: A list of lists in arbitrary depth. :type lol: list of list. :returns: flat list of elements. """ new_list = [] for element in lol: if element is None: continue elif not isinstance(element, list...
Simplify a polynomial for uniform handling later.
def simplify_polynomial(polynomial, monomial_substitutions): """Simplify a polynomial for uniform handling later. """ if isinstance(polynomial, (int, float, complex)): return polynomial polynomial = (1.0 * polynomial).expand(mul=True, multinomial=True) ...
Separate the constant factor from a monomial.
def __separate_scalar_factor(monomial): """Separate the constant factor from a monomial. """ scalar_factor = 1 if is_number_type(monomial): return S.One, monomial if monomial == 0: return S.One, 0 comm_factors, _ = split_commutative_parts(monomial) if len(comm_factors) > 0: ...
Gets the support of a polynomial.
def get_support(variables, polynomial): """Gets the support of a polynomial. """ support = [] if is_number_type(polynomial): support.append([0] * len(variables)) return support for monomial in polynomial.expand().as_coefficients_dict(): tmp_support = [0] * len(variables) ...
Gets the support of a polynomial.
def get_support_variables(polynomial): """Gets the support of a polynomial. """ support = [] if is_number_type(polynomial): return support for monomial in polynomial.expand().as_coefficients_dict(): mon, _ = __separate_scalar_factor(monomial) symbolic_support = flatten(split_...
Construct a monomial with the coefficient separated from an element in a polynomial.
def separate_scalar_factor(element): """Construct a monomial with the coefficient separated from an element in a polynomial. """ coeff = 1.0 monomial = S.One if isinstance(element, (int, float, complex)): coeff *= element return monomial, coeff for var in element.as_coeff_mul...
Given a list of monomials it counts those that have a certain degree or less. The function is useful when certain monomials were eliminated from the basis.
def count_ncmonomials(monomials, degree): """Given a list of monomials, it counts those that have a certain degree, or less. The function is useful when certain monomials were eliminated from the basis. :param variables: The noncommutative variables making up the monomials :param monomials: List of...
Helper function to remove monomials from the basis.
def apply_substitutions(monomial, monomial_substitutions, pure=False): """Helper function to remove monomials from the basis.""" if is_number_type(monomial): return monomial original_monomial = monomial changed = True if not pure: substitutions = monomial_substitutions else: ...
Experimental fast substitution routine that considers only restricted cases of noncommutative algebras. In rare cases it fails to find a substitution. Use it with proper testing.
def fast_substitute(monomial, old_sub, new_sub): """Experimental fast substitution routine that considers only restricted cases of noncommutative algebras. In rare cases, it fails to find a substitution. Use it with proper testing. :param monomial: The monomial with parts need to be substituted. :p...
Generates a number of commutative or noncommutative variables
def generate_variables(name, n_vars=1, hermitian=None, commutative=True): """Generates a number of commutative or noncommutative variables :param name: The prefix in the symbolic representation of the noncommuting variables. This will be suffixed by a number from 0 to n_vars-1...
Generates a number of commutative or noncommutative operators
def generate_operators(name, n_vars=1, hermitian=None, commutative=False): """Generates a number of commutative or noncommutative operators :param name: The prefix in the symbolic representation of the noncommuting variables. This will be suffixed by a number from 0 to n_vars-...
Generates all noncommutative monomials up to a degree
def get_monomials(variables, degree): """Generates all noncommutative monomials up to a degree :param variables: The noncommutative variables to generate monomials from :type variables: list of :class:`sympy.physics.quantum.operator.Operator` or :class:`sympy.physi...
Returns the degree of a noncommutative polynomial.
def ncdegree(polynomial): """Returns the degree of a noncommutative polynomial. :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: int -- the degree of the polynomial. """ degree = 0 if is_number_type(polynomial): ret...
Returns whether the polynomial has complex coefficients
def iscomplex(polynomial): """Returns whether the polynomial has complex coefficients :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: bool -- whether there is a complex coefficient. """ if isinstance(polynomial, (int, float)):...
Return the monomials of a certain degree.
def get_all_monomials(variables, extramonomials, substitutions, degree, removesubstitutions=True): """Return the monomials of a certain degree. """ monomials = get_monomials(variables, degree) if extramonomials is not None: monomials.extend(extramonomials) if removesubs...
Collect monomials up to a given degree.
def pick_monomials_up_to_degree(monomials, degree): """Collect monomials up to a given degree. """ ordered_monomials = [] if degree >= 0: ordered_monomials.append(S.One) for deg in range(1, degree + 1): ordered_monomials.extend(pick_monomials_of_degree(monomials, deg)) return ord...
Collect all monomials up of a given degree.
def pick_monomials_of_degree(monomials, degree): """Collect all monomials up of a given degree. """ selected_monomials = [] for monomial in monomials: if ncdegree(monomial) == degree: selected_monomials.append(monomial) return selected_monomials
Save a monomial dictionary for debugging purposes.
def save_monomial_index(filename, monomial_index): """Save a monomial dictionary for debugging purposes. :param filename: The name of the file to save to. :type filename: str. :param monomial_index: The monomial index of the SDP relaxation. :type monomial_index: dict of :class:`sympy.core.expr.Expr...
Helper function to include only unique monomials in a basis.
def unique(seq): """Helper function to include only unique monomials in a basis.""" seen = {} result = [] for item in seq: marker = item if marker in seen: continue seen[marker] = 1 result.append(item) return result
Build a permutation matrix for a permutation.
def build_permutation_matrix(permutation): """Build a permutation matrix for a permutation. """ matrix = lil_matrix((len(permutation), len(permutation))) column = 0 for row in permutation: matrix[row, column] = 1 column += 1 return matrix
Convert all inequalities to > = 0 form.
def convert_relational(relational): """Convert all inequalities to >=0 form. """ rel = relational.rel_op if rel in ['==', '>=', '>']: return relational.lhs-relational.rhs elif rel in ['<=', '<']: return relational.rhs-relational.lhs else: raise Exception("The relational o...
Returns the value of a board >>> b = Board () ; b. _rows = [[ x x x ] [ x x x ] [ x x x ]] >>> value ( b ) 1 >>> b = Board () ; b. _rows = [[ o o o ] [ o o o ] [ o o o ]] >>> value ( b ) - 1 >>> b = Board () ; b. _rows = [[ x o ] [ x o ] [ ]] >>> value ( b ) 1 >>> b. _rows [ 0 ] [ 2 ] = x >>> value ( b ) - 1
def value(board, who='x'): """Returns the value of a board >>> b = Board(); b._rows = [['x', 'x', 'x'], ['x', 'x', 'x'], ['x', 'x', 'x']] >>> value(b) 1 >>> b = Board(); b._rows = [['o', 'o', 'o'], ['o', 'o', 'o'], ['o', 'o', 'o']] >>> value(b) -1 >>> b = Board(); b._rows = [['x', 'o', '...
Returns best next board
def ai(board, who='x'): """ Returns best next board >>> b = Board(); b._rows = [['x', 'o', ' '], ['x', 'o', ' '], [' ', ' ', ' ']] >>> ai(b) < Board |xo.xo.x..| > """ return sorted(board.possible(), key=lambda b: value(b, who))[-1]
Returns either x or o if one of them won otherwise None
def winner(self): """Returns either x or o if one of them won, otherwise None""" for c in 'xo': for comb in [(0,3,6), (1,4,7), (2,5,8), (0,1,2), (3,4,5), (6,7,8), (0,4,8), (2,4,6)]: if all(self.spots[p] == c for p in comb): return c return None
Get the sparse SDP relaxation of a Bell inequality.
def get_relaxation(self, A_configuration, B_configuration, I): """Get the sparse SDP relaxation of a Bell inequality. :param A_configuration: The definition of measurements of Alice. :type A_configuration: list of list of int. :param B_configuration: The definition of measurements of Bo...
Returns list of users track has been shared with. Either track or url need to be provided.
def share(track_id=None, url=None, users=None): """ Returns list of users track has been shared with. Either track or url need to be provided. """ client = get_client() if url: track_id = client.get('/resolve', url=url).id if not users: return client.get('/tracks/%d/permis...
Helper function to convert the SDP problem to PICOS and call CVXOPT solver and parse the output.
def solve_with_cvxopt(sdp, solverparameters=None): """Helper function to convert the SDP problem to PICOS and call CVXOPT solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. """ P = convert_to_picos(sdp) P.set_option("solver", "cvxo...
Convert an SDP relaxation to a PICOS problem such that the exported. dat - s file is extremely sparse there is not penalty imposed in terms of SDP variables or number of constraints. This conversion can be used for imposing extra constraints on the moment matrix such as partial transpose.
def convert_to_picos(sdp, duplicate_moment_matrix=False): """Convert an SDP relaxation to a PICOS problem such that the exported .dat-s file is extremely sparse, there is not penalty imposed in terms of SDP variables or number of constraints. This conversion can be used for imposing extra constraints on...
Helper function to convert the SDP problem to CVXPY and call the solver and parse the output.
def solve_with_cvxpy(sdp, solverparameters=None): """Helper function to convert the SDP problem to CVXPY and call the solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. """ problem = convert_to_cvxpy(sdp) if solverparameters is not...
Convert an SDP relaxation to a CVXPY problem.
def convert_to_cvxpy(sdp): """Convert an SDP relaxation to a CVXPY problem. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`cvxpy.Problem`. """ from cvxpy import Minimize, Problem, Variable row_offsets = [0] cumulative_sum = 0 for bl...
Get the forward neighbors of a site in a lattice.
def get_neighbors(index, lattice_length, width=0, periodic=False): """Get the forward neighbors of a site in a lattice. :param index: Linear index of operator. :type index: int. :param lattice_length: The size of the 2D lattice in either dimension :type lattice_length: int. :param width: Option...
Get the forward neighbors at a given distance of a site or set of sites in a lattice.
def get_next_neighbors(indices, lattice_length, width=0, distance=1, periodic=False): """Get the forward neighbors at a given distance of a site or set of sites in a lattice. :param index: Linear index of operator. :type index: int. :param lattice_length: The size of the 2D l...
Return a set of constraints that define fermionic ladder operators.
def bosonic_constraints(a): """Return a set of constraints that define fermionic ladder operators. :param a: The non-Hermitian variables. :type a: list of :class:`sympy.physics.quantum.operator.Operator`. :returns: a dict of substitutions. """ substitutions = {} for i, ai in enumerate(a): ...
Return a set of constraints that define fermionic ladder operators.
def fermionic_constraints(a): """Return a set of constraints that define fermionic ladder operators. :param a: The non-Hermitian variables. :type a: list of :class:`sympy.physics.quantum.operator.Operator`. :returns: a dict of substitutions. """ substitutions = {} for i, ai in enumerate(a)...
Return a set of constraints that define Pauli spin operators.
def pauli_constraints(X, Y, Z): """Return a set of constraints that define Pauli spin operators. :param X: List of Pauli X operator on sites. :type X: list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param Y: List of Pauli Y operator on sites. :type Y: list of :class:`sympy.phys...
Generate variables that behave like measurements.
def generate_measurements(party, label): """Generate variables that behave like measurements. :param party: The list of number of measurement outputs a party has. :type party: list of int. :param label: The label to be given to the symbolic variables. :type label: str. :returns: list of list o...
Return a set of constraints that define projective measurements.
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...
Define a polynomial using measurements and an I matrix describing a Bell inequality.
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...
Correlators between the probabilities of two parties.
def correlator(A, B): """Correlators between the probabilities of two parties. :param A: Measurements of Alice. :type A: list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param B: Measurements of Bob. :type B: list of list of :class:`sympy.physics...
Get the maximum violation of a two - party Bell inequality.
def maximum_violation(A_configuration, B_configuration, I, level, extra=None): """Get the maximum violation of a two-party Bell inequality. :param A_configuration: Measurement settings of Alice. :type A_configuration: list of int. :param B_configuration: Measurement settings of Bob. :type B_configu...
A sorted python2/ 3 stable formatting of a dictionary.
def stable_format_dict(d): """A sorted, python2/3 stable formatting of a dictionary. Does not work for dicts with unicode strings as values.""" inner = ', '.join('{}: {}'.format(repr(k)[1:] if repr(k).startswith(u"u'") or repr(k).startswith(u'u"') ...
Returns by how much two intervals overlap
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...
>>> width_aware_slice ( u a \ uff25iou 0 2 ) [ 1 ] == u True
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_chunk_chars = [] for char, char_start, char_...
Returns a list of lines split on the last possible space of each line.
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 be the color of the first whitespace character of the ...
Fill in the Nones in a slice.
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,...
Returns a kwargs dictionary by turning args into kwargs
def parse_args(args, kwargs): """Returns a kwargs dictionary by turning args into 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(args...
Convenience function for creating a FmtStr
def fmtstr(string, *args, **kwargs): # type: (Union[Text, bytes, FmtStr], *Any, **Any) -> FmtStr """ Convenience function for creating a FmtStr >>> fmtstr('asdf', 'blue', 'on_red', 'bold') on_red(bold(blue('asdf'))) >>> fmtstr('blarg', fg='blue', bg='red', bold=True) on_red(bold(blue('blarg...
Return an escape - coded string to write to the terminal.
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...
FmtStr repr is build by concatenating these.
def repr_part(self): """FmtStr repr is build by concatenating these.""" 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 (...
Requests a sub - chunk of max_width or shorter. Returns None if no chunks left.
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) ...
r Return a FmtStr representing input.
def from_str(cls, s): # type: (Union[Text, bytes]) -> FmtStr r""" Return a FmtStr representing input. The str() of a FmtStr is guaranteed to produced the same FmtStr. Other input with escape sequences may not be preserved. >>> fmtstr("|"+fmtstr("hey", fg='red', bg='blue...
Copies the current FmtStr s attributes while changing its string.
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...
Shim for easily converting old __setitem__ calls
def setitem(self, startindex, fs): """Shim for easily converting old __setitem__ calls""" return self.setslice_with_length(startindex, startindex+1, fs, len(self))
Shim for easily converting old __setitem__ calls
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)) ...
Returns a new FmtStr with the input string spliced into the the original FmtStr at start and end. If end is provided new_str will replace the substring self. s [ start: end - 1 ].
def splice(self, new_str, start, end=None): """Returns a new FmtStr with the input string spliced into the the original FmtStr at start and end. If end is provided, new_str will replace the substring self.s[start:end-1]. """ if len(new_str) == 0: return self n...
Returns a new FmtStr with the same content but new formatting
def copy_with_new_atts(self, **attributes): """Returns a new FmtStr with the same content but new formatting""" return FmtStr(*[Chunk(bfs.s, bfs.atts.extend(attributes)) for bfs in self.chunks])
Joins an iterable yielding strings or FmtStrs with self as separator
def join(self, iterable): """Joins an iterable yielding strings or FmtStrs with self as separator""" before = [] chunks = [] for i, s in enumerate(iterable): chunks.extend(before) before = self.chunks if isinstance(s, FmtStr): chunks.ex...
Split based on seperator optionally using a regex
def split(self, sep=None, maxsplit=None, regex=False): """Split based on seperator, optionally using a regex Capture groups are ignored in regex, the whole pattern is matched and used to split the original FmtStr.""" if maxsplit is not None: raise NotImplementedError('no max...
Return a list of lines split on newline characters include line boundaries if keepends is true.
def splitlines(self, keepends=False): """Return a list of lines, split on newline characters, include line boundaries, if keepends is true.""" lines = self.split('\n') return [line+'\n' for line in lines] if keepends else ( lines if lines[-1] else lines[:-1])
S. ljust ( width [ fillchar ] ) - > string
def ljust(self, width, fillchar=None): """S.ljust(width[, fillchar]) -> string If a fillchar is provided, less formatting information will be preserved """ if fillchar is not None: return fmtstr(self.s.ljust(width, fillchar), **self.shared_atts) to_add = ' ' * (width...
The number of columns it would take to display this string
def width(self): """The number of columns it would take to display this string""" if self._width is not None: return self._width self._width = sum(fs.width for fs in self.chunks) return self._width
Returns the horizontal position of character n of the string
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
Gets atts shared among all nonzero length component Chunk
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...
Returns a new FmtStr with the same content but some attributes removed
def new_with_atts_removed(self, *attributes): """Returns a new FmtStr with the same content but some attributes removed""" return FmtStr(*[Chunk(bfs.s, bfs.atts.remove(*attributes)) for bfs in self.chunks])
List of indices of divisions between the constituent chunks.
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
Slice based on the number of columns it would take to display the substring.
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 = [] ...
Split into lines pushing doublewidth characters at the end of a line to the next line.
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 ...
Builds the more compact fmtstrs by using fromstr ( of the control sequences )
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...
Calculates the block_struct array for the output file.
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the outp...
Ideally we shouldn t lose the first second of events
def main(): """Ideally we shouldn't lose the first second of events""" time.sleep(1) with Input() as input_generator: for e in input_generator: print(repr(e))
Process a single monomial when building the moment matrix.
def _process_monomial(self, monomial, n_vars): """Process a single monomial when building the moment matrix. """ coeff, monomial = monomial.as_coeff_Mul() k = 0 # Have we seen this monomial before? conjugate = False try: # If yes, then we improve spars...
Return dense vector representation of a polynomial. This function is nearly identical to __push_facvar_sparse but instead of pushing sparse entries to the constraint matrices it returns a dense vector.
def __get_trace_facvar(self, polynomial): """Return dense vector representation of a polynomial. This function is nearly identical to __push_facvar_sparse, but instead of pushing sparse entries to the constraint matrices, it returns a dense vector. """ facvar = [0] * (sel...
Set or change the objective function of the polynomial optimization problem.
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 ...
Calculates the block_struct array for the output file.
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the outp...
Write the relaxation to a file.
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...
There s a bug in Python3. 4 + see http:// bugs. python. org/ issue23773 remove this and use sys. _getframe ( 3 ) when bug is fixed
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...
template function of public api
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)
r Returns a list of strings or format dictionaries to describe the strings.
def parse(s): r""" Returns a list of strings or format dictionaries to describe the strings. May raise a ValueError if it can't be parsed. >>> parse(">>> []") ['>>> []'] >>> #parse("\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\...
r Returns processed text the next token and unprocessed text
def peel_off_esc_code(s): r"""Returns processed text, the next token, and unprocessed text >>> front, d, rest = peel_off_esc_code('somestuff') >>> front, rest ('some', 'stuff') >>> d == {'numbers': [2], 'command': 'A', 'intermed': '', 'private': '', 'csi': '\x1b[', 'seq': '\x1b[2A'} True ...
Return key pressed from bytes_ or None
def get_key(bytes_, encoding, keynames='curtsies', full=False): """Return key pressed from bytes_ or None Return a key name or None meaning it's an incomplete sequence of bytes (more bytes needed to determine the key pressed) encoding is how the bytes should be translated to unicode - it should ma...
Whether seq bytes might create a char in encoding if more bytes were added
def could_be_unfinished_char(seq, encoding): """Whether seq bytes might create a char in encoding if more bytes were added""" if decodable(seq, encoding): return False # any sensible encoding surely doesn't require lookahead (right?) # (if seq bytes encoding a character, adding another byte shou...
Returns pretty representation of an Event or keypress
def pp_event(seq): """Returns pretty representation of an Event or keypress""" 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 CURTS...
Return a string of random nouns up to max number
def create_nouns(max=2): """ Return a string of random nouns up to max number """ nouns = [] for noun in range(0, max): nouns.append(random.choice(noun_list)) return " ".join(nouns)
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
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 = ...
Create a random birthday fomr someone between the ages of min_age and max_age
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...
Create a random password From Stackoverflow: http:// stackoverflow. com/ questions/ 7479442/ high - quality - simple - random - password - generator
def create_pw(length=8, digits=2, upper=2, lower=2): """Create a random password From Stackoverflow: http://stackoverflow.com/questions/7479442/high-quality-simple-random-password-generator Create a random password with the specified length and no. of digit, upper and lower case letters. :para...
Run through some simple examples
def show_examples(): """ Run through some simple 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)) print(phone) ...
MOSEK requires a specific sparse format to define the lower - triangular part of a symmetric matrix. This function does the conversion from the sparse upper triangular matrix format of Ncpol2SDPA.
def convert_to_mosek_index(block_struct, row_offsets, block_offsets, row): """MOSEK requires a specific sparse format to define the lower-triangular part of a symmetric matrix. This function does the conversion from the sparse upper triangular matrix format of Ncpol2SDPA. """ block_index, i, j = con...
Converts the entire sparse representation of the Fi constraint matrices to sparse MOSEK matrices.
def convert_to_mosek_matrix(sdp): """Converts the entire sparse representation of the Fi constraint matrices to sparse MOSEK matrices. """ barci = [] barcj = [] barcval = [] barai = [] baraj = [] baraval = [] for k in range(sdp.n_vars): barai.append([]) baraj.appe...
Convert an SDP relaxation to a MOSEK task.
def convert_to_mosek(sdp): """Convert an SDP relaxation to a MOSEK task. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`mosek.Task`. """ import mosek # Cheat when variables are complex and convert with PICOS if sdp.complex_matrix: ...
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.
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...
Return version string.
def version(): """Return version string.""" with open(os.path.join('curtsies', '__init__.py')) as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s
fsarray ( list_of_FmtStrs_or_strings width = None ) - > FSArray
def fsarray(strings, *args, **kwargs): """fsarray(list_of_FmtStrs_or_strings, width=None) -> FSArray Returns a new FSArray of width of the maximum size of the provided strings, or width provided, and height of the number of strings provided. If a width is provided, raises a ValueError if any of the str...
Returns two FSArrays with differences underlined
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(...
create new order function: param rate: float: param amount: float: param order_type: str ; set buy or sell: param pair: str ; set btc_jpy
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() payload = { 'rate': rate, ...
cancel the specified order: param order_id: order_id to be canceled
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.access_key,secret_key=self.secret_key) r = requests.delete(url,hea...