Python string.upper() Examples

The following are 30 code examples for showing how to use string.upper(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module string , or try the search function .

Example 1
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _initializePOSTables():
    global _POSNormalizationTable, _POStoDictionaryTable
    _POSNormalizationTable = {}
    _POStoDictionaryTable = {}
    for pos, abbreviations in (
	    (NOUN, "noun n n."),
	    (VERB, "verb v v."),
	    (ADJECTIVE, "adjective adj adj. a s"),
	    (ADVERB, "adverb adv adv. r")):
	tokens = string.split(abbreviations)
	for token in tokens:
	    _POSNormalizationTable[token] = pos
	    _POSNormalizationTable[string.upper(token)] = pos
    for dict in Dictionaries:
	_POSNormalizationTable[dict] = dict.pos
	_POStoDictionaryTable[dict.pos] = dict 
Example 2
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _initializePOSTables():
    global _POSNormalizationTable, _POStoDictionaryTable
    _POSNormalizationTable = {}
    _POStoDictionaryTable = {}
    for pos, abbreviations in (
	    (NOUN, "noun n n."),
	    (VERB, "verb v v."),
	    (ADJECTIVE, "adjective adj adj. a s"),
	    (ADVERB, "adverb adv adv. r")):
	tokens = string.split(abbreviations)
	for token in tokens:
	    _POSNormalizationTable[token] = pos
	    _POSNormalizationTable[string.upper(token)] = pos
    for dict in Dictionaries:
	_POSNormalizationTable[dict] = dict.pos
	_POStoDictionaryTable[dict.pos] = dict 
Example 3
Project: CVE-2017-7494   Author: joxeankoret   File: nmb.py    License: GNU General Public License v3.0 6 votes vote down vote up
def name_registration_request(self, nbname, destaddr, qtype, scope, nb_flags=0, nb_address='0.0.0.0'):
        netbios_name = nbname.upper()
        qn_label = encode_name(netbios_name, qtype, scope)

        p = NAME_REGISTRATION_REQUEST()
        p['NAME_TRN_ID'] = randint(1, 32000)
        p['QUESTION_NAME'] = qn_label[:-1]
        p['RR_NAME'] = qn_label[:-1]
        p['TTL'] = 0xffff
        p['NB_FLAGS'] = nb_flags
        p['NB_ADDRESS'] = socket.inet_aton(nb_address)
        if not destaddr:
            p['FLAGS'] |= NM_FLAGS_BROADCAST
            destaddr = self.__broadcastaddr
        req = p.getData()

        res = self.send(p, destaddr, 1)
        return res 
Example 4
Project: CVE-2017-7494   Author: joxeankoret   File: nmb.py    License: GNU General Public License v3.0 6 votes vote down vote up
def name_query_request(self, nbname, destaddr = None, qtype = TYPE_SERVER, scope = None, timeout = 1):
        netbios_name = nbname.upper()
        qn_label = encode_name(netbios_name, qtype, scope)

        p = NAME_QUERY_REQUEST()
        p['NAME_TRN_ID'] = randint(1, 32000)
        p['QUESTION_NAME'] = qn_label[:-1]
        p['FLAGS'] = NM_FLAGS_RD
        if not destaddr:
            p['FLAGS'] |= NM_FLAGS_BROADCAST

            destaddr = self.__broadcastaddr
        req = p.getData()

        res = self.send(p, destaddr, timeout)
        return NBPositiveNameQueryResponse(res['ANSWERS']) 
Example 5
Project: CVE-2017-7494   Author: joxeankoret   File: nmb.py    License: GNU General Public License v3.0 6 votes vote down vote up
def node_status_request(self, nbname, destaddr, type, scope, timeout):
        netbios_name = string.upper(nbname)
        qn_label = encode_name(netbios_name, type, scope)
        p = NODE_STATUS_REQUEST()
        p['NAME_TRN_ID'] = randint(1, 32000)
        p['QUESTION_NAME'] = qn_label[:-1]

        if not destaddr:
            p['FLAGS'] = NM_FLAGS_BROADCAST
            destaddr = self.__broadcastaddr

        res = self.send(p, destaddr, timeout)
        answ = NBNodeStatusResponse(res['ANSWERS'])
        self.mac = answ.get_mac()
        return answ.entries

################################################################################
# 4.2 SESSION SERVICE PACKETS
################################################################################ 
Example 6
Project: pivy   Author: coin3d   File: SConsOptions.py    License: ISC License 6 votes vote down vote up
def format_option_strings(self, option):
        """Return a comma-separated list of option strings & metavariables."""
        if option.takes_value():
            metavar = option.metavar or string.upper(option.dest)
            short_opts = []
            for sopt in option._short_opts:
                short_opts.append(self._short_opt_fmt % (sopt, metavar))
            long_opts = []
            for lopt in option._long_opts:
                long_opts.append(self._long_opt_fmt % (lopt, metavar))
        else:
            short_opts = option._short_opts
            long_opts = option._long_opts

        if self.short_first:
            opts = short_opts + long_opts
        else:
            opts = long_opts + short_opts

        return string.join(opts, ", ") 
Example 7
Project: pivy   Author: coin3d   File: _scons_optparse.py    License: ISC License 6 votes vote down vote up
def format_option_strings(self, option):
        """Return a comma-separated list of option strings & metavariables."""
        if option.takes_value():
            metavar = option.metavar or string.upper(option.dest)
            short_opts = []
            for sopt in option._short_opts:
                short_opts.append(self._short_opt_fmt % (sopt, metavar))
            long_opts = []
            for lopt in option._long_opts:
                long_opts.append(self._long_opt_fmt % (lopt, metavar))
        else:
            short_opts = option._short_opts
            long_opts = option._long_opts

        if self.short_first:
            opts = short_opts + long_opts
        else:
            opts = long_opts + short_opts

        return string.join(opts, ", ") 
Example 8
Project: pivy   Author: coin3d   File: msvs.py    License: ISC License 6 votes vote down vote up
def _generateGUID(slnfile, name):
    """This generates a dummy GUID for the sln file to use.  It is
    based on the MD5 signatures of the sln filename plus the name of
    the project.  It basically just needs to be unique, and not
    change with each invocation."""
    m = hashlib.md5()
    # Normalize the slnfile path to a Windows path (\ separators) so
    # the generated file has a consistent GUID even if we generate
    # it on a non-Windows platform.
    m.update(ntpath.normpath(str(slnfile)) + str(name))
    # TODO(1.5)
    #solution = m.hexdigest().upper()
    solution = string.upper(_hexdigest(m.digest()))
    # convert most of the signature to GUID form (discard the rest)
    solution = "{" + solution[:8] + "-" + solution[8:12] + "-" + solution[12:16] + "-" + solution[16:20] + "-" + solution[20:32] + "}"
    return solution 
Example 9
Project: cracke-dit   Author: eth0izzle   File: nmb.py    License: MIT License 6 votes vote down vote up
def name_registration_request(self, nbname, destaddr, qtype, scope, nb_flags=0, nb_address='0.0.0.0'):
        netbios_name = nbname.upper()
        qn_label = encode_name(netbios_name, qtype, scope)

        p = NAME_REGISTRATION_REQUEST()
        p['NAME_TRN_ID'] = randint(1, 32000)
        p['QUESTION_NAME'] = qn_label[:-1]
        p['RR_NAME'] = qn_label[:-1]
        p['TTL'] = 0xffff
        p['NB_FLAGS'] = nb_flags
        p['NB_ADDRESS'] = socket.inet_aton(nb_address)
        if not destaddr:
            p['FLAGS'] |= NM_FLAGS_BROADCAST
            destaddr = self.__broadcastaddr
        req = p.getData()

        res = self.send(p, destaddr, 1)
        return res 
Example 10
Project: cracke-dit   Author: eth0izzle   File: nmb.py    License: MIT License 6 votes vote down vote up
def name_query_request(self, nbname, destaddr = None, qtype = TYPE_SERVER, scope = None, timeout = 1):
        netbios_name = nbname.upper()
        qn_label = encode_name(netbios_name, qtype, scope)

        p = NAME_QUERY_REQUEST()
        p['NAME_TRN_ID'] = randint(1, 32000)
        p['QUESTION_NAME'] = qn_label[:-1]
        p['FLAGS'] = NM_FLAGS_RD
        if not destaddr:
            p['FLAGS'] |= NM_FLAGS_BROADCAST

            destaddr = self.__broadcastaddr
        req = p.getData()

        res = self.send(p, destaddr, timeout)
        return NBPositiveNameQueryResponse(res['ANSWERS']) 
Example 11
Project: cracke-dit   Author: eth0izzle   File: nmb.py    License: MIT License 6 votes vote down vote up
def node_status_request(self, nbname, destaddr, type, scope, timeout):
        netbios_name = string.upper(nbname)
        qn_label = encode_name(netbios_name, type, scope)
        p = NODE_STATUS_REQUEST()
        p['NAME_TRN_ID'] = randint(1, 32000)
        p['QUESTION_NAME'] = qn_label[:-1]

        if not destaddr:
            p['FLAGS'] = NM_FLAGS_BROADCAST
            destaddr = self.__broadcastaddr

        res = self.send(p, destaddr, timeout)
        answ = NBNodeStatusResponse(res['ANSWERS'])
        self.mac = answ.get_mac()
        return answ.entries

################################################################################
# 4.2 SESSION SERVICE PACKETS
################################################################################ 
Example 12
Project: tvalacarta   Author: tvalacarta   File: smb.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __connect_tree(self, path, service, password, timeout = None):
        if password:
            # Password is only encrypted if the server passed us an "encryption" during protocol dialect
            # negotiation and mxCrypto's DES module is loaded.
            if self.__enc_key and DES:
                password = self.__deshash(password)
            self.__send_smb_packet(SMB.SMB_COM_TREE_CONNECT_ANDX, 0, 0x08, 0, 0, 0, pack('<BBHHH', 0xff, 0, 0, 0, len(password)), password + string.upper(path) + '\0' + service + '\0')
        else:
            self.__send_smb_packet(SMB.SMB_COM_TREE_CONNECT_ANDX, 0, 0x08, 0, 0, 0, pack('<BBHHH', 0xff, 0, 0, 0, 1), '\0' + string.upper(path) + '\0' + service + '\0')

        while 1:
            data = self.__sess.recv_packet(timeout)
            if data:
                cmd, err_class, err_code, flags1, flags2, tid, _, mid, params, d = self.__decode_smb(data)
                if cmd == SMB.SMB_COM_TREE_CONNECT_ANDX:
                    if err_class == 0x00 and err_code == 0x00:
                        return tid
                    else:
                        raise SessionError, ( "Cannot connect tree. (ErrClass: %d and ErrCode: %d)" % ( err_class, err_code ), err_class, err_code ) 
Example 13
Project: Fluid-Designer   Author: Microvellum   File: normalDate.py    License: GNU General Public License v3.0 6 votes vote down vote up
def formatMS(self,fmt):
        '''format like MS date using the notation
        {YY}    --> 2 digit year
        {YYYY}  --> 4 digit year
        {M}     --> month as digit
        {MM}    --> 2 digit month
        {MMM}   --> abbreviated month name
        {MMMM}  --> monthname
        {MMMMM} --> first character of monthname
        {D}     --> day of month as digit
        {DD}    --> 2 digit day of month
        {DDD}   --> abrreviated weekday name
        {DDDD}  --> weekday name
        '''
        r = fmt[:]
        f = 0
        while 1:
            m = _fmtPat.search(r,f)
            if m:
                y = getattr(self,'_fmt'+string.upper(m.group()[1:-1]))()
                i, j = m.span()
                r = (r[0:i] + y) + r[j:]
                f = i + len(y)
            else:
                return r 
Example 14
Project: Ossian   Author: CSTR-Edinburgh   File: NodeProcessors.py    License: Apache License 2.0 6 votes vote down vote up
def enrich_nodes(node, function=string.upper,\
                     target_nodes="//Token", input_attribute="text", \
                     output_attribute="uppercase_text", overwrite=True, kwargs={}):
    """
    Apply function to elements of utt that mathc xpath target_nodes. Input to
    the function with be input_attribute, output will be put in output_attribute.  

    Using the defaults, this should make uppercase copies of tokens [TODO: test this].  
    """
    nodes = node.xpath(target_nodes)
    assert len(nodes) > 0
    for node in nodes:
        assert node.has_attribute(input_attribute)
        if not overwrite:
            assert not node.has_attribute(output_attribute),"Cannot overwrite existing '%s' in node "%(output_attribute)
        input_data = node.get(input_attribute)
        transformed_data = function(input_data, **kwargs)
        node.set(output_attribute, transformed_data) 
Example 15
Project: mxnet-lambda   Author: awslabs   File: Image.py    License: Apache License 2.0 6 votes vote down vote up
def copy(self):
        "Copy raster data"

        self.load()
        im = self.im.copy()
        return self._new(im)

    ##
    # Returns a rectangular region from this image. The box is a
    # 4-tuple defining the left, upper, right, and lower pixel
    # coordinate.
    # <p>
    # This is a lazy operation.  Changes to the source image may or
    # may not be reflected in the cropped image.  To break the
    # connection, call the {@link #Image.load} method on the cropped
    # copy.
    #
    # @param The crop rectangle, as a (left, upper, right, lower)-tuple.
    # @return An Image object. 
Example 16
Project: GloboNetworkAPI   Author: globocom   File: models.py    License: Apache License 2.0 6 votes vote down vote up
def heathcheck_exist(cls, healthcheck_type, id_evironment_vip):

        health_type_upper = healthcheck_type.upper()

        env_query = Ambiente.objects.filter(
            Q(vlan__networkipv4__ambient_vip__id=id_evironment_vip) |
            Q(vlan__networkipv6__ambient_vip__id=id_evironment_vip)
        )

        environment = env_query and env_query.uniqueResult() or None

        options_pool_environment = environment.opcaopoolambiente_set.all()

        for option_pool_env in options_pool_environment:
            if option_pool_env.opcao_pool.description.upper() == health_type_upper:
                return True

        return False 
Example 17
Project: luscan-devel   Author: blackye   File: ntlm.py    License: GNU General Public License v2.0 6 votes vote down vote up
def create_LM_hashed_password_v1(passwd):
    "setup LanManager password"
    "create LanManager hashed password"
    # if the passwd provided is already a hash, we just return the first half
    if re.match(r'^[\w]{32}:[\w]{32}$',passwd):
        return binascii.unhexlify(passwd.split(':')[0])

    # fix the password length to 14 bytes
    passwd = string.upper(passwd)
    lm_pw = passwd + '\0' * (14 - len(passwd))
    lm_pw = passwd[0:14]

    # do hash
    magic_str = "KGS!@#$%" # page 57 in [MS-NLMP]

    res = ''
    dobj = des.DES(lm_pw[0:7])
    res = res + dobj.encrypt(magic_str)

    dobj = des.DES(lm_pw[7:14])
    res = res + dobj.encrypt(magic_str)

    return res 
Example 18
Project: CAMISIM   Author: CAMI-challenge   File: ref_seq_gen.py    License: Apache License 2.0 5 votes vote down vote up
def getSeeds(inSortedFasta, outSeedsFasta):
    """
        @param inSortedFasta: DNA sequences sorted according to the sequence length in the descending order
        @param outSeedsFasta: a fasta file that contains all seeds
    """
    out = csv.OutFileBuffer(outSeedsFasta)
    seedList = []
    seqList = fasta.getSequencesToList(inSortedFasta)  # list of (sequenceName, sequence)

    for seqId, seq in seqList:
        seq = string.upper(seq)

        newSeed = True
        for seedSeq in seedList:

            if len(seedSeq) < len(seq):
                continue

            # if bool(re.search(seq, seedSeq, re.I)) or bool(re.search(str(Seq(seq).reverse_complement()), seedSeq, re.I)):
            if seq in seedSeq or str(Seq(seq).reverse_complement()) in seedSeq:
                newSeed = False
                break

        if newSeed:
            # print 'new seed:', seqId
            seedList.append(seq)
            out.writeText(str('>' + seqId + '\n' + seq + '\n'))
        # else:
        #    print 'no seed:', seqId

    out.close()

    print 'total', len(seqList)
    print 'seed count', len(seedList)
    print 'duplicate', (len(seqList) - len(seedList)) 
Example 19
Project: CVE-2017-7494   Author: joxeankoret   File: smb.py    License: GNU General Public License v3.0 5 votes vote down vote up
def tree_connect(self, path, password = '', service = SERVICE_ANY):
        LOG.warning("[MS-CIFS] This is an original Core Protocol command.This command has been deprecated.Client Implementations SHOULD use SMB_COM_TREE_CONNECT_ANDX")

        # return 0x800
        if password:
            # Password is only encrypted if the server passed us an "encryption" during protocol dialect
            if self._dialects_parameters['ChallengeLength'] > 0:
                # this code is untested
                password = self.get_ntlmv1_response(ntlm.compute_lmhash(password))

        if not unicode_support:
            if unicode_convert:
                path = str(path)
            else:
                raise Exception('SMB: Can\t conver path from unicode!')

        smb = NewSMBPacket()
        treeConnect = SMBCommand(SMB.SMB_COM_TREE_CONNECT)
        treeConnect['Parameters'] = SMBTreeConnect_Parameters()
        treeConnect['Data']       = SMBTreeConnect_Data()
        treeConnect['Data']['Path'] = path.upper()
        treeConnect['Data']['Password'] = password
        treeConnect['Data']['Service'] = service
        smb.addCommand(treeConnect)
        self.sendSMB(smb)

        while 1:
            smb = self.recvSMB()
            if smb.isValidAnswer(SMB.SMB_COM_TREE_CONNECT):
                # XXX Here we are ignoring the rest of the response
                return smb['Tid']
            return smb['Tid'] 
Example 20
Project: CVE-2017-7494   Author: joxeankoret   File: nmb.py    License: GNU General Public License v3.0 5 votes vote down vote up
def set_mac_in_hexa(self, data):
        data_aux = ''
        for d in data:
            if data_aux == '':
                data_aux = '%02x' % ord(d)
            else:
                data_aux += '-%02x' % ord(d)
        self.mac = string.upper(data_aux) 
Example 21
Project: python-netsurv   Author: sofia-netsurv   File: unittest_checker_python3.py    License: MIT License 5 votes vote down vote up
def test_bad_string_call(self):
        node = astroid.extract_node(
            """
        import string
        string.upper("hello world") #@
        """
        )
        message = testutils.Message("deprecated-string-function", node=node)
        with self.assertAddsMessages(message):
            self.checker.visit_call(node) 
Example 22
Project: python-netsurv   Author: sofia-netsurv   File: unittest_checker_python3.py    License: MIT License 5 votes vote down vote up
def test_bad_string_call(self):
        node = astroid.extract_node(
            """
        import string
        string.upper("hello world") #@
        """
        )
        message = testutils.Message("deprecated-string-function", node=node)
        with self.assertAddsMessages(message):
            self.checker.visit_call(node) 
Example 23
Project: Webshell-Sniper   Author: WangYihang   File: WebShell.py    License: GNU General Public License v3.0 5 votes vote down vote up
def check_working(self, url, method, auth):
        Log.info("Checking whether the webshell is still work...")
        flag = random_string(32, string.letters)
        token = random_string(32, string.letters)
        Log.info("Using challenge flag : [%s]" % (flag))
        Log.info("Using token : [%s]" % (token))
        code = "echo '%s'; echo '%s'; echo '%s';" % (token, flag, token)
        result = self.php_code_exec(code)
        if result[0]:
            content = result[1]
            for i in content.split(token):
                if i == flag:
                    return True
        return False
        '''
        method = string.upper(method)
        if method == "POST" or method == "REQUEST":
            Log.info("Using POST method...")
            data = {auth:'echo "'+token+'";echo "'+flag+'";echo "'+token+'";'}
            response = requests.post(url, data=data)
        elif method == "GET":
            Log.info("Using GET method...")
            params = {auth:'echo "'+token+'";echo "'+flag+'";echo "'+token+'";'}
            url = build_url(url, params)
            data = {key:value}
            response = requests.post(url, data=data)
        else:
            Log.error("Unsupported method!")
            return False
        content = response.content
        # Log.success("The content is :\n " + content)
        ''' 
Example 24
Project: Comparative-Annotation-Toolkit   Author: ComparativeGenomicsToolkit   File: bio.py    License: Apache License 2.0 5 votes vote down vote up
def __getitem__(self, islice):
        d = self.getdata(islice)
        return d.tostring().decode().upper() if self.as_string else list(map(string.upper, d)) 
Example 25
Project: Comparative-Annotation-Toolkit   Author: ComparativeGenomicsToolkit   File: bio.py    License: Apache License 2.0 5 votes vote down vote up
def translate_sequence(sequence):
    """
    Translates a given DNA sequence to single-letter amino acid
    space. If the sequence is not a multiple of 3 and is not a unique degenerate codon it will be truncated silently.
    """
    result = []
    sequence = sequence.upper()
    i = 0
    for i in range(0, len(sequence) - len(sequence) % 3, 3):
        result.append(codon_to_amino_acid(sequence[i: i + 3]))
    if len(sequence) % 3 == 2:
        c = codon_to_amino_acid(sequence[i + 3:] + 'N')
        if c != 'X':
            result.append(c)
    return ''.join(result) 
Example 26
Project: Comparative-Annotation-Toolkit   Author: ComparativeGenomicsToolkit   File: bio.py    License: Apache License 2.0 5 votes vote down vote up
def get_sequence_dict(file_path, upper=True):
    """
    Returns a dictionary of fasta records. If upper is true, all bases will be uppercased.
    """
    assert os.path.exists(file_path), ('Error: FASTA file {} does not exist'.format(file_path))
    gdx_path = file_path + ".gdx"
    assert os.path.exists(gdx_path), ("Error: gdx does not exist for this fasta. We need the fasta files to be "
                                      "flattened in place prior to running the pipeline because of concurrency issues.")
    flat_path = file_path + '.flat'
    assert os.path.exists(flat_path), ("Error: flat file does not exist for this fasta. We need the fasta files to be "
                                       "flattened in place prior to running the pipeline because of concurrency issues.")
    if upper is True:
        return Fasta(file_path, record_class=UpperNpyFastaRecord)
    else:
        return Fasta(file_path) 
Example 27
Project: pivy   Author: coin3d   File: FS.py    License: ISC License 5 votes vote down vote up
def _my_normcase(x):
        return string.upper(x) 
Example 28
Project: pivy   Author: coin3d   File: SConf.py    License: ISC License 5 votes vote down vote up
def _createConfigH(target, source, env):
    t = open(str(target[0]), "w")
    defname = re.sub('[^A-Za-z0-9_]', '_', string.upper(str(target[0])))
    t.write("""#ifndef %(DEFNAME)s_SEEN
#define %(DEFNAME)s_SEEN

""" % {'DEFNAME' : defname})
    t.write(source[0].get_contents())
    t.write("""
#endif /* %(DEFNAME)s_SEEN */
""" % {'DEFNAME' : defname})
    t.close() 
Example 29
Project: pivy   Author: coin3d   File: CacheDir.py    License: ISC License 5 votes vote down vote up
def cachepath(self, node):
        """
        """
        if not self.is_enabled():
            return None, None

        sig = node.get_cachedir_bsig()
        subdir = string.upper(sig[0])
        dir = os.path.join(self.path, subdir)
        return dir, os.path.join(dir, sig) 
Example 30
Project: pivy   Author: coin3d   File: Conftest.py    License: ISC License 5 votes vote down vote up
def _Have(context, key, have, comment = None):
    """
    Store result of a test in context.havedict and context.headerfilename.
    "key" is a "HAVE_abc" name.  It is turned into all CAPITALS and non-
    alphanumerics are replaced by an underscore.
    The value of "have" can be:
    1      - Feature is defined, add "#define key".
    0      - Feature is not defined, add "/* #undef key */".
             Adding "undef" is what autoconf does.  Not useful for the
             compiler, but it shows that the test was done.
    number - Feature is defined to this number "#define key have".
             Doesn't work for 0 or 1, use a string then.
    string - Feature is defined to this string "#define key have".
             Give "have" as is should appear in the header file, include quotes
             when desired and escape special characters!
    """
    key_up = string.upper(key)
    key_up = re.sub('[^A-Z0-9_]', '_', key_up)
    context.havedict[key_up] = have
    if have == 1:
        line = "#define %s 1\n" % key_up
    elif have == 0:
        line = "/* #undef %s */\n" % key_up
    elif isinstance(have, IntType):
        line = "#define %s %d\n" % (key_up, have)
    else:
        line = "#define %s %s\n" % (key_up, str(have))
    
    if comment is not None:
        lines = "\n/* %s */\n" % comment + line
    else:
        lines = "\n" + line

    if context.headerfilename:
        f = open(context.headerfilename, "a")
        f.write(lines)
        f.close()
    elif hasattr(context,'config_h'):
        context.config_h = context.config_h + lines