idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
62,700
def edit_secondary_name_server ( self , zone_name , primary = None , backup = None , second_backup = None ) : name_server_info = { } if primary is not None : name_server_info [ 'nameServerIp1' ] = { 'ip' : primary } if backup is not None : name_server_info [ 'nameServerIp2' ] = { 'ip' : backup } if second_backup is not...
Edit the axfr name servers of a secondary zone .
62,701
def get_rrsets ( self , zone_name , q = None , ** kwargs ) : uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params ( q , kwargs ) return self . rest_api_connection . get ( uri , params )
Returns the list of RRSets in the specified zone .
62,702
def create_rrset ( self , zone_name , rtype , owner_name , ttl , rdata ) : if type ( rdata ) is not list : rdata = [ rdata ] rrset = { "ttl" : ttl , "rdata" : rdata } return self . rest_api_connection . post ( "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name , json . dumps ( rrset ) )
Creates a new RRSet in the specified zone .
62,703
def edit_rrset ( self , zone_name , rtype , owner_name , ttl , rdata , profile = None ) : if type ( rdata ) is not list : rdata = [ rdata ] rrset = { "ttl" : ttl , "rdata" : rdata } if profile : rrset [ "profile" ] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self . rest_api_c...
Updates an existing RRSet in the specified zone .
62,704
def edit_rrset_rdata ( self , zone_name , rtype , owner_name , rdata , profile = None ) : if type ( rdata ) is not list : rdata = [ rdata ] rrset = { "rdata" : rdata } method = "patch" if profile : rrset [ "profile" ] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return...
Updates an existing RRSet s Rdata in the specified zone .
62,705
def delete_rrset ( self , zone_name , rtype , owner_name ) : return self . rest_api_connection . delete ( "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name )
Deletes an RRSet .
62,706
def create_web_forward ( self , zone_name , request_to , redirect_to , forward_type ) : web_forward = { "requestTo" : request_to , "defaultRedirectTo" : redirect_to , "defaultForwardType" : forward_type } return self . rest_api_connection . post ( "/v1/zones/" + zone_name + "/webforwards" , json . dumps ( web_forward )...
Create a web forward record .
62,707
def create_sb_pool ( self , zone_name , owner_name , ttl , pool_info , rdata_info , backup_record_list ) : rrset = self . _build_sb_rrset ( backup_record_list , pool_info , rdata_info , ttl ) return self . rest_api_connection . post ( "/v1/zones/" + zone_name + "/rrsets/A/" + owner_name , json . dumps ( rrset ) )
Creates a new SB Pool .
62,708
def create_tc_pool ( self , zone_name , owner_name , ttl , pool_info , rdata_info , backup_record ) : rrset = self . _build_tc_rrset ( backup_record , pool_info , rdata_info , ttl ) return self . rest_api_connection . post ( "/v1/zones/" + zone_name + "/rrsets/A/" + owner_name , json . dumps ( rrset ) )
Creates a new TC Pool .
62,709
def remove ( self , other ) : if other is FullSpace : return TrivialSpace if other is TrivialSpace : return self if isinstance ( other , ProductSpace ) : oops = set ( other . operands ) else : oops = { other } return ProductSpace . create ( * sorted ( set ( self . operands ) . difference ( oops ) ) )
Remove a particular factor from a tensor product space .
62,710
def intersect ( self , other ) : if other is FullSpace : return self if other is TrivialSpace : return TrivialSpace if isinstance ( other , ProductSpace ) : other_ops = set ( other . operands ) else : other_ops = { other } return ProductSpace . create ( * sorted ( set ( self . operands ) . intersection ( other_ops ) ) ...
Find the mutual tensor factors of two Hilbert spaces .
62,711
def _isinstance ( expr , classname ) : for cls in type ( expr ) . __mro__ : if cls . __name__ == classname : return True return False
Check whether expr is an instance of the class with name classname
62,712
def decompose_space ( H , A ) : return OperatorTrace . create ( OperatorTrace . create ( A , over_space = H . operands [ - 1 ] ) , over_space = ProductSpace . create ( * H . operands [ : - 1 ] ) )
Simplifies OperatorTrace expressions over tensor - product spaces by turning it into iterated partial traces .
62,713
def factor_coeff ( cls , ops , kwargs ) : coeffs , nops = zip ( * map ( _coeff_term , ops ) ) coeff = 1 for c in coeffs : coeff *= c if coeff == 1 : return nops , coeffs else : return coeff * cls . create ( * nops , ** kwargs )
Factor out coefficients of all factors .
62,714
def doit ( self , classes = None , recursive = True , ** kwargs ) : return super ( ) . doit ( classes , recursive , ** kwargs )
Write out commutator
62,715
def _attrprint ( d , delimiter = ', ' ) : return delimiter . join ( ( '"%s"="%s"' % item ) for item in sorted ( d . items ( ) ) )
Print a dictionary of attributes in the DOT format
62,716
def _styleof ( expr , styles ) : style = dict ( ) for expr_filter , sty in styles : if expr_filter ( expr ) : style . update ( sty ) return style
Merge style dictionaries in order
62,717
def _git_version ( ) : import subprocess import os def _minimal_ext_cmd ( cmd ) : env = { } for k in [ 'SYSTEMROOT' , 'PATH' ] : v = os . environ . get ( k ) if v is not None : env [ k ] = v env [ 'LANGUAGE' ] = 'C' env [ 'LANG' ] = 'C' env [ 'LC_ALL' ] = 'C' FNULL = open ( os . devnull , 'w' ) cwd = os . path . dirnam...
If installed with pip installe - e . from inside a git repo the current git revision as a string
62,718
def pad_with_identity ( circuit , k , n ) : circuit_n = circuit . cdim combined_circuit = circuit + circuit_identity ( n ) permutation = ( list ( range ( k ) ) + list ( range ( circuit_n , circuit_n + n ) ) + list ( range ( k , circuit_n ) ) ) return ( CPermutation . create ( invert_permutation ( permutation ) ) << com...
Pad a circuit by adding a n - channel identity circuit at index k
62,719
def move_drive_to_H ( slh , which = None , expand_simplify = True ) : r if which is None : which = [ ] scalarcs = [ ] for jj , L in enumerate ( slh . Ls ) : if not which or jj in which : scalarcs . append ( - get_coeffs ( L . expand ( ) ) [ IdentityOperator ] ) else : scalarcs . append ( 0 ) if np . all ( np . array ( ...
r Move coherent drives from the Lindblad operators to the Hamiltonian .
62,720
def prepare_adiabatic_limit ( slh , k = None ) : if k is None : k = symbols ( 'k' , positive = True ) Ld = slh . L . dag ( ) LdL = ( Ld * slh . L ) [ 0 , 0 ] K = ( - LdL / 2 + I * slh . H ) . expand ( ) . simplify_scalar ( ) N = slh . S . dag ( ) B , A , Y = K . series_expand ( k , 0 , 2 ) G , F = Ld . series_expand ( ...
Prepare the adiabatic elimination on an SLH object
62,721
def eval_adiabatic_limit ( YABFGN , Ytilde , P0 ) : Y , A , B , F , G , N = YABFGN Klim = ( P0 * ( B - A * Ytilde * A ) * P0 ) . expand ( ) . simplify_scalar ( ) Hlim = ( ( Klim - Klim . dag ( ) ) / 2 / I ) . expand ( ) . simplify_scalar ( ) Ldlim = ( P0 * ( G - A * Ytilde * F ) * P0 ) . expand ( ) . simplify_scalar ( ...
Compute the limiting SLH model for the adiabatic approximation
62,722
def try_adiabatic_elimination ( slh , k = None , fock_trunc = 6 , sub_P0 = True ) : ops = prepare_adiabatic_limit ( slh , k ) Y = ops [ 0 ] if isinstance ( Y . space , LocalSpace ) : try : b = Y . space . basis_labels if len ( b ) > fock_trunc : b = b [ : fock_trunc ] except BasisNotSetError : b = range ( fock_trunc ) ...
Attempt to automatically do adiabatic elimination on an SLH object
62,723
def index_in_block ( self , channel_index : int ) -> int : if channel_index < 0 or channel_index >= self . cdim : raise ValueError ( ) struct = self . block_structure if len ( struct ) == 1 : return channel_index , 0 i = 1 while sum ( struct [ : i ] ) <= channel_index and i < self . cdim : i += 1 block_index = i - 1 in...
Return the index a channel has within the subblock it belongs to
62,724
def get_blocks ( self , block_structure = None ) : if block_structure is None : block_structure = self . block_structure try : return self . _get_blocks ( block_structure ) except IncompatibleBlockStructures as e : raise e
For a reducible circuit get a sequence of subblocks that when concatenated again yield the original circuit . The block structure given has to be compatible with the circuits actual block structure i . e . it can only be more coarse - grained .
62,725
def show ( self ) : from IPython . display import Image , display fname = self . render ( ) display ( Image ( filename = fname ) )
Show the circuit expression in an IPython notebook .
62,726
def render ( self , fname = '' ) : import qnet . visualization . circuit_pyx as circuit_visualization from tempfile import gettempdir from time import time , sleep if not fname : tmp_dir = gettempdir ( ) fname = os . path . join ( tmp_dir , "tmp_{}.png" . format ( hash ( time ) ) ) if circuit_visualization . draw_circu...
Render the circuit expression and store the result in a file
62,727
def space ( self ) : args_spaces = ( self . S . space , self . L . space , self . H . space ) return ProductSpace . create ( * args_spaces )
Total Hilbert space
62,728
def free_symbols ( self ) : return set . union ( self . S . free_symbols , self . L . free_symbols , self . H . free_symbols )
Set of all symbols occcuring in S L or H
62,729
def expand ( self ) : return SLH ( self . S . expand ( ) , self . L . expand ( ) , self . H . expand ( ) )
Expand out all operator expressions within S L and H
62,730
def simplify_scalar ( self , func = sympy . simplify ) : return SLH ( self . S . simplify_scalar ( func = func ) , self . L . simplify_scalar ( func = func ) , self . H . simplify_scalar ( func = func ) )
Simplify all scalar expressions within S L and H
62,731
def symbolic_master_equation ( self , rho = None ) : L , H = self . L , self . H if rho is None : rho = OperatorSymbol ( 'rho' , hs = self . space ) return ( - I * ( H * rho - rho * H ) + sum ( Lk * rho * adjoint ( Lk ) - ( adjoint ( Lk ) * Lk * rho + rho * adjoint ( Lk ) * Lk ) / 2 for Lk in L . matrix . ravel ( ) ) )
Compute the symbolic Liouvillian acting on a state rho
62,732
def symbolic_heisenberg_eom ( self , X = None , noises = None , expand_simplify = True ) : L , H = self . L , self . H if X is None : X = OperatorSymbol ( 'X' , hs = ( L . space | H . space ) ) summands = [ I * ( H * X - X * H ) , ] for Lk in L . matrix . ravel ( ) : summands . append ( adjoint ( Lk ) * X * Lk ) summan...
Compute the symbolic Heisenberg equations of motion of a system operator X . If no X is given an OperatorSymbol is created in its place . If no noises are given this correspnds to the ensemble - averaged Heisenberg equation of motion .
62,733
def block_perms ( self ) : if not self . _block_perms : self . _block_perms = permutation_to_block_permutations ( self . permutation ) return self . _block_perms
If the circuit is reducible into permutations within subranges of the full range of channels this yields a tuple with the internal permutations for each such block .
62,734
def series_with_permutation ( self , other ) : combined_permutation = tuple ( [ self . permutation [ p ] for p in other . permutation ] ) return CPermutation . create ( combined_permutation )
Compute the series product with another channel permutation circuit
62,735
def save ( self , data , chart_type , options = None , filename = 'chart' , w = 800 , h = 420 , overwrite = True ) : html = self . render ( data = data , chart_type = chart_type , options = options , div_id = filename , head = self . head , w = w , h = h ) if overwrite : with open ( filename . replace ( " " , "_" ) + '...
Save the rendered html to a file in the same directory as the notebook .
62,736
def _unicode_sub_super ( string , mapping , max_len = None ) : string = str ( string ) if string . startswith ( '(' ) and string . endswith ( ')' ) : len_string = len ( string ) - 2 else : len_string = len ( string ) if max_len is not None : if len_string > max_len : raise KeyError ( "max_len exceeded" ) unicode_letter...
Try to render a subscript or superscript string in unicode fall back on ascii if this is not possible
62,737
def _translate_symbols ( string ) : res = [ ] string = str ( string ) for s in re . split ( r'(\W+)' , string , flags = re . UNICODE ) : tex_str = _GREEK_DICTIONARY . get ( s ) if tex_str : res . append ( tex_str ) elif s . lower ( ) in _GREEK_DICTIONARY : res . append ( _GREEK_DICTIONARY [ s ] ) else : res . append ( ...
Given a description of a Greek letter or other special character return the appropriate unicode letter .
62,738
def plot_and_save ( self , data , w = 800 , h = 420 , filename = 'chart' , overwrite = True ) : self . save ( data , filename , overwrite ) return IFrame ( filename + '.html' , w , h )
Save the rendered html to a file and returns an IFrame to display the plot in the notebook .
62,739
def _get_from_cache ( self , expr ) : is_cached , res = super ( ) . _get_from_cache ( expr ) if is_cached : indent_str = " " * self . _print_level return True , indent ( res , indent_str ) else : return False , None
Obtain cached result prepend with the keyname if necessary and indent for the current level
62,740
def _write_to_cache ( self , expr , res ) : res = dedent ( res ) super ( ) . _write_to_cache ( expr , res )
Store the cached result without indentation and without the keyname
62,741
def _translate_symbols ( string ) : res = [ ] for s in re . split ( r'([,.:\s=]+)' , string ) : tex_str = _TEX_GREEK_DICTIONARY . get ( s ) if tex_str : res . append ( tex_str ) elif s . lower ( ) in greek_letters_set : res . append ( "\\" + s . lower ( ) ) elif s in other_symbols : res . append ( "\\" + s ) else : if ...
Given a description of a Greek letter or other special character return the appropriate latex .
62,742
def _render_str ( self , string ) : if isinstance ( string , StrLabel ) : string = string . _render ( string . expr ) string = str ( string ) if len ( string ) == 0 : return '' name , supers , subs = split_super_sub ( string ) return render_latex_sub_super ( name , subs , supers , translate_symbols = True )
Returned a texified version of the string
62,743
def is_symbol ( string ) : return ( is_int ( string ) or is_float ( string ) or is_constant ( string ) or is_unary ( string ) or is_binary ( string ) or ( string == '(' ) or ( string == ')' ) )
Return true if the string is a mathematical symbol .
62,744
def find_word_groups ( string , words ) : scale_pattern = '|' . join ( words ) regex = re . compile ( r'(?:(?:\d+)\s+(?:' + scale_pattern + r')*\s*)+(?:\d+|' + scale_pattern + r')+' ) result = regex . findall ( string ) return result
Find matches for words in the format 3 thousand 6 hundred 2 . The words parameter should be the list of words to check for such as hundred .
62,745
def replace_word_tokens ( string , language ) : words = mathwords . word_groups_for_language ( language ) operators = words [ 'binary_operators' ] . copy ( ) if 'unary_operators' in words : operators . update ( words [ 'unary_operators' ] ) for operator in list ( operators . keys ( ) ) : if operator in string : string ...
Given a string and an ISO 639 - 2 language code return the string with the words replaced with an operational equivalent .
62,746
def to_postfix ( tokens ) : precedence = { '/' : 4 , '*' : 4 , '+' : 3 , '-' : 3 , '^' : 2 , '(' : 1 } postfix = [ ] opstack = [ ] for token in tokens : if is_int ( token ) : postfix . append ( int ( token ) ) elif is_float ( token ) : postfix . append ( float ( token ) ) elif token in mathwords . CONSTANTS : postfix ....
Convert a list of evaluatable tokens to postfix format .
62,747
def evaluate_postfix ( tokens ) : stack = [ ] for token in tokens : total = None if is_int ( token ) or is_float ( token ) or is_constant ( token ) : stack . append ( token ) elif is_unary ( token ) : a = stack . pop ( ) total = mathwords . UNARY_FUNCTIONS [ token ] ( a ) elif len ( stack ) : b = stack . pop ( ) a = st...
Given a list of evaluatable tokens in postfix format calculate a solution .
62,748
def tokenize ( string , language = None , escape = ' ' ) : string = string . lower ( ) if len ( string ) and not string [ - 1 ] . isalnum ( ) : character = string [ - 1 ] string = string [ : - 1 ] + ' ' + character string = string . replace ( '(' , ' ( ' ) string = string . replace ( ')' , ' ) ' ) if language : words =...
Given a string return a list of math symbol tokens
62,749
def parse ( string , language = None ) : if language : string = replace_word_tokens ( string , language ) tokens = tokenize ( string ) postfix = to_postfix ( tokens ) return evaluate_postfix ( postfix )
Return a solution to the equation in the input string .
62,750
def expr_order_key ( expr ) : if hasattr ( expr , '_order_key' ) : return expr . _order_key try : if isinstance ( expr . kwargs , OrderedDict ) : key_vals = expr . kwargs . values ( ) else : key_vals = [ expr . kwargs [ key ] for key in sorted ( expr . kwargs ) ] return KeyTuple ( ( expr . __class__ . __name__ , ) + tu...
A default order key for arbitrary expressions
62,751
def Sum ( idx , * args , ** kwargs ) : from qnet . algebra . core . hilbert_space_algebra import LocalSpace from qnet . algebra . core . scalar_algebra import ScalarValue from qnet . algebra . library . spin_algebra import SpinSpace dispatch_table = { tuple ( ) : _sum_over_fockspace , ( LocalSpace , ) : _sum_over_focks...
Instantiator for an arbitrary indexed sum .
62,752
def diff ( self , sym : Symbol , n : int = 1 , expand_simplify : bool = True ) : if not isinstance ( sym , sympy . Basic ) : raise TypeError ( "%s needs to be a Sympy symbol" % sym ) if sym . free_symbols . issubset ( self . free_symbols ) : deriv = QuantumDerivative . create ( self , derivs = { sym : n } , vals = None...
Differentiate by scalar parameter sym .
62,753
def series_expand ( self , param : Symbol , about , order : int ) -> tuple : r expansion = self . _series_expand ( param , about , order ) res = [ ] for v in expansion : if v == 0 or v . is_zero : v = self . _zero elif v == 1 : v = self . _one assert isinstance ( v , self . _base_cls ) res . append ( v ) return tuple (...
r Expand the expression as a truncated power series in a scalar parameter .
62,754
def factor_for_space ( self , spc ) : if spc == TrivialSpace : ops_on_spc = [ o for o in self . operands if o . space is TrivialSpace ] ops_not_on_spc = [ o for o in self . operands if o . space > TrivialSpace ] else : ops_on_spc = [ o for o in self . operands if ( o . space & spc ) > TrivialSpace ] ops_not_on_spc = [ ...
Return a tuple of two products where the first product contains the given Hilbert space and the second product is disjunct from it .
62,755
def evaluate_at ( self , vals ) : new_vals = self . _vals . copy ( ) new_vals . update ( vals ) return self . __class__ ( self . operand , derivs = self . _derivs , vals = new_vals )
Evaluate the derivative at a specific point
62,756
def bound_symbols ( self ) : if self . _bound_symbols is None : res = set ( ) self . _bound_symbols = res . union ( * [ sym . free_symbols for sym in self . _vals . keys ( ) ] ) return self . _bound_symbols
Set of Sympy symbols that are eliminated by evaluation .
62,757
def render_dot ( self , code , options , format , prefix = 'graphviz' ) : graphviz_dot = options . get ( 'graphviz_dot' , self . builder . config . graphviz_dot ) hashkey = ( code + str ( options ) + str ( graphviz_dot ) + str ( self . builder . config . graphviz_dot_args ) ) . encode ( 'utf-8' ) fname = '%s-%s.%s' % (...
Render graphviz code into a PNG or PDF output file .
62,758
def generate_clickable_map ( self ) : if self . clickable : return '\n' . join ( [ self . content [ 0 ] ] + self . clickable + [ self . content [ - 1 ] ] ) else : return ''
Generate clickable map tags if clickable item exists .
62,759
def next_basis_label_or_index ( self , label_or_index , n = 1 ) : if isinstance ( label_or_index , int ) : new_index = label_or_index + n if new_index < 0 : raise IndexError ( "index %d < 0" % new_index ) if new_index >= self . dimension : raise IndexError ( "index %d out of range for basis %s" % ( new_index , self . _...
Given the label or index of a basis state return the label the next basis state .
62,760
def texinfo_visit_inheritance_diagram ( self , node ) : graph = node [ 'graph' ] graph_hash = get_graph_hash ( node ) name = 'inheritance%s' % graph_hash dotcode = graph . generate_dot ( name , env = self . builder . env , graph_attrs = { 'size' : '"6.0,6.0"' } ) render_dot_texinfo ( self , node , dotcode , { } , 'inhe...
Output the graph for Texinfo . This will insert a PNG .
62,761
def class_name ( self , cls , parts = 0 , aliases = None ) : module = cls . __module__ if module in ( '__builtin__' , 'builtins' ) : fullname = cls . __name__ else : fullname = '%s.%s' % ( module , cls . __name__ ) if parts == 0 : result = fullname else : name_parts = fullname . split ( '.' ) result = '.' . join ( name...
Given a class object return a fully - qualified name .
62,762
def codemirror_settings_update ( configs , parameters , on = None , names = None ) : output = copy . deepcopy ( configs ) if names : output = { k : output [ k ] for k in names } if not on : on = output . keys ( ) for k in on : output [ k ] . update ( parameters ) return output
Return a new dictionnary of configs updated with given parameters .
62,763
def lhs ( self ) : lhs = self . _lhs i = 0 while lhs is None : i -= 1 lhs = self . _prev_lhs [ i ] return lhs
The left - hand - side of the equation
62,764
def set_tag ( self , tag ) : return Eq ( self . _lhs , self . _rhs , tag = tag , _prev_lhs = self . _prev_lhs , _prev_rhs = self . _prev_rhs , _prev_tags = self . _prev_tags )
Return a copy of the equation with a new tag
62,765
def apply ( self , func , * args , cont = False , tag = None , ** kwargs ) : new_lhs = func ( self . lhs , * args , ** kwargs ) if new_lhs == self . lhs and cont : new_lhs = None new_rhs = func ( self . rhs , * args , ** kwargs ) new_tag = tag return self . _update ( new_lhs , new_rhs , new_tag , cont )
Apply func to both sides of the equation
62,766
def apply_mtd ( self , mtd , * args , cont = False , tag = None , ** kwargs ) : new_lhs = getattr ( self . lhs , mtd ) ( * args , ** kwargs ) if new_lhs == self . lhs and cont : new_lhs = None new_rhs = getattr ( self . rhs , mtd ) ( * args , ** kwargs ) new_tag = tag return self . _update ( new_lhs , new_rhs , new_tag...
Call the method mtd on both sides of the equation
62,767
def substitute ( self , var_map , cont = False , tag = None ) : return self . apply ( substitute , var_map = var_map , cont = cont , tag = tag )
Substitute sub - expressions both on the lhs and rhs
62,768
def verify ( self , func = None , * args , ** kwargs ) : res = ( self . lhs . expand ( ) . simplify_scalar ( ) - self . rhs . expand ( ) . simplify_scalar ( ) ) if func is not None : return func ( res , * args , ** kwargs ) else : return res
Subtract the rhs from the lhs of the equation
62,769
def copy ( self ) : return Eq ( self . _lhs , self . _rhs , tag = self . _tag , _prev_lhs = self . _prev_lhs , _prev_rhs = self . _prev_rhs , _prev_tags = self . _prev_tags )
Return a copy of the equation
62,770
def free_symbols ( self ) : try : lhs_syms = self . lhs . free_symbols except AttributeError : lhs_syms = set ( ) try : rhs_syms = self . rhs . free_symbols except AttributeError : rhs_syms = set ( ) return lhs_syms | rhs_syms
Set of free SymPy symbols contained within the equation .
62,771
def bound_symbols ( self ) : try : lhs_syms = self . lhs . bound_symbols except AttributeError : lhs_syms = set ( ) try : rhs_syms = self . rhs . bound_symbols except AttributeError : rhs_syms = set ( ) return lhs_syms | rhs_syms
Set of bound SymPy symbols contained within the equation .
62,772
def SympyCreate ( n ) : a = sympy . zeros ( n ) for i in range ( 1 , n ) : a += sympy . sqrt ( i ) * basis_state ( i , n ) * basis_state ( i - 1 , n ) . H return a
Creation operator for a Hilbert space of dimension n as an instance of sympy . Matrix
62,773
def formfield_for_dbfield ( self , db_field , ** kwargs ) : overrides = self . formfield_overrides . get ( db_field . name ) if overrides : kwargs . update ( overrides ) field = super ( AbstractEntryBaseAdmin , self ) . formfield_for_dbfield ( db_field , ** kwargs ) if db_field . name == 'author' : field . user = kwarg...
Allow formfield_overrides to contain field names too .
62,774
def _split_op ( self , identifier , hs_label = None , dagger = False , args = None ) : if self . _isinstance ( identifier , 'SymbolicLabelBase' ) : identifier = QnetAsciiDefaultPrinter ( ) . _print_SCALAR_TYPES ( identifier . expr ) name , total_subscript = self . _split_identifier ( identifier ) total_superscript = ''...
Return name total subscript total superscript and arguments str . All of the returned strings are fully rendered .
62,775
def _render_hs_label ( self , hs ) : if isinstance ( hs . __class__ , Singleton ) : return self . _render_str ( hs . label ) else : return self . _tensor_sym . join ( [ self . _render_str ( ls . label ) for ls in hs . local_factors ] )
Return the label of the given Hilbert space as a string
62,776
def parenthesize ( self , expr , level , * args , strict = False , ** kwargs ) : needs_parenths = ( ( precedence ( expr ) < level ) or ( strict and precedence ( expr ) == level ) ) if needs_parenths : return ( self . _parenth_left + self . doprint ( expr , * args , ** kwargs ) + self . _parenth_right ) else : return se...
Render expr and wrap the result in parentheses if the precedence of expr is below the given level ( or at the given level if strict is True . Extra args and kwargs are passed to the internal doit renderer
62,777
def draw_circuit ( circuit , filename , direction = 'lr' , hunit = HUNIT , vunit = VUNIT , rhmargin = RHMARGIN , rvmargin = RVMARGIN , rpermutation_length = RPLENGTH , draw_boxes = True , permutation_arrows = False ) : if direction == 'lr' : hunit = abs ( hunit ) elif direction == 'rl' : hunit = - abs ( hunit ) try : c...
Generate a graphic representation of circuit and store them in a file . The graphics format is determined from the file extension .
62,778
def nested_tuple ( container ) : if isinstance ( container , OrderedDict ) : return tuple ( map ( nested_tuple , container . items ( ) ) ) if isinstance ( container , Mapping ) : return tuple ( sorted_if_possible ( map ( nested_tuple , container . items ( ) ) ) ) if not isinstance ( container , ( str , bytes ) ) : if i...
Recursively transform a container structure to a nested tuple .
62,779
def precedence ( item ) : try : mro = item . __class__ . __mro__ except AttributeError : return PRECEDENCE [ "Atom" ] for i in mro : n = i . __name__ if n in PRECEDENCE_FUNCTIONS : return PRECEDENCE_FUNCTIONS [ n ] ( item ) elif n in PRECEDENCE_VALUES : return PRECEDENCE_VALUES [ n ] return PRECEDENCE [ "Atom" ]
Returns the precedence of a given object .
62,780
def callback_prototype ( prototype ) : protosig = signature ( prototype ) positional , keyword = [ ] , [ ] for name , param in protosig . parameters . items ( ) : if param . kind in ( Parameter . VAR_POSITIONAL , Parameter . VAR_KEYWORD ) : raise TypeError ( "*args/**kwargs not supported in prototypes" ) if ( param . d...
Decorator to process a callback prototype . A callback prototype is a function whose signature includes all the values that will be passed by the callback API in question . The original function will be returned with a prototype . adapt attribute which can be used to prepare third party callbacks .
62,781
def published ( self , for_user = None ) : if appsettings . FLUENT_BLOGS_FILTER_SITE_ID : qs = self . parent_site ( settings . SITE_ID ) else : qs = self if for_user is not None and for_user . is_staff : return qs return qs . filter ( status = self . model . PUBLISHED ) . filter ( Q ( publication_date__isnull = True ) ...
Return only published entries for the current site .
62,782
def authors ( self , * usernames ) : if len ( usernames ) == 1 : return self . filter ( ** { "author__{}" . format ( User . USERNAME_FIELD ) : usernames [ 0 ] } ) else : return self . filter ( ** { "author__{}__in" . format ( User . USERNAME_FIELD ) : usernames } )
Return the entries written by the given usernames When multiple tags are provided they operate as OR query .
62,783
def categories ( self , * category_slugs ) : categories_field = getattr ( self . model , 'categories' , None ) if categories_field is None : raise AttributeError ( "The {0} does not include CategoriesEntryMixin" . format ( self . model . __name__ ) ) if issubclass ( categories_field . rel . model , TranslatableModel ) ...
Return the entries with the given category slugs . When multiple tags are provided they operate as OR query .
62,784
def tagged ( self , * tag_slugs ) : if getattr ( self . model , 'tags' , None ) is None : raise AttributeError ( "The {0} does not include TagsEntryMixin" . format ( self . model . __name__ ) ) if len ( tag_slugs ) == 1 : return self . filter ( tags__slug = tag_slugs [ 0 ] ) else : return self . filter ( tags__slug__in...
Return the items which are tagged with a specific tag . When multiple tags are provided they operate as OR query .
62,785
def format ( self , ** kwargs ) : name = self . name . format ( ** kwargs ) subs = [ ] if self . sub is not None : subs = [ self . sub . format ( ** kwargs ) ] supers = [ ] if self . sup is not None : supers = [ self . sup . format ( ** kwargs ) ] return render_unicode_sub_super ( name , subs , supers , sub_first = Tru...
Format and combine the name subscript and superscript
62,786
def _render_str ( self , string ) : if isinstance ( string , StrLabel ) : string = string . _render ( string . expr ) string = str ( string ) if len ( string ) == 0 : return '' name , supers , subs = split_super_sub ( string ) return render_unicode_sub_super ( name , subs , supers , sub_first = True , translate_symbols...
Returned a unicodified version of the string
62,787
def PauliX ( local_space , states = None ) : r local_space , states = _get_pauli_args ( local_space , states ) g , e = states return ( LocalSigma . create ( g , e , hs = local_space ) + LocalSigma . create ( e , g , hs = local_space ) )
r Pauli - type X - operator
62,788
def PauliY ( local_space , states = None ) : r local_space , states = _get_pauli_args ( local_space , states ) g , e = states return I * ( - LocalSigma . create ( g , e , hs = local_space ) + LocalSigma . create ( e , g , hs = local_space ) )
r Pauli - type Y - operator
62,789
def PauliZ ( local_space , states = None ) : r local_space , states = _get_pauli_args ( local_space , states ) g , e = states return ( LocalProjector ( g , hs = local_space ) - LocalProjector ( e , hs = local_space ) )
r Pauli - type Z - operator
62,790
def render_head_repr ( expr : Any , sub_render = None , key_sub_render = None ) -> str : head_repr_fmt = r'{head}({args}{kwargs})' if sub_render is None : sub_render = render_head_repr if key_sub_render is None : key_sub_render = sub_render if isinstance ( expr . __class__ , Singleton ) : return repr ( expr ) if isinst...
Render a textual representation of expr using Positional and keyword arguments are recursively rendered using sub_render which defaults to render_head_repr by default . If desired a different renderer may be used for keyword arguments by giving key_sub_renderer
62,791
def check_rules_dict ( rules ) : from qnet . algebra . pattern_matching import Pattern , ProtoExpr if hasattr ( rules , 'items' ) : items = rules . items ( ) else : items = rules keys = set ( ) for key_rule in items : try : key , rule = key_rule except ValueError : raise TypeError ( "rules does not contain (key, rule) ...
Verify the rules that classes may use for the _rules or _binary_rules class attribute .
62,792
def derationalize_denom ( expr ) : r_pos = - 1 p_pos = - 1 numerator = S . Zero denom_sq = S . One post_factors = [ ] if isinstance ( expr , Mul ) : for pos , factor in enumerate ( expr . args ) : if isinstance ( factor , Rational ) and r_pos < 0 : r_pos = pos numerator , denom_sq = factor . p , factor . q elif isinsta...
Try to de - rationalize the denominator of the given expression .
62,793
def entries ( self ) : EntryModel = get_entry_model ( ) qs = get_entry_model ( ) . objects . order_by ( '-publication_date' ) if issubclass ( EntryModel , TranslatableModel ) : admin_form_language = self . get_current_language ( ) qs = qs . active_translations ( admin_form_language ) . language ( admin_form_language ) ...
Return the entries that are published under this node .
62,794
def get_entry_url ( self , entry ) : with switch_language ( self , entry . get_current_language ( ) ) : return self . get_absolute_url ( ) + entry . get_relative_url ( )
Return the URL of a blog entry relative to this page .
62,795
def create_placeholder ( self , slot = "blog_contents" , role = 'm' , title = None ) : return Placeholder . objects . create_for_object ( self , slot , role = role , title = title )
Create a placeholder on this blog entry .
62,796
def save_as_png ( self , filename , width = 300 , height = 250 , render_time = 1 ) : self . driver . set_window_size ( width , height ) self . driver . get ( 'file://{path}/{filename}' . format ( path = os . getcwd ( ) , filename = filename + ".html" ) ) time . sleep ( render_time ) self . driver . save_screenshot ( fi...
Open saved html file in an virtual browser and save a screen shot to PNG format .
62,797
def get_version ( filename ) : with open ( filename ) as in_fh : for line in in_fh : if line . startswith ( '__version__' ) : return line . split ( '=' ) [ 1 ] . strip ( ) [ 1 : - 1 ] raise ValueError ( "Cannot extract version from %s" % filename )
Extract the package version
62,798
def format_year ( year ) : if isinstance ( year , ( date , datetime ) ) : return unicode ( year . year ) else : return unicode ( year )
Format the year value of the YearArchiveView which can be a integer or date object .
62,799
def free_symbols ( self ) : return set ( [ sym for sym in self . term . free_symbols if sym not in self . bound_symbols ] )
Set of all free symbols