Ejemplo n.º 1
0
def argfilter(args):
  switches = []
  sys = []
  for arg in args:
    if arg[0] == '-':
      switches.append(arg)
    else:
      sys.append(arg)
  return switches, " ".join(sys)
Ejemplo n.º 2
0
def get_systematics(file, overrides={}, rename=lambda u: u, samples=False):
    """Reads `file` and returns a list of (uncertainty, type, {sample:
    value}).

    The parameter `overrides` allows to specify a dict of form
    {uncertainty: value}, and values of "x" n the systematics file are
    replaced by the one specified in the dict.

    A function passed as `rename` allows to alter the uncertainty name,
    _after_ all other processing has happened.

    The parameter `samples` can be set to `True` to obtain the available
    sample names defined in the systematics file.
    """
    reader = csv.DictReader(open(file))
    reader.fieldnames = map(str.strip, reader.fieldnames)
    sys_samples = reader.fieldnames[2:]

    if samples:
        return sys_samples

    sys = []
    # create a list whose elements are the tuples
    # (uncertainty, type, {sample:value})
    # row is a list of the items in the row
    for row in reader:
        # comment character
        # if the line is not empty
        if len(row) >0:            
            # print row
            # if the row starts with comment #
            if re.match("^#", row["Uncertainty"]):
                continue
            # end if re.match
        # end if len
        unc = row.pop("Uncertainty").strip()
        type = row.pop("Type").strip()
        # `row` is a dictionary with sample names as keys.  Strip spaces
        # from the actual value
        row = dict(map(lambda (k,v): (k, v.strip()), row.items()))
        if unc in overrides:
            row = dict(
                    map(
                        lambda (k,v): (k, overrides[unc] if v == "x" else v),
                        row.items()))
        sys.append((rename(unc), type, row))
    return sys
Ejemplo n.º 3
0
def AppendPythonPath():

    import sys
    import Tkinter,Tkconstants,tkFileDialog
    
    root = Tkinter.Tk()
    root.withdraw()
  
    options = {}
    options['initialdir'] = '/'
    options['mustexist'] = False
    options['parent'] = root
    options['title'] = 'Choose directory to add to PATH'
    newdir = tkFileDialog.askdirectory(**options)
    sys.append(newdir)

    print '\nDirectory add to PATH: ' + newdir + '\n'
Ejemplo n.º 4
0
    def _get_app_info(self):
        """Get information about the app.
        """

        info = dict()
        info['core_data'] = core_data = _get_core_data()
        info['extensions'] = extensions = self._get_extensions(core_data)
        page_config = self._read_page_config()
        info['disabled'] = page_config.get('disabledExtensions', [])
        info['local_extensions'] = self._get_local_extensions()
        info['linked_packages'] = self._get_linked_packages()
        info['app_extensions'] = app = []
        info['sys_extensions'] = sys = []
        for (name, data) in extensions.items():
            data['is_local'] = name in info['local_extensions']
            if data['location'] == 'app':
                app.append(name)
            else:
                sys.append(name)

        info['uninstalled_core'] = self._get_uninstalled_core_extensions()

        info['static_data'] = _get_static_data(self.app_dir)
        app_data = info['static_data'] or core_data
        info['version'] = app_data['jupyterlab']['version']
        info['publicUrl'] = app_data['jupyterlab'].get('publicUrl', '')

        info['sys_dir'] = self.sys_dir
        info['app_dir'] = self.app_dir

        info['core_extensions'] = core_extensions = _get_core_extensions()

        disabled_core = []
        for key in core_extensions:
            if key in info['disabled']:
                disabled_core.append(key)

        info['disabled_core'] = disabled_core
        return info
import sys
import os
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter
from plotting_functions import *
from sel_list import *

stdev = np.std
sqrt = np.sqrt
nullfmt = NullFormatter()

file1 = sys.argv[1]
time_offset = int(sys.argv[2])		# units of ns 

sys = []
sys.append(['Apo','steelblue',','])
sys.append(['ATP','cadetblue',','])
sys.append(['ssRNA','turquoise',','])
sys.append(['ssRNA+ATP','forestgreen',','])
sys.append(['ssRNA+ADP+Pi','limegreen',','])
sys.append(['ssRNA+ADP','orangered',','])
sys.append(['ssRNA+Pi','crimson',','])

nSys = len(sys)
nSel = len(sel)

# ----------------------------------------
# MAIN PROGRAM:

datalist1 = np.loadtxt(file1)
nSteps = len(datalist1)/nSys
Ejemplo n.º 6
0
    calc.set(isif=2)

    secban('Elastic tensor by internal routine')

    # Elastic tensor by internal routine
    Cij, Bij=cryst.get_elastic_tensor(n=5,d=0.33)
    print("Cij (GPa):", Cij/GPa)

    calc.clean()

    secban('C11 and C12 by hand')

    # Now let us do it (only c11 and c12) by hand
    sys=[]
    for d in linspace(-0.5,0.5,6):
        sys.append(cryst.get_cart_deformed_cell(axis=0,size=d))
    r=ParCalculate(sys,cryst.calc)
    ss=[]
    for s in r:
        ss.append([s.get_strain(cryst), s.get_stress()])
    # Plot strain-stress relation
    figure(3)

    ss=[]
    for p in r:
        ss.append([p.get_strain(cryst),p.get_stress()])
    ss=array(ss)
    lo=min(ss[:,0,0])
    hi=max(ss[:,0,0])
    mi=(lo+hi)/2
    wi=(hi-lo)/2
Ejemplo n.º 7
0
# ----------------------------------------
# VARIABLE DECLARATION

ref = sys.argv[1]		# full protein reference structure...
traj_loc = sys.argv[2]		# pointer to the directories of the systems...
out = sys.argv[3]		# output file name w/ extension

selection = 'protein'
alignment = 'protein and name CA and (resid 20:25 or resid 50:55 or resid 73:75 or resid 90:94 or resid 112:116 or resid 142:147 or resid 165:169 or resid 190:194 or resid 214:218 or resid 236:240 or resid 253:258 or resid 303:307)'

grab_frame = 50 	#grab a frame every 50 frames (100 ps);

flush = sys.stdout.flush

sys = []
sys.append(['AMBER_apo', 21, 150])		#
#sys.append(['AMBER_atp', 51, 100])		#
#sys.append(['AMBER_ssrna', 51, 100])		#
#sys.append(['AMBER_ssrna_atp', 51, 100])	#
#sys.append(['AMBER_ssrna_adp_pi', 51, 100])	#
#sys.append(['AMBER_ssrna_adp', 51, 100])	#
#sys.append(['AMBER_ssrna_pi', 51, 100])		#

# ----------------------------------------
# SUBROUTINES:

def ffprint(string):
        print '%s' %(string)
        flush()

# ----------------------------------------
Ejemplo n.º 8
0
import sys
sys.append("../Py2D")
sys.append("./Py2D")

def txt2json(txtfile):
    # create base dictionary:
    SET_SLOTS = False
    ont = dict.fromkeys(['type','requestable','discourseAct','system_requestable','method','informable'])
    ont['discourseAct'] = [
        "ack", 
        "hello", 
        "none", 
        "repeat", 
        "silence", 
        "thankyou"
    ] 
    ont['method'] = [
        "none", 
        "byconstraints", 
        "byname", 
        "finished", 
        "byalternatives", 
        "restart"
    ]
   
    # step through txt rules
    with open(txtfile+'.txt','r') as txtFILE:
        f = txtFILE.readlines()

        for i in range(len(f)):
            line = f[i]
            if line[0] == '#':
                continue
            if 'task' in line:
                continue
            if 'entity' in line:
                # assume entity comes before type:
                req = re.findall(r"[\w']+", line)
                continue
            if 'type' in line:
                req += re.findall(r"[\w']+", line) 
                for x in remove_from_req:
                    while x in req:
                        req.remove(x)  # this should remove all occurences.
                print 'requestable slots are (ie all slots)'
                req_final = copy.deepcopy(req)
                ont['requestable'] = req_final
                print ont['requestable']
                ont['informable'] = dict.fromkeys(req)
                # also set the breakup of informable and requestable slots via inform_req_lines - 
                # do this MANUALLY - easier! but gives some confidence/checks:
                sys = []
                for slot in req:
                    ans = raw_input('is slot: '+slot+' SYSTEM REQUESTABLE?')
                    if ans == 'y':
                        sys.append(slot)
                print 'system requestable slots are:'
                print sys
                ont['system_requestable'] = sys
                SET_SLOTS = True
                continue
            if 'method' in line:
                continue
            if 'discourseAct' in line:
                continue
            if SET_SLOTS:
                #for slot in ont['requestable']:
                for slot in req:
                    #print slot
                    #print line
                    #raw_input()
                    if slot in line and ('"' not in line):
                        count = 0
                        while ');' not in f[i+count]:
                            count += 1
                        values = f[i+1:i+count]
                        #raw_input('-- print values now:')
                        #print values
                        #raw_input('check')
                        vals = []
                        for v in values:
                            x = v.split('"')
                            vals.append(x[1])
                        print vals
                        print '^^ are for slot: ', slot
                        raw_input('check values parsed')
                        ont['informable'][slot] = vals
                        req.remove(slot)
                        break
    writeto = open(txtfile+'.json','w')
    json.dump(ont,writeto)
    writeto.close()
Ejemplo n.º 10
0
def list_extensions(app_dir=None, logger=None):
    """List the extensions.
    """
    logger = logger or logging
    app_dir = get_app_dir(app_dir)
    extensions = _get_extensions(app_dir)
    disabled = _get_disabled(app_dir)
    all_linked = _get_linked_packages(app_dir, logger=logger)
    app = []
    sys = []
    linked = []
    errors = dict()

    core_data = _get_core_data()

    # We want to organize by dir.
    sys_path = pjoin(get_app_dir(), 'extensions')
    for (key, value) in extensions.items():
        deps = extensions[key].get('dependencies', dict())
        errors[key] = _validate_compatibility(key, deps, core_data)
        if key in all_linked:
            linked.append(key)
        if value['path'] == sys_path and sys_path != app_dir:
            sys.append(key)
            continue
        app.append(key)

    logger.info('JupyterLab v%s' % __version__)
    logger.info('Known labextensions:')
    if app:
        logger.info('   app dir: %s' % app_dir)
        for item in sorted(app):
            version = extensions[item]['version']
            extra = ''
            if item in disabled:
                extra += ' %s' % RED_DISABLED
            else:
                extra += ' %s' % GREEN_ENABLED
            if errors[item]:
                extra += ' %s' % RED_X
            else:
                extra += ' %s' % GREEN_OK
            logger.info('        %[email protected]%s%s' % (item, version, extra))
            if errors[item]:
                msg = _format_compatibility_errors(item, version, errors[item])
                logger.warn(msg + '\n')

    if sys:
        logger.info('   sys dir: %s' % sys_path)
        for item in sorted(sys):
            version = extensions[item]['version']
            extra = ''
            if item in disabled:
                extra += ' %s' % RED_DISABLED
            else:
                extra += ' %s' % GREEN_ENABLED
            logger.info('        %s%s' % (item, extra))
            if errors[item]:
                extra += ' %s' % RED_X
            else:
                extra += ' %s' % GREEN_OK
            if item in linked:
                extra += '*'
            logger.info('        %[email protected]%s%s' % (item, version, extra))
            if errors[item]:
                msg = _format_compatibility_errors(item, version, errors[item])
                logger.warn(msg + '\n')

    if linked:
        logger.info('   linked extensions:')
        for item in sorted(linked):
            logger.info('        %s: %s' % (item, all_linked[item]))

    if len(all_linked) > len(linked):
        logger.info('   linked packages:')
        for key in sorted(all_linked.keys()):
            if (key in linked):
                continue
            logger.info('        %s: %s' % (key, all_linked[key]))

    # Handle uninstalled and disabled core packages
    uninstalled_core = _get_uinstalled_core_extensions(app_dir)
    if uninstalled_core:
        logger.info('\nUninstalled core extensions:')
        [logger.info('    %s' % item) for item in sorted(uninstalled_core)]

    core_extensions = _get_core_extensions()

    disabled_core = []
    for key in core_extensions:
        if key in disabled:
            disabled_core.append(key)

    if disabled_core:
        logger.info('\nDisabled core extensions:')
        [logger.info('    %s' % item) for item in sorted(disabled_core)]
Ejemplo n.º 11
0
import os
import sys

try:
    from gitcrawler import collect_details as detail
except:
    sys.append('/media/laxmena/Bazinga/Crawler/GIT-beta')
    from gitcrawler import collect_details as detail

count = 0
crawl_list = []
#Get initial Username from the User
username = detail.get_username()
crawl_list.append(username)

if not os.path.exists('/home/laxmena/gitcrawler'):
    os.mkdir('/home/laxmena/gitcrawler')
for i in crawl_list:
    try:
        file_name = '/home/laxmena/gitcrawler/' + i + '.txt'
        f = open(file_name,'w')
        f.write('Personal Details:\n')
        f.write('-'*50 + '\n')

        print ('Scraping Details of %s' % i)
        for itr in detail.personal_details(i):
            f.write(itr)
            f.write('\n')
        f.write('\n\nAll Repositories:\n')
        f.write('-'*50 + '\n')
        f.write('Repository Name\n')
#!/usr/bin/env python
'''
NPR 2015-12-06

http://www.npr.org/2015/12/06/458661972/transform-words-with-an-additional-letter-in-this-weeks-puzzle

Name a state capital. Drop one of its letters. 
The remaining letters can be rearranged to name of another major city 
in the United States. What is it? 
There are two different answers, and you should find both of them.
'''

import sys
sys.append('..')
from nprcommontools import sort_string

from nltk.corpus import wordnet as wn, gazetteers
import re

# U.S. States
states = set(gazetteers.words('usstates.txt'))

# capitals and major cities
cities = set(); capitals = set()
for synset in wn.all_synsets():
    d = synset.definition()
    for state in states:
        if state in d and 'city' in d:
            for l in synset.lemma_names():
                if l[0] == l[0].upper():
                    cities.add(l)
#-*- coding: utf-8 -*-
# 此程式用來檢查 OrderQuote.dat 中的時間是否順序正確
import os
import collections
import sys
from subprocess import call
import unittest
import subprocess
import re
import time
import shlex
import shutil
from datetime import datetime

if(len(sys.argv)<2):
    sys.append('/home/newemg/data/OrderQuote.dat')

arg_names = ['command', 'file']
args = dict(zip(arg_names, sys.argv))
Arg_list = collections.namedtuple('Arg_list', arg_names)
args = Arg_list(*(args.get(arg, None) for arg in arg_names))

class CheckQrderQuoteTimeSeq(unittest.TestCase):
    def setUp(self):
        pass
    def tearDown(self):
        pass

    def getLineInfo(self, line):
        ret=''
        if(line[41:133]=='                                                                                            '):
Ejemplo n.º 14
0
#!/usr/bin/env python
#-*-coding: utf-8-*-
## File name: ub_model/mr/mr_fac.py

import os
import sys
import logging
sys.append('../../common')
from mr import Mr
from utils import Utils

class MrFac:
  def __init__(self):
    self.mr = None

  def getmr(self, mrname, productline):
    abspath = self.getmr_abspath(mrname)
    self.mr = Utils.getinstanceffile(abspath, Mr, productline)

    return self.mr

  def getmr_abspath(self, mrname):
    if mrname != None and not mrname.endswith('.py'):
      mrname = '%s.py' %(mrname)
    
    abspath = ''
    files = os.listdir('.')

    for f in files:
      if f == mrname:
        abspath = os.path.abspath('./%s' %(mrname))