def group_assignmentgroups(assignment_groups):
    
    dict = OrderedDict()

    for group in assignment_groups:
        
        if not dict.has_key(group.parentnode.parentnode.parentnode):
            subject = Subject(group.parentnode.parentnode.parentnode.short_name)
            dict[group.parentnode.parentnode.parentnode] = subject

        dict[group.parentnode.parentnode.parentnode].add_period(group)

    return dict.values()
def group_assignmentgroups(assignment_groups):

    dict = OrderedDict()

    for group in assignment_groups:

        if not dict.has_key(group.parentnode.parentnode.parentnode):
            subject = Subject(
                group.parentnode.parentnode.parentnode.short_name)
            dict[group.parentnode.parentnode.parentnode] = subject

        dict[group.parentnode.parentnode.parentnode].add_period(group)

    return dict.values()
Exemple #3
0
    def __init__(self, name=None):
        """Initialize a new System object. This must be run before the system can be used.

        Args:
            name (str): The name of the system

        >>> print __init__(name='sysname')
        """
        if name:
            self._name = name
        else:
            self._name = "Untitled"

        self._v1x = 0.0
        self._v2x = 0.0
        self._v3x = 0.0
        self._v1y = 0.0
        self._v2y = 0.0
        self._v3y = 0.0
        self._v1z = 0.0
        self._v2z = 0.0
        self._v3z = 0.0

        self._nbFunc = 0
        self._combinationRule = 0
        self._genpairs = True
        self._ljCorrection = 0
        self._coulombCorrection = 0
        self._molecules = OrderedDict.OrderedDict()
        self._atomtypes = HashMap.HashMap()
        self._forces = OrderedSet.OrderedSet()
        self._boxVector = []
Exemple #4
0
def co_render (a_co):
    """ 
    Transforma un concentador en un OrderedDict para luego ser 
    convertido en html 
    """
    d = OrderedDict.OrderedDict()
    d['h1'] = 'Concentrador %d' %co.id
    d['']
Exemple #5
0
def main():
    if len(sys.argv) < 4:
        usage()
        sys.exit(0)

    NewJSONName = sys.argv[1]
    OldJSONName = sys.argv[2]
    
    NewJSON = selectionParser(open(sys.argv[1]).read()).runsandls()
    OldJSON = selectionParser(open(sys.argv[2]).read()).runsandls()

    TrigFolder  = sys.argv[3]

    KeyQuery = """
    SELECT A.TRIGGERMODE, B.HLT_KEY, B.GT_RS_KEY, B.TSC_KEY, C.CONFIGID, D.GT_KEY FROM
    CMS_WBM.RUNSUMMARY A, CMS_L1_HLT.L1_HLT_CONF B, CMS_HLT.CONFIGURATIONS C, CMS_TRG_L1_CONF.TRIGGERSUP_CONF D WHERE
    B.ID = A.TRIGGERMODE AND C.CONFIGDESCRIPTOR = B.HLT_KEY AND D.TS_Key = B.TSC_Key AND A.RUNNUMBER=%d
    """

    JSONS = {}
    for run in sorted(NewJSON.iterkeys()):
        if OldJSON.has_key(run):
            continue  # skip already processed runs
        LSs = NewJSON[run]
        print "Processing Run: %d" % (run,)
        parser = DatabaseParser.DatabaseParser()
        parser.RunNumber = run
        parser.ParseRunSetup()
        
        PrescaleTable = CheckPrescales.GetPrescaleTable(parser.HLT_Key,parser.GT_Key,parser.GTRS_Key,[],False)

        for HLT,Prescales in PrescaleTable.iteritems():            
            HLTNoV = DatabaseParser.StripVersion(HLT)
            oldpath = TrigFolder + "/" + HLTNoV + "_" + OldJSONName
            if not JSONS.has_key(HLTNoV):
                if os.path.exists(oldpath):
                    JSONS[HLTNoV] = json.load(open(oldpath))
                else:
                    JSONS[HLTNoV] = {}
            tmpLSRange = []
            for ls in LSs:                
                if Prescales[parser.PSColumnByLS[ls]] == 1:
                    tmpLSRange.append(ls)
            JSONS[HLTNoV][str(run)] = truncateRange(tmpLSRange)
    if not os.path.exists(TrigFolder):
        os.system("mkdir -p %s" % (TrigFolder,))
    for name in JSONS.iterkeys():
        thisJSON = JSONS[name]
        sortedJSON = OrderedDict.OrderedDict()
        for key in sorted(thisJSON.iterkeys()):
            sortedJSON[key] = thisJSON[key]
        newpath = TrigFolder + "/" + DatabaseParser.StripVersion(name) + "_" + NewJSONName
        #print "Writing %s" % (newpath,)
        out = open(newpath,'w')
        out.write(json.dumps(sortedJSON))
        #out.write(str(oldJSON))
        out.close()
Exemple #6
0
def get_error_constraints_by_max_percentage_error(qoi_ref,qoi_pct_err):
    assert isinstance(qoi_ref,OrderedDict)
    
    _qoi_pct_err = OrderedDict()
    if isinstance(qoi_pct_err,OrderedDict):
        _qoi_pct_err = OrderedDict(qoi_pct_err)
    elif type(qoi_pct_err) in [int,float]:
        for qn,qv in qoi_ref.items():
            _qoi_pct_err[qn] = qoi_pct_err
    else:
        err_msg = "qoi_pct_err must either be OrderedDict or a numeric value"
        raise ValueError(err_msg)

    _error_constraints = OrderedDict()
    for qn,qv in qoi_ref.items():
        _qce = _qoi_pct_err[qn]
        _error_constraints[qn] = ['<',abs(qv) * _qce]

    return _error_constraints
class Subject(object):

    def __init__(self, name):
        self.periods = OrderedDict()
        self.name = name
            
    def __str__(self):
        return self.name

    def add_period(self, assignment_group):
        
        if not self.periods.has_key(assignment_group.parentnode.parentnode):
            period = Period(assignment_group.parentnode.parentnode.short_name)
            self.periods[assignment_group.parentnode.parentnode] = period

        self.periods[assignment_group.parentnode.parentnode].add_assignment(assignment_group)

    def __iter__(self):
        return iter(self.periods.values())
class Subject(object):
    def __init__(self, name):
        self.periods = OrderedDict()
        self.name = name

    def __str__(self):
        return self.name

    def add_period(self, assignment_group):

        if not self.periods.has_key(assignment_group.parentnode.parentnode):
            period = Period(assignment_group.parentnode.parentnode.short_name)
            self.periods[assignment_group.parentnode.parentnode] = period

        self.periods[assignment_group.parentnode.parentnode].add_assignment(
            assignment_group)

    def __iter__(self):
        return iter(self.periods.values())
Exemple #9
0
    def __init__(self, path):
        '''constructor

        get information from the theme located in path
        '''
        self.path           = None
        # if you add a smilie key twice you will have a nice stack overflow :D
        self.emotes         = OrderedDict()
        self.emote_files    = []
        self.emote_regex_str= ""
        self.emote_regex    = None

        self.load_information(path)
Exemple #10
0
    def find_and_render(cls, path):

        result = {}

        try:
            filepaths = cls.find_relevant_files(path)
        except:
            # This is ok, no tabs when multiple returned.
            return None

        if filepaths:
            for filepath in filepaths:
                title = settings.FILES_MAP[os.path.basename(filepath)]
                result[title] = cls.render_file(filepath)

        if not filepaths and len(result) == 0:
            return None

        result_items = sorted(result.items(), cmp=cls.sort_tabs_by_priority)
        result = OrderedDict.OrderedDict()
        for v, k in result_items:
            result[v] = k
        return result
Exemple #11
0

# These properties are put in a panel where you can tune the properties of your
# source. The first element of each tuple is the name of the variable available
# in your python script, the second is the default value.
# Top-level tuples are propertygroups. One level below is a list of dictionaries for the elements
# Names are converted to labels by '_' > ' ' and uppercasing the first letter
Properties = OrderedDict([
    # Which variables to read from the file
    ('variables',
     ArraySelectionDomain([
         ('Psi', 1),
         ('u', 1),
         ('j', 1),
         ('w', 1),
         ('rho', 1),
         ('T', 1),
     ])),
    ('interpolation_options',
     PropertyGroup([
         ('number_of_subdivisions', dict(value=3, min=2, max=6)),
         ('quadratic', False),
     ])),
])


# from paraview import vtk is done automatically in the reader
def RequestData(self):
    """Create a VTK output given the list of filenames and the current timestep.
    This script can access self and FileNames and should return an output of type
    OutputDataType above"""
Exemple #12
0
 def __setitem__(self, key, value):
     OrderedDict.__setitem__(self, key, value)
     self._check_size_limit()
Exemple #13
0
 def __init__(self, *args, **kwds):
     self.size_limit = kwds.pop("size_limit", None)
     OrderedDict.__init__(self, *args, **kwds)
     self._check_size_limit()
 def __init__(self, name):
     self.periods = OrderedDict()
     self.name = name
Exemple #15
0
m collections import OrderedDict
dict = OrderedDict()
n = int(input())

l = [input().rpartition(' ') for i in range(n)]
for item, space, quant in l:
    dict[item] = dict[item] + int(quant) if item in dict else int(quant)
print("\n".join([" ".join([key, str(value)]) for key, value in dict.items()]))
Exemple #16
0
class AdiumEmoteTheme(object):
    '''a class that contains information of a adium emote theme
    '''

    def __init__(self, path):
        '''constructor

        get information from the theme located in path
        '''
        self.path           = None
        # if you add a smilie key twice you will have a nice stack overflow :D
        self.emotes         = OrderedDict()
        self.emote_files    = []
        self.emote_regex_str= ""
        self.emote_regex    = None

        self.load_information(path)

    def load_information(self, path):
        '''load the information of the theme on path
        '''
        self.path = path

        emote_config_file = os.path.join(self.path, "Emoticons.plist")

        emote_data=plistlib.readPlist(emote_config_file)
        for key, val in emote_data['Emoticons'].iteritems():
            self.emote_files.append(key)
            pointer_name = val['Name']
            pointer_key = val['Equivalents'][0]
            self.emotes[pointer_key] = key
            for v in val['Equivalents'][1:]:
                if v != "":
                    self.emotes[v] = self.emotes[pointer_key]
        for key2 in self.emotes:
            self.emote_regex_str += re.escape(key2) + "|"
        self.emote_regex = re.compile("("+self.emote_regex_str+")")

    def emote_to_path(self, shortcut, remove_protocol=False):
        '''return a string representing the path to load the emote if it exist
        None otherwise'''

        if shortcut not in self.emotes:
            return None

        path = os.path.join(self.path, self.emotes[shortcut])
        path = os.path.abspath(path)

        if os.access(path, os.R_OK) and os.path.isfile(path):
            path = path.replace("\\", "/")

            if remove_protocol:
                return path
            else:
                if os.name == "nt":
                    #if path[1] == ":":
                    #    path = path[2:]
                    path = "localhost/"+path

                return 'file://' + path

        return None

    def _get_emotes_shortcuts(self):
        '''return the list of shortcuts'''
        return self.emotes.keys()

    shortcuts = property(fget=_get_emotes_shortcuts, fset=None)

    def shortcuts_by_length(self, celist=None):
        '''return the list of shortcuts ordered from longest to shortest with
        it's corresponding path or hash '''
        l = [(x, self.emote_to_path(x, True)) for x in self.emotes.keys()]
        if celist is not None:
            l += celist
        
        return sorted(l, key=lambda pair: len(pair[0]), reverse=True)

    def _get_emotes_count(self):
        '''return the number of emoticons registered'''
        return len(set(self.emotes.values()))

    emotes_count = property(fget=_get_emotes_count, fset=None)

    def split_smilies(self, text):
        '''split text in smilies, return a list of tuples that contain
        a boolean as first item indicating if the text is an emote or not
        and the text as second item.
        example : [(False, "hi! "), (True, ":)")]
        '''
        keys = self.emotes.keys()
        return [(item in keys, item) for item in self.emote_regex.split(text)
                if item is not None]
Exemple #17
0
"""Constructing and loading dictionaries"""import cPickle as pklimport numpyfrom collections import OrderedDict
def build_dictionary(text): """    Build a dictionary    text: list of sentences (pre-tokenized) """    wordcount = OrderedDict() for cc in text:        words = cc.split() for w in words: if w not in wordcount:                wordcount[w] = 0            wordcount[w] += 1    words = wordcount.keys()    freqs = wordcount.values()    sorted_idx = numpy.argsort(freqs)[::-1]
    worddict = OrderedDict() for idx, sidx in enumerate(sorted_idx):        worddict[words[sidx]] = idx+2 # 0: <eos>, 1: <unk>
 return worddict, wordcount
def load_dictionary(loc='/ais/gobi3/u/rkiros/bookgen/book_dictionary_large.pkl'): """    Load a dictionary """ with open(loc, 'rb') as f:        worddict = pkl.load(f) return worddict
def save_dictionary(worddict, wordcount, loc): """    Save a dictionary to the specified location  """ with open(loc, 'wb') as f:        pkl.dump(worddict, f)        pkl.dump(wordcount, f)

 def __init__(self, name):
     self.periods = OrderedDict()
     self.name = name
Exemple #19
0
 def __init__(self):
     self._items = OrderedDict.OrderedDict()
    def createTasks(self,
                    configOnly=False,
                    codeRepo='git',
                    over500JobsMode=NONE,
                    **kwargs):
        if self.datasets == None:
            self._createDatasets()

        # If mode is NONE, create tasks for all datasets
        if over500JobsMode == Multicrab.NONE:
            return self._createTasks(configOnly, codeRepo, **kwargs)

        datasetsOver500Jobs = OrderedDict.OrderedDict()
        datasetsUnder500Jobs = OrderedDict.OrderedDict()

        def checkAnyOver500Jobs(dataset):
            njobs = dataset.getNumberOfJobs()
            if njobs > 500:
                datasetsOver500Jobs[dataset.getName()] = njobs
            else:
                datasetsUnder500Jobs[dataset.getName()] = njobs

        self.forEachDataset(checkAnyOver500Jobs)
        # If all tasks have < 500 jobs, create all tasks
        if len(datasetsOver500Jobs) == 0:
            return self._createTasks(configOnly, codeRepo, **kwargs)

        # If mode is SERVER, set server=1 for tasks with >= 500 jobs
        if over500JobsMode == Multicrab.SERVER:
            for dname in datasetsOver500Jobs.iterkeys():
                self.getDataset(dname).useServer(True)
            return self._createTasks(configOnly, codeRepo, **kwargs)

        # If mode is SPLIT, first create < 500 job tasks in one
        # multicrab directory, then for each tasks with >= 500 jobs
        # create one multicrab directory per 500 jobs
        if over500JobsMode == Multicrab.SPLIT:
            ret = self._createTasks(configOnly,
                                    codeRepo,
                                    datasetNames=datasetsUnder500Jobs.keys(),
                                    **kwargs)

            args = {}
            args.update(kwargs)
            prefix = kwargs.get("prefix", "multicrab")

            for datasetName, njobs in datasetsOver500Jobs.iteritems():
                dname = datasetName.split("_")[0]
                nMulticrabTasks = int(math.ceil(njobs / 500.0))
                for i in xrange(nMulticrabTasks):
                    firstJob = i * 500 + 1
                    lastJob = (i + 1) * 500
                    args["prefix"] = "%s_%s_%d-%d" % (prefix, dname, firstJob,
                                                      lastJob)
                    ret.extend(
                        self._createTasks(configOnly,
                                          codeRepo,
                                          datasetNames=[datasetName],
                                          **args))

            return ret

        raise Exception("Incorrect value for over500JobsMode: %d" %
                        over500JobsMode)
# Sort dictionary with tuple values and filter top k elements
In [1]: from collections import OrderedDict
In [2]: OrderedDict(sorted(A.iteritems(), key=operator.itemgetter(1), reverse=False)[:k])
Out[2]: OrderedDict([('b', (1, 2)), ('a', (3, 4)), ('c', (10, 11))])
cause_search_library = OrderedDict({r'.*HIV.*':'HIV/AIDS',
                        r'.*AIDS.*':'HIV/AIDS',
                        r'.*(?i)motor\sneuron.*':'Motor neuron disease',
                        r'.*(?i)tuberculosis.*':'Tuberculosis',
                        r'.*(?i)syphilis.*':'Sexually transmitted infections excluding HIV',
                        r'.*(?i)chlamydia.*':'Sexually transmitted infections excluding HIV',
                        r'.*(?i)(gonococc|gonorrhea).*':'Sexually transmitted infections excluding HIV',
                        r'.*(?i)trichomon.*':'Sexually transmitted infections excluding HIV',
                        r'.*(?i)(varicella|herpes.zoster).*':'Varicella and herpes zoster',
                        r'.*(?i)herpes.*':'Sexually transmitted infections excluding HIV',
                        r'.*(?i)lower\srespiratory\sinfection.*':'Lower respiratory infections',
                        r'.*(?i)(influenza|pneumonia|respiratory\ssyncytial).*':'Lower respiratory infections',
                        r'.*(?i)upper\srespiratory\sinfection.*':'Upper respiratory infections',
                        r'.*(?i)otitis.*':'Otitis media',
                        r'.*(?i)diarrhea.*':'Diarrheal diseases',
                        r'.*(?i)(cholera|shigella|enteropathogenic\se\scoli|enterotoxigenic\se\scoli|campylobacter|entamoeba|cryptosporidium|rotavirus|aeromonas|clostridium\sdifficile|norovirus|adenovirus).*':'Diarrheal diseases',
                        r'.*(?i)typhoid.*':'Typhoid and paratyphoid',
                        r'.*[iI]NTS.*':'Invasive Non-typhoidal Salmonella (iNTS)',
                        r'.*(?i)salmonella.*':'Invasive Non-typhoidal Salmonella (iNTS)',
                        r'.*(?i)non\-typhoidal.*':'Invasive Non-typhoidal Salmonella (iNTS)',
                        r'.*(?i)malaria.*':'Malaria',
                        r'.*(?i)chagas.*':'Chagas disease',
                        r'.*(?i)leishmaniasis':'Leishmaniasis',
                        r'.*(?i)trypanosomiasis.*':'African trypanosomiasis',
                        r'.*(?i)schistosomiasis.*':'Schistosomiasis',
                        r'.*(?i)cysticercosis.*':'Cysticercosis',
                        r'.*(?i)echinococcosis.*':'Cystic echinococcosis',
                        r'.*(?i)filariasis.*':'Lymphatic filariasis',
                        r'.*(?i)onchocerciasis.*':'Onchocerciasis',
                        r'.*(?i)trachoma.*':'Trachoma',
                        r'.*(?i)dengue.*':'Dengue',
                        r'.*(?i)yellow\sfever.*':'Yellow fever',
                        r'.*(?i)rabies.*': 'Rabies',
                        r'.*(?i)(ascariasis|trichuriasis|hookworm|nematode).*':'Intestinal nematode infections',
                        r'.*(?i)trematodias.*':'Food-borne trematodiases',
                        r'.*(?i)leprosy.*':'Leprosy',
                        r'.*(?i)ebola.*':'Ebola',
                        r'.*(?i)zika.*':'Zika virus',
                        r'.*(?i)guinea\sworm.*':'Guinea worm disease',
                        r'.*(?i)tropical\sdisease.*':'Other neglected tropical diseases',
                        r'.*(?i)meningitis.*':'Meningitis',
                        r'.*(?i)encephalitis.*':'Encephalitis',
                        r'.*(?i)diphtheria.*':'Diphtheria',
                        r'.*(?i)whooping\scough.*':'Whooping cough',
                        r'.*(?i)tetanus.*':'Tetanus',
                        r'.*(?i)measle.*':'Measles',
                        r'.*(?i)hepatitis.*':'Acute hepatitis',
                        r'.*(?i)maternal.*':'Maternal disorders',
                        r'.*(?i)neonatal.*':'Neonatal disorders',
                        r'.*(?i)protein.energy.*':'Protein-energy malnutrition',
                        r'.*PEM':'Protein-energy malnutrition',
                        r'.*(?i)iodine.deficien.*':'Iodine deficiency',
                        r'.*(?i)vitamin.a.*':'Vitamin A deficiency',
                        r'.*(?i)iron.deficien.*':'Dietary iron deficiency',
                        r'.*(?i)(lip|oral|mouth)\s(cancer|neoplasm).*':'Lip and oral cavity cancer',
                        r'.*(?i)(cancer|neoplasm)\s.*(lip|oral|mouth).*':'Lip and oral cavity cancer',
                        r'.*(?i)nasopharynx.*':'Nasopharynx cancer',
                        r'.*(?i)pharnyx.*':'Other pharynx cancer',
                        r'.*(?i)(esophageal|esophagus).*\s(cancer|neoplasm).*':'Esophageal cancer',
                        r'.*(?i)stomach\s.*(cancer|neoplasm).*':'Stomach cancer',
                        r'.*(?i)(cancer|neoplasm)\s.*stomach.*':'Stomach cancer',
                        r'.*(?i)(colorectal|colon|rectum)\s(cancer|neoplasm).*':'Colon and rectum cancer',
                        r'.*(?i)(cancer|neoplasm)\s(colorectal|colon|rectum).*':'Colon and rectum cancer',
                        r'.*(?i)liver\s.*(cancer|neoplasm).*':'Liver cancer',
                        r'.*(?i)(cancer|neoplasm)\s.*liver.*':'Liver cancer',
                        r'.*(?i)(gallbladder|biliary)\s.*(cancer|neoplasm).*':'Gallbladder and biliary tract cancer',
                        r'.*(?i)(cancer|neoplasm)\s.*(gallbladder|biliary).*':'Gallbaldder and biliary tract cancer',
                        r'.*(?i)(pancreatic|pancreas).*':'Pancreatic cancer',
                        r'.*(?i)larynx\s.*(cancer|neoplasm).*':'Larynx cancer',
                        r'.*(?i)(cancer|neoplasm)\s.*larynx.*':'Larynx cancer',
                        r'.*(?i)(trachea|bronchus|lung)\s.*(cancer|neoplasm).*':'Tracheal, bronchus, and lung cancer',
                        r'.*(?i)(cancer|neoplasm)\s.*(trachea|bronchus|lung).*':'Tracheal, bronchus, and lung cancer',
                        r'.*(?i)(non.melanoma|squamous.cell|basal.cell)\s.*(cancer|neoplasm|carcinoma).*':'Non-melanoma skin cancer',
                        r'.*(?i)melanoma.*':'Malignant skin melanoma',
                        r'.*(?i)skin\s.*(cancer|neoplasm).*':'Malignant skin melanoma',
                        r'.*(?i)breast\s.*(cancer|neoplasm).*':'Breast cancer',
                        r'.*(?i)(cancer|neoplasm)\s.*breast.*':'Breast cancer',
                        r'.*(?i)(cervical|cervix)\s.*(cancer|neoplasm).*':'Cervical cancer',
                        r'.*(?i)(cancer|neoplasm)\s.*(cervical|cervix).*':'Cervical cancer',
                        r'.*(?i)(cancer|neoplasm)\s.*(uterine|uterus).*':'Uterine cancer',
                        r'.*(?i)(uterine|uterus)\s.*(cancer|neoplasm).*':'Uterine cancer',
                        r'.*(?i)(ovarian|ovary)\s.*(cancer|neoplasm).*':'Ovarian cancer',
                        r'.*(?i)(cancer|neoplasm)\s.*(ovarian|ovary).*':'Ovarian cancer',
                        r'.*(?i)prostate\s.*(cancer|neoplasm).*':'Prostate cancer',
                        r'.*(?i)(cancer|neoplasm)\s.*prostate.*':'Prostate cancer',
                        r'.*(?i)(testicular|testes|testicle).*(cancer|neoplasm)':'Testicular cancer',
                        r'.*(?i)(cancer|neoplasm)\s.*(testicular|testes|testicle)':'Testicular cancer',
                        r'.*(?i)(cancer|neoplasm)\s.*kidney':'Kidney cancer',
                        r'.*(?i)kidney\s.*(cancer|neoplasm)':'Kidney cancer',
                        r'.*(?i)bladder\s.*(cancer|neoplasm)':'Bladder cancer',
                        r'.*(?i)(cancer|neoplasm)\s.*bladder.*':'Bladder cancer',
                        r'.*(?i)(cancer|neoplasm)\s.*(brain|nervous).*':'Brain and nervous system cancer',
                        r'.*(?i)(cancer|neoplasm)\s.*thyroid.*':'Thyroid cancer',
                        r'.*(?i)(brain|nervous)\s.*(cancer|neoplasm)':'Brain and nervous system cancer',
                        r'.*(?i)thyroid\s.*(cancer|neoplasm)':'Thyroid cancer',
                        r'.*(?i)mesothelioma.*':'Mesothelioma',
                        r'.*(?i)non\-hodgkin.*':'Non-Hodgkin lymphoma',
                        r'.*(?i)hodgkin.*':'Hodgkin lymphoma',
                        r'.*(?i)leukemia.*':'Leukemia',
                        r'.*(?i)myeloma.*':'Multiple myeloma',
                        r'.*(?i)(rheumat|valvular).*heart.*':'Rheumatic heart disease',
                        r'.*RHD.*':'Rheumatic heart disease',
                        r'.*(?i)(non.?rheumatic|calcific.aort|degenerative.mitr).*':'Non-rheumatic valvular heart disease',
                        r'.*(?i)ischem.*heart.*':'Ischemic heart disease',
                        r'.*IHD.*':'Ischemic heart disease',
                        r'.*(?i)heart.*ischem.*':'Ischemic heart disease',
                        r'.*(?i)(stroke|intracerebral.hemorrhage|subarachnoid.hemorrhage).*':'Stroke',
                        r'.*(?i)hypertensive.*':'Hypertensive heart disease',
                        r'.*(?i)cardiomyopathy.*':'Cardiomyopathy and myocarditis',
                        r'.*(?i)myocarditis.*':'Cardiomyopathy and myocarditis',
                        r'.*(?i)fibrillation.*':'Atrial fibrillation and flutter',
                        r'.*(?i)aort.*aneurysm.*':'Aortic aneurysm',
                        r'.*(?i)peripheral\sart.*':'Peripheral artery disease',
                        r'.*(?i)endocarditis.*':'Endocarditis',
                        r'.*COPD.*':'Chronic obstructive pulmonary disease',
                        r'.*(?i)obstruct.*pulmonary.*':'Chronic obstructive pulmonary disease',
                        r'.*(?i)pneumoconiosis.*':'Pneumoconiosis',
                        r'.*(?i)silicosis.*':'Pneumoconiosis',
                        r'.*(?i)asbestosis.*':'Pneumoconiosis',
                        r'.*(?i)\scoal\s.*':'Pneumoconiosis',
                        r'.*(?i)asthma.*':'Asthma',
                        r'.*(?i)interstitial\slung.*':'Interstitial lung disease and pulmonary sarcoidosis',
                        r'.*(?i)sarcoidosis.*':'Interstitial lung disease and pulmonary sarcoidosis',
                        r'.*(?i)cirrhos.*':'Cirrhosis and other chronic liver diseases',
                        r'.*(?i)chronic.*liver.*':'Cirrhosis and other chronic liver diseases',
                        r'.*(?i)peptic\sulcer.*':'Upper digestive system diseases',
                        r'.*(?i)gastritis.*':'Upper digestive system diseases',
                        r'.*(?i)duodenitis.*':'Upper digestive system diseases',
                        r'.*(?i)reflux.*':'Upper digestive system diseases',
                        r'.*(?i)gastroesophageal.*':'Upper digestive system diseases',
                        r'.*(?i)appendi.*':'Appendicitis',
                        r'.*(?i)(ileus|intestinal)\sobstruction.*':'Paralytic ileus and intestinal obstruction',
                        r'.*(?i)hernia.*':'Inguinal, femoral, and abdominal hernia',
                        r'.*(?i)inflam.*bowel.*':'Inflammatory bowel disease',
                        r'.*(IBS|IBD).*':'Inflammatory bowel disease',
                        r'.*(?i)(vascular.intestin|mesenteric.vasc|intestinal.ischem).*':'Vascular intestinal disorders',
                        r'.*(?i)pancreatitis.*':'Pancreatitis',
                        r'.*(?i)alzheimer.*':'Alzheimer\'s disease and other dementias',
                        r'.*(?i)dementia.*':'Alzheimer\'s disease and other dementias',
                        r'.*(?i)parkinson.*':'Parkinson\'s disease',
                        r'.*(?i)epilep(sy|tic).*':'Epilepsy',
                        r'.*(?i)multiple\ssclero(sis|tic).*':'Multiple sclerosis',
                        r'.*(?i)motor.neuron.*':'Motor neuron disease',
                        r'.*(?i)gehrig.*':'Motor neuron disease',
                        r'.*lateral\ssclero(sy|tic).*':'Motor neuron disease',
                        r'.*(?i)(migraine|tension|cluster).*(headache)?.*':'Headache disorders',
                        r'.*(?i)conduct\sdisorder.*':'Conduct disorder',
                        r'.*(?i)schizo.*':'Schizophrenia',
                        r'.*(?i)(depressi|dysthymia).*':'Depressive disorders',
                        r'.*(?i)bipolar.*':'Bipolar disorder',
                        r'.*(?i)anxi.*':'Anxiety disorders',
                        r'.*(?i)(anorex|bulim).*':'Eating disorders',
                        r'.*(?i)(asperger|autis(tic|m)).*':'Autism spectrum disorders',
                        r'.*(ADHD|(?i)attention.deficit|hyperactiv).*':'Attention-deficit/hyperactivity disorder',
                        r'.*(?i)idiopath.*':'Idiopathic developmental intellectual disability',
                        r'.*(?i)alcohol.*':'Alcohol use disorders',
                        r'.*(?i)(opioid|cocaine|amphetamine|cannabis|marijuana|drug).*\sabuse.*':'Drug use disorders',
                        r'.*(CKD|(?i)chronic\skidney).*':'Chronic kidney disease',
                        r'.*(?i)(diabetes|diabetic).*':'Diabetes mellitus',
                        r'.*(?i)glomerulonephr.*':'Acute glomerulonephritis',
                        r'.*(?i)dermatit.*':'Dermatitis',
                        r'.*(?i)psoria.*':'Psoriasis',
                        r'.*(?i)(cellulitis|pyoderma|bacterial\sskin).*':'Bacterial skin diseases',
                        r'.*(?i)scabies.*':'Scabies',
                        r'.*(?i)fungal.*':'Fungal skin diseases',
                        r'.*(?i)viral\sskin.*':'Viral skin diseases',
                        r'.*(?i)acne.*':'Acne vulgaris',
                        r'.*(?i)alopecia.*':'Alopecia areata',
                        r'.*(?i)pruritus.*':'Pruritus',
                        r'.*(?i)urticari.*':'Urticaria',
                        r'.*(?i)decubit.*':'Decubitus ulcer',
                        r'.*(?i)(glaucoma|cataract|macular.degener|refraction|vision.loss).*':'Blindness and vision impairment',
                        r'.*(?i)hearing.*loss.*':'Age-related and other hearing loss',
                        r'.*(?i)rheumat.*arthrit.*':'Rheumatoid arthritis',
                        r'.*(?i)osteoarthritis.*':'Osteoarthritis',
                        r'.*(?i)back.*pain.*':'Low back pain',
                        r'.*(?i)neck.*pain.*':'Neck pain',
                        r'.*(?i)gout.*':'Gout',
                        r'.*(?i)(neural.tube|congenital.heart|cleft|down.syndrome|turner.syndrome|klinefelter.syndrome|congenital).*':'Congenital birth defects',
                        r'.*(?i)(urolithiasis|urinary.tract.infect|prostatic.hyperplasia|male.infertility).*':'Urinary diseases and male infertility',
                        r'.*(PMS|(?i)uterine.fibroid|polycystic|female.infertil|endometrios|genital.prolapse|premenstrual|gynecol).*':'Gynecological diseases',
                        r'.*(?i)(thalassemi|sickle.cell|g6pd|hemoglobinopath|hemolytic.anemia).*':'Hemoglobinopathies and hemolytic anemias',
                        r'.*(?i)(endocrine|metabolic|blood|immune).*disorder.*':'Endocrine, metabolic, blood, and immune disorders',
                        r'.*(?i)caries.*(deciduous|permanent).*':'Oral disorders',
                        r'.*(?i)periodontal.*diseas.*':'Oral disorders',
                        r'.*(?i)(edentulis|tooth.loss|oral.disorder).*':'Oral disorders',
                        r'.*(SIDS|(?i)sudden.infant.death).*':'Sudden infant death syndrome',
                        r'.*(?i)gallbladder.*':'Gallbladder and biliary diseases',
                        r'.*(?i)bil(e|iary).*':'Gallbladder and biliary diseases',
                        r'.*(?i)digest.*':'Other digestive diseases',
                        r'.*(?i)sense.organ.dis.*':'Other sense organ diseases',
                        f'.*(?i)intestinal.infect.*':'Other intestinal infectious diseases',
                        r'.*(?i)(cardiovascular|heart).*':'Other cardiovascular and circulatory diseases',
                        r'.*(?i)neurol.*':'Other neurological disorders',
                        r'.*(?i)mental.*':'Other mental disorders',
                        r'.*(?i)respiratory.*':'Other chronic respiratory diseases',
                        r'.*(?i)malignant.*':'Other malignant neoplasms',
                        r'.*(?i)(benign|in.situ|myelodysplat|myeloproliferat|hematopoietic).*(cancer|neoplasm).*':'Other neoplasms',
                        r'.*(?i)cancer.*':'Other malignant neoplasms',
                        r'.*(?i)infectio.*':'Other unspecified infectious diseases',
                        r'.*(?i)sexually.*':'Sexually transmitted infections excluding HIV',
                        r'.*(?i)nutritional.deficien.*':'Other nutritional deficiencies',
                        r'.*ALS.*':'Motor neuron disease',
                        r'.*(?i)(skin|subcutaneous).*disease.*':'Other skin and subcutaneous diseases',
                        r'.*(?i)musculoskel.*':'Other musculoskeletal disorders',
                        r'.*':'Other'})
m collections import OrderedDict
dict = OrderedDict()
for _ in range(int(input())):
    s = input()
    dict[s] = dict.get(s, 0) + 1
print(len(dict))
print(*[value for _, value in dict.items()])
rom collections import OrderedDict

glossary = OrderedDict()

glossary['string'] = 'A series of characters.'
glossary['comment'] = 'A note in a program that the Python interpreter ignores.'
glossary['list'] = 'A collection of items in a particular order.'
glossary['loop'] = 'Work through a collection of items, one at a time.'
glossary['dictionary'] = "A collection of key-value pairs."
glossary['key'] = 'The first item in a key-value pair in a dictionary.'
glossary['value'] = 'An item associated with a key in a dictionary.'
glossary['conditional test'] = 'A comparison between two values.'
glossary['float'] = 'A numerical value with a decimal component.'
glossary['boolean expression'] = 'An expression that evaluates to True or False.'

for word, definition in glossary.items():
    print("\n" + word.title() + ": " + definition)
Exemple #25
0
def init():
    MyDict = OrderedDict.OrderedDict()
    MyDict.createDict()
    return MyDict
Exemple #26
0
def play():

    actions = OrderedDict()
    actions[]



    player = Player()

    

    print('Escape from Cave Terror!')

    while True:
        room = world.tile_at(player.x, player.y)

        # print(player.x)
        # print(player.y)


        print(room.intro_text())
        room.modify_player(player)
        
        # Interactives rooms
        if room.x == 0 and room.y == 0:
            print("You have lost 50hp")
            player.hp = player.hp - 50

        if room.x == 2 and room.y == 3:
            print("You have lost 15hp")
            player.hp -= 15


        # Finish ga
        if player.hp < 1:
            print('PLAYER DIED')
            return
        if room.x == 1 and room.y == 0:
            print('YOU WIN')
            print(str(player.hp) + ' (hp)')
            return

        action_input = get_player_command()


        if action_input in ['n', 'N']:
            player.move_north()
            
        elif action_input in ['s', 'S']:
            player.move_south()
        elif action_input in ['e', 'E']:
            player.move_east()
        elif action_input in ['w', 'W']:
            player.move_west()
        elif action_input in ['A', 'a']:
            player.attack()
        elif action_input in ['sw', 'SW']:
            player.move_south()
            player.move_west()
        elif action_input in ['se', 'SE']:
            player.move_south()
            player.move_east()
        elif action_input in ['ne', 'NE']:
            player.move_north()
            player.move_east()
        elif action_input in ['nw', 'NW']:
            player.move_north()
            player.move_west()

        elif action_input in ['I', 'i']:        
            print(player.print_inventory())
            print (player.hp)

        elif action_input in ['h', 'H']:
            player.heal()

        elif action_input in ['q', 'Q']:
            print('Finished')
            return                       
                        
        else:
            print('Acción inválida')
 def __init__(self, name=None):
     self._columns = OrderedDict.OrderedDict()
     self._name = name