示例#1
0
def restrain_dihedrals(resName, atomNameList, Type, phi, dphi, fc):
    utils.update("restrain_dihedrals", "will add restraints for {0} (all chains)...".format(resName))

    # Every chain has its own .itp file, so we loop through every file:
    for letter in universe.get('d_chain'):
        # This is to make sure we don't have multiple headers when we add multiple different restraints.
        first = False
        if not "[ dihedral_restraints ]" in open("topol_Protein_chain_{0}.itp".format(letter)).read():
            first = True

        # Append to the end of relevant .itp file:
        with open("topol_Protein_chain_{0}.itp".format(letter), 'a') as file:
            if first:
                file.write("[ dihedral_restraints ]\n")
                file.write("; ai aj ak al type phi dphi fc\n")

            # Atomcount resets for every separate .itp file.
            atomCount = 0
            for residue in universe.get('d_residues'):
                # Dictionary resets for every residue, as we can of course have
                # multiple ASPs or GLUs in one chain.
                dictionary = {}
                for atom in residue.d_atoms:
                    # Only increase atomcount when we read the relevant chain:
                    if residue.d_chain == letter:
                        atomCount += 1

                        if residue.d_resname == resName and atom in atomNameList:
                            dictionary[atom] = atomCount

                if len(dictionary) == 4:
                    utils.update("restrain_dihedrals", "adding restraints for chain {0} {1}-{2}...".format(residue.d_chain, resName, residue.d_resid))
                    for atom in atomNameList:
                        file.write("{:<6d} ".format(dictionary[atom]))
                    file.write(" {}  {}  {}  {}\n".format(Type, phi, dphi, fc))
示例#2
0
def set(user, user_id, text):

	muscle_groups = defaultdict(list)

	text_muscles = [x.strip() for x in re.split(',|and',text) if x.strip()]
	
	#=====[ Check to see if each item in text matches against a muscle group ]=====
	for muscle in text_muscles:
		
		#=====[ Checks for individual muscles: e.g. lats, traps]=====
		if muscle in muscles:
			muscle_groups['specific'].append(muscle)
		#=====[ Checks for muscle groups: e.g. back, legs ]=====
		elif muscle in grouped_muscles:
			muscle_groups['group'].append(muscle)

	#=====[ If no muscle groups found, inform user of possible muscle groups to specify ]===== 
	if not len(muscle_groups):
		ut.send_response(GOAL_EXERCISES, user_id)
		return 
			
	#=====[ Update user object ]=====            
	user.goals = muscle_groups
	for key in user.goals.keys():
		print key
		for key2 in user.goals[key]:
			print key2
	ut.update(user_id, user)
	
	message = UPDATED_GOALS + ', '.join(user.goals['specific'])
	message += ', ' + ', '.join(user.goals['group']) if user.goals['group'] else ''

	ut.send_response(message, user_id)
示例#3
0
文件: search.py 项目: 153672/8600_hw1
 def __init__(self, state, parent=None, action=None, path_cost=0):
     "Create a search tree Node, derived from a parent by an action."
     # state = force_hashable(state)
     update(self, state=state, parent=parent, action=action,
            path_cost=path_cost, depth=0)
     if parent:
         self.depth = parent.depth + 1
示例#4
0
def end_user_workout(user, user_id, workout):

	print 'in end workout'
	#=====[ Clear process timers to remind user to start next set ]=====
	clear_timers(user)

	#=====[ Record current workout and end time. Update user ]=====
	if workout.end():

		ut.send_response(END_WORKOUT_MESSAGE, user_id)

		#=====[ Send workout summary, stats, and spider chart ]=====
		ut.send_response(workout.get_summary(), user_id)
		ut.send_response(workout.get_stats(), user_id)

		ut.send_response(workout.summarize_muscle_groups(4), user_id)
		#=====[ Add workout to list of past workouts and put in idle mode ]=====
		user.add_workout(workout)

	else:
		user.current_workout = None
		user.status = 'idle'
		ut.update(user_id, user)
		
		ut.send_response(NO_WORKOUT_LOGGED, user_id)
	
	ut.update(user_id, user)
示例#5
0
 def __init__(self, name):
     update(self,
            name=name,
            pos=Struct(x=0.0, y=0.0, z=0.0),
            simulator=Morse())
     inst = getattr(self.simulator, self.name)
     inst.robot_pose.subscribe(self.setpos)
示例#6
0
def update():
    if not session:
       return redirect('/')
    if request.method=="POST":
       user_dict={k:v[0] for k,v in dict(request.form).items()}
       print user_dict
       if user_dict.has_key('oldpasswd'):
           username=session['username']
           data1={}
           data1['username']=username
           field=['id','username','name','password','phone','email','role','status']
           result=utils.get_one(table,field,data1)
           if user_dict['oldpasswd']==result['msg']['password']:
               info={}
               field=['id','password']
               info['id']=result['msg']['id']
               info['password']=user_dict['newpasswd']
               util.WriteLog("update_psswd","/tmp/info.log").info("update_passwd:%s"%session['username'])
               data=utils.update(table,field,info)
               return json.dumps(data)
           else:
               result={'code':1,'msg':'oldpasswd is error'}
               util.WriteLog('update_passwd','/tmp/error.log').error("update_password:%s"%session['username'])  
               return json.dumps(result)    
       else:
           field=[]
           util.WriteLog("update","/tmp/info.log").info("update:%s"%session['username'])
           data=utils.update(table,field,user_dict)
           return json.dumps(data)
示例#7
0
def order_deal():
    if request.method == 'POST':
        data = {k: v[0] for k, v in dict(request.form).iteritems()}
        print '111111111111111111data'
        print data
        data['status'], data['deal_person'] = 1, session['username']
        print '\n'
        print data
        field = ['status', 'deal_person', 'deal_desc']
        result = update('work_order', field, data)
        #	if result['code'] == 0:
        return json.dumps(result)
#			result = result['msg']
#			return redirect('/orderlist/',result=result,info=session)
#		result = {'errmsg':'deal is fail'}
#		return render_template('order_list.html',result=result)
    if request.method == 'GET':
        orderid = request.args.get('id', '')
        orderdesc = request.args.get('deal_desc', '')
        data = {}
        data['id'], data['deal_desc'], data['status'], data[
            'deal_person'] = orderid, orderdesc, 1, session['username']
        print "\n"
        print "deal----deal"
        print data
        field = ['id', 'deal_desc', 'status', 'deal_person']
        result = update('work_order', field, data)
        return json.dumps(result)
示例#8
0
    def save_report_player_data(self, arr, report_type):
        count_sql = "select count(*) cc from test.wcl_report_player where report_id = %(report_id)s " \
                    "and player_name = %(player_name)s and report_type = %(report_type)s"
        sql = "insert into test.wcl_report_player (report_id,report_type,player_rank,player_name," \
              "player_amount,player_per_second,player_performance) values " \
              "(%(report_id)s, %(report_type)s, %(player_rank)s, %(player_name)s, " \
              "%(player_amount)s, %(player_per_second)s, %(player_performance)s)"
        with utils.connect_by_code('test001') as conn:
            for i, o in enumerate(arr):
                x = utils.query_one(
                    conn, count_sql, {
                        "report_id": self.report.id,
                        "player_name": o['name'],
                        "report_type": report_type
                    })
                if x.cc == 0:
                    utils.update(
                        conn, sql, {
                            "report_id": self.report.id,
                            "report_type": report_type,
                            "player_rank": i + 1,
                            "player_name": o['name'],
                            "player_amount": o['amount'],
                            "player_per_second": o['dps'],
                            "player_performance": o['performance'],
                        })

        pass
示例#9
0
def process(fname, d_model=1, d_ALI='A', d_chain=[], resetResId=False):
    basename = os.path.basename(fname)
    universe.add('d_pdbName', basename[0:len(basename) - 4])
    universe.add('d_model', d_model)
    universe.add('d_ALI', d_ALI)

    load(fname, d_model, d_ALI, d_chain)

    # Update d_chain from [] to a list of actual chains used:
    d_chain = []
    for residue in universe.get('d_residues'):
        d_chain.append(residue.d_chain)
    d_chain = list(set(d_chain))
    d_chain.sort()
    universe.add('d_chain', d_chain)

    utils.update(
        "process", 'file={0}, MODEL#={1}, ALI={2}, chain(s)={3}...'.format(
            fname, d_model, d_ALI, d_chain))

    # Write processed.pdb to file:
    utils.update(
        "process", "writing processed .pdb file to {}_PR1.pdb...".format(
            universe.get('d_pdbName')))
    write("{0}_PR1.pdb".format(universe.get('d_pdbName')))
示例#10
0
def run(gmxPath="/usr/local/gromacs", options=""):
    # If we do a non-constant-pH simulation, gen_constantph will not make index.ndx,
    # so do it here.
    if not os.path.isfile('index.ndx'):
        utils.generate_index()

    # User update:
    if options == "":
        utils.update("run", "gmxPath={0}".format(gmxPath))
    else:
        utils.update(
            "run",
            "gmxPath={0}, additional options= {1}".format(gmxPath, options))

    with open("run.sh", 'w') as file:
        file.write("#!/bin/bash\n\n")

        file.write("# Gromacs version to use:\n")
        file.write("source {0}/bin/GMXRC\n\n".format(gmxPath))

        file.write(
            "gmx grompp -f MD.mdp -c {0} -p topol.top -n index.ndx -o MD.tpr -r {0}\n"
            .format(universe.get('d_nameList')[-1]))
        file.write(
            "gmx mdrun -deffnm MD -v -c {0}_MD.pdb -x MD.xtc {1}\n".format(
                universe.get('d_pdbName'), options))

    os.system("chmod +x run.sh")
示例#11
0
def saveresponse():
    vidname = request.args.get('vidname', None, type=str)
    egosummary = request.args.get('ego', None, type=str)
    sursummary = request.args.get('sur', None, type=str)
    total = request.args.get('total', None, type=int)
    utils.update(vidname, egosummary, sursummary)
    return utils.getstats(request.args.get('vidname', None, type=str),total)
示例#12
0
 def __init__(self, states, gamma, terminals):
     update(self,
            P={},
            reward={},
            states=states,
            gamma=gamma,
            terminals=terminals)
示例#13
0
文件: rl.py 项目: yeesian/aima-python
 def __init__(self, states, gamma, terminals):
     update(self,
            P={},
            reward={},
            states=states,
            gamma=gamma,
            terminals=terminals)
示例#14
0
def reset():
    utils.update("reset", "writing reset.sh...")

    with open("reset.sh", "w+") as file:
        file.write("#!/bin/bash\n\n")
        
        file.write("if [ -f \"%s_MD.pdb\" ]\nthen\n" % universe.get('d_pdbName'))
        file.write("\tread -p \"Warning: simulation has finished. Proceed? (y)\" var\n")
        file.write("else\n")
        file.write("\trm -rf \\_\\_py* charmm*\n")
        file.write("\trm -f *.itp *.top *.mdp *.tpr *.log *.ndx *.edr *.trr *.xtc *.cpt *.dat *.pdf *.xvg\n")
        file.write("\trm -f \\#*\\# EM.pdb NVT.pdb NPT.pdb MD.pdb \n")
        file.write("\trm -f step*.pdb buffer.pdb %s_*.pdb\n" % universe.get('d_pdbName'))
        file.write("\trm -f run.sh reset.sh jobscript.sh universe\n")                   
        file.write("fi\n\n")

        file.write("if [ \"${var}\" = \"y\" ]\nthen\n")
        file.write("\trm -rf \\_\\_py* charmm*\n")
        file.write("\trm -f *.itp *.top *.mdp *.tpr *.log *.ndx *.edr *.trr *.xtc *.cpt *.dat *.pdf *.xvg\n")
        file.write("\trm -f \\#*\\# EM.pdb NVT.pdb NPT.pdb MD.pdb \n")
        file.write("\trm -f step*.pdb buffer.pdb %s_*.pdb\n" % universe.get('d_pdbName'))
        file.write("\trm -f run.sh reset.sh jobscript.sh universe\n")            
        file.write("fi\n\n")

    os.system("chmod +x reset.sh")
示例#15
0
def modpwd():
    data = {k: v[0] for k, v in dict(request.form).items()}
    if 'password' in data.keys():
        if not data['password'] or not data['newpassword'] or not data[
                'renewpassword']:
            errmsg = 'password can not be null'
            return json.dumps({'code': '1', 'errmsg': errmsg})
    else:
        if not data['newpassword'] or not data['renewpassword']:
            errmsg = 'password can not be null'
            return json.dumps({'code': '1', 'errmsg': errmsg})
    try:
        condition = [
            "{}='{}'".format('password', v[0]) for k, v in data.items()
            if k == 'newpassword'
        ]
        id = session.get('id')
        if session.get('role') == 1:
            utils.update('user', condition, data['id'])
            return json.dumps({'code': '0', 'result': 'modify completed!'})
        else:
            if data['password'] == utils.get_one('user', fields,
                                                 data)['password']:
                utils.update('user', condition, data['id'])
                return json.dumps({'code': '0', 'result': 'modify completed!'})
            return json.dumps({'code': '1', 'errmsg': 'wrong old password'})
    except:
        errmsg = "modify failed"
        return json.dumps({'code': '1', 'errmsg': errmsg})
示例#16
0
文件: app.py 项目: hjshiwbd/notes
def save_report(report_list):
    count_sql = "select count(*) cc from test.wcl_report where report_id = %(report_id)s"
    sql = "insert into test.wcl_report (report_id,title,report_date,link) values (%(report_id)s,%(title)s,%(report_date)s,%(link)s)"
    with utils.connect_by_code('test001') as conn:
        for o in report_list:
            x = utils.query_one(conn, count_sql, o)
            if x.cc == 0:
                utils.update(conn, sql, o)
示例#17
0
 def __init__(self, name, type, pos, color, size):
     update(self,
            name=name,
            type=type,
            pos=pos,
            color=color,
            size=size,
            simulator=Morse())
示例#18
0
def jobscript(jobName, jobTime, nodes, ntasks, queue):
    utils.update(
        "jobscript",
        "jobName={0}, jobTime={1}(hrs), nodes={2}, ntasks={3}, queue={4}...".
        format(jobName, jobTime, nodes, ntasks, queue))

    file = open("jobscript.sh", 'w')

    def writeHead(param, value):
        file.write("#SBATCH --%s=%s\n" % (param, value))

    def moduleLoad(value):
        file.write("module load {0}\n".format(value))

    file.write("#!/bin/bash\n\n")

    writeHead("time", "%d-%.2d:00:00" % (int(jobTime / 24), jobTime % 24))
    writeHead("nodes", nodes)
    # writeHead("ntasks", ntasks)
    writeHead("partition", queue)
    writeHead("job-name", jobName)
    writeHead("mail-user", "*****@*****.**")
    writeHead("mail-type", "ALL")
    file.write("#SBATCH -C gpu --gres=gpu:1\n\n")

    moduleLoad("cmake/latest")
    moduleLoad("gcc/7.4")
    moduleLoad("cuda/10.2")

    file.write('\n')

    if universe.get('ph_constantpH'):
        file.write(
            "# compile our custom Gromacs version on cluster backend node\n")
        file.write("mkdir build\n")
        file.write("cd build\n")
        file.write(
            "CC=gcc-7 CXX=g++-7 cmake ~/gromacs-constantph -DGMX_USE_RDTSCP=ON -DCMAKE_INSTALL_PREFIX=${PWD}/.. -DGMX_BUILD_OWN_FFTW=ON -DGMX_GPU=CUDA\n"
        )
        file.write("make -j 12\n")
        file.write("make install -j 12\n")
        file.write("cd ..\n")
        file.write("rm -r build\n")
        file.write("source ${PWD}/bin/GMXRC\n\n")
    else:
        file.write("module load gromacs/2021.1\n\n")

    file.write(
        "gmx grompp -f MD.mdp -c {0} -p topol.top -n index.ndx -o MD.tpr -r {0}\n"
        .format(universe.get('d_nameList')[-1]))

    if universe.get('ph_constantpH'):
        file.write(
            "gmx mdrun -deffnm MD -c {0}_MD.pdb -x MD.xtc -pme cpu -ntmpi 1\n".
            format(universe.get('d_pdbName')))
    else:
        file.write("gmx mdrun -deffnm MD -c {0}_MD.pdb -x MD.xtc\n".format(
            universe.get('d_pdbName')))
示例#19
0
def process(message):
    out = [[], []]
    print(message.type)

    if message.content.lower().startswith("update"):
        out[0].append([message.channel, "ok"])
        update()

    return [[], []]
示例#20
0
def update():
    data = dict((k,v[0]) for k,v in dict(request.form).items())
    if data.get('newpassword'):
        conditions = ["password='******'"% data.get('newpassword')]
    else:
        conditions = [ "%s='%s'" %  (k,v) for k,v in data.items() if v !='id']
    utils.update('user',conditions,data['id'])
    session['role'] = data['role']
    return json.dumps({'code':1,'result':'update completed!'})
示例#21
0
 def __init__(self, state, parent=None, action=None, path_cost=0, improvement = 1000.0, inside_convex= False):
     "Create a search tree Node, derived from a parent by an action."
     utils.update(self, state=state, parent=parent, action=action,
            path_cost=path_cost, depth=0, improvement= improvement, inside_convex= inside_convex)
     self.state = state
     if parent:
         self.parent = parent
         self.depth = parent.depth + 1
         self.improvement = linfDistance([np.array(self.state[1])], [np.array(parent.state[1])], 'chebyshev')[0,0]
示例#22
0
def counter():
    current_id = request.args.get('id')
    resp = make_response(send_file('img/1x1.png', cache_timeout=-1))
    cookie = request.cookies.get('some cookie')
    if cookie is None:
        cookie = token_urlsafe(5)
    update("BD.db", current_id, cookie)
    if cookie:
        resp.set_cookie('some cookie', str(cookie), max_age=1296000)
    return resp
示例#23
0
def start(user):

	user_id = user.get_id()

	#=====[ Start workout ]=====
	user.status = "feedback"
	user.status_state = 0
	ut.update(user_id, user)

	ut.send_response(FEEDBACK_QUESTION, user_id)
示例#24
0
 def __init__(self, state, parent=None, action=None, path_cost=0):
     "Create a search tree Node, derived from a parent by an action."
     update(self,
            state=state,
            parent=parent,
            action=action,
            path_cost=path_cost,
            depth=0)
     if parent:
         self.depth = parent.depth + 1
示例#25
0
def update():
	if request.method=="GET":
		uid = request.args.get('id','')
		user = utils.inquire(uid)
		return render_template('update.html',user=user)
	if request.method=="POST":
		user = {k:v[0] for k,v in dict(request.form).items()}	
		print user
		utils.update(user)
		return redirect('/list/')
示例#26
0
 def __init__(self, vars, domains, neighbors, constraints):
     "Construct a CSP problem. If vars is empty, it becomes domains.keys()."
     vars = vars or domains.keys()
     update(self,
            vars=vars,
            domains=domains,
            neighbors=neighbors,
            constraints=constraints,
            initial=(),
            curr_domains=None,
            nassigns=0)
示例#27
0
文件: rl.py 项目: yeesian/aima-python
 def __init__(self, mdp, pi):
     update(self,
            pi = pi,
            mdp = self.LearntMDP(mdp.states,mdp.gamma,mdp.terminals),
            U = {},
            Ns_sa = {s:{a:{t:0 for (p,t) in mdp.T(s,a)}
                        for a in mdp.actlist}
                     for s in mdp.states},
            Nsa = {s:{a:0. for a in mdp.actlist}
                   for s in mdp.states},
            s = None,
            a = None)
示例#28
0
def energy_pcouple():
    gen_mdp('NPT')

    utils.update("energy_pcouple",
                 "running gmx grompp and mdrun for pressure coupling...")

    os.system(
        "gmx grompp -f NPT.mdp -c {0} -p topol.top -o NPT.tpr -r {0} >> builder.log 2>&1"
        .format(universe.get('d_nameList')[-1]))
    os.system("gmx mdrun -deffnm NPT -c NPT.pdb >> builder.log 2>&1")

    utils.add_to_nameList("NPT.pdb")
示例#29
0
def energy_minimize():
    gen_mdp('EM')

    utils.update("energy_minimize",
                 "running gmx grompp and mdrun for energy minimization...")

    os.system(
        "gmx grompp -f EM.mdp -c {0} -p topol.top -o EM.tpr -r {0} >> builder.log 2>&1"
        .format(universe.get('d_nameList')[-1]))
    os.system("gmx mdrun -deffnm EM -c EM.pdb >> builder.log 2>&1")

    utils.add_to_nameList("EM.pdb")
示例#30
0
def up():
    if not session:
        return redirect('/logout/')
    if request.method == 'POST':
        dat = {k: v[0] for k, v in dict(request.form).items()}
        print dat
        data = update("user", filed, dat)
        return json.dumps(data)
        # return redirect('/login/')
    dat = {k: v[0] for k, v in dict(request.args).items()}
    print dat
    data = update("user", filed, dat)
    return json.dumps(data)
示例#31
0
def upda():
    if not session:
        return redirect('/logout/')
    if request.method == 'POST':
        filed = ['id', 'username', 'password']
        dat = {k: v[0] for k, v in dict(request.form).items()}
        print dat
        data = update("user", filed, dat)
        return json.dumps(data)
    dat = {k: v[0] for k, v in dict(request.args).items()}
    print dat
    data = update("user", filed, dat)
    return json.dumps(data)
示例#32
0
def add_water():
    utils.update("add_water", "running gmx solvate...")
    
    os.system("gmx solvate -cp {0} -o {1}_SOL.pdb >> builder.log 2>&1".format(universe.get('d_nameList')[-1], universe.get('d_pdbName')))

    # To update d_residues.
    load("{0}_SOL.pdb".format(universe.get('d_pdbName')))

    # To update topol.top.
    topol.add_mol("{0}.ff/{1}.itp".format(universe.get('d_modelFF'), universe.get('d_modelWater')), "Include water topology", "SOL", countRes('SOL'))

    # To update d_nameList.
    utils.add_to_nameList("{0}_SOL.pdb".format(universe.get('d_pdbName')))
示例#33
0
	def process(self, text, user, user_id):
		""" 
			Processes user input for a given state

			state = NOT_STARTED ---> ask user to start
			state = IN_WORKOUT ---> log current set reported by user

			Returns bool representing successful parse and whether we should move on to next set

		"""

		#=====[ If user has not started workout ]=====
		if self.state == NOT_STARTED:
			if 'yes' in text:

				#=====[ hard coding timers for now ]=====
				self.template.workout.timer = [45, 60]
				user.timer = self.template.workout.timer
				ut.update(user_id, user)

				self.state = IN_WORKOUT
				self.workout_state = (0, -1)
				return (True, True)

			else:
				ut.send_response(START_WORKOUT,user_id)
				return (False, False)

		#=====[ If in workout, log state ]=====
		elif self.state == IN_WORKOUT:
			sub_state, set_state = self.workout_state

			user_set = ut.extract_exercise(text)

			if user_set:

				template_workout = self.template.workout
				sub_state, set_state = self.workout_state

				xsets = template_workout.subroutines[sub_state].get_flattened_sets()
				user_set.exercise = xsets[set_state].exercise

				#=====[ Log set and give feedback ]=====
				workout_log.log_set(user_set, self.workout, user, user_id)
				ut.send_response('Got your last set to be: ' + str(user_set), user_id)

				self.prev_user_set = user_set
				return (self.cur_set_feedback(user_set, xsets[set_state], user_id), True)
			else:
				ut.send_response('Exercise not recognized, please retry', user_id)
				return (False, False)
示例#34
0
def add_box(d_boxMargin, d_boxType='cubic'):
    utils.update("add_box", "adding box using gmx editconf (boxMargin = {0}, boxType = {1})...".format(d_boxMargin, d_boxType))

    os.system("gmx editconf -f {0} -o {1}_BOX.pdb -d {2} -bt {3} >> builder.log 2>&1".format(universe.get('d_nameList')[-1], universe.get('d_pdbName'), d_boxMargin, d_boxType))

    # To set d_boxMargin and d_boxType.
    universe.add('d_boxMargin', d_boxMargin)
    universe.add('d_boxType', d_boxType)

    # To update d_box.
    load("{0}_BOX.pdb".format(universe.get('d_pdbName')))

    # To update d_nameList.
    utils.add_to_nameList("{0}_BOX.pdb".format(universe.get('d_pdbName')))
示例#35
0
def energy_tcouple():
    gen_mdp('NVT')

    utils.update("energy_tcouple",
                 "running gmx grompp and mdrun for temperature coupling...")

    os.system(
        "gmx grompp -f NVT.mdp -c {0} -p topol.top -o NVT.tpr -r {0} >> builder.log 2>&1"
        .format(universe.get('d_nameList')[-1]))
    os.system(
        "gmx mdrun -deffnm NVT -c {0}_NVT.pdb >> builder.log 2>&1".format(
            universe.get('d_pdbName')))

    utils.add_to_nameList("{0}_NVT.pdb".format(universe.get('d_pdbName')))
示例#36
0
def add_ions(neutral=True, conc=0, pname='NA', nname='CL'):
    if (not neutral) and (conc == 0):
        utils.update("add_ions", "no ions will be added...")
        return

    if neutral:
        utils.update("add_ions", "will add ions ({}/{}) to neutralize the system...".format(pname, nname))

    if conc > 0:
        utils.update("add_ions", "will add ions ({}/{}) for target concentration = {} mmol/ml...".format(pname, nname, conc))

    # Generate IONS.mdp (just a dummy required).
    os.system('touch IONS.mdp')

    # Add ion topology to topol.top.
    topol.add_mol("{0}.ff/ions.itp".format(universe.get('d_modelFF')), "Include ion topology")

    # Run gmx grompp and genion.
    utils.update("add_ions", "running gmx grompp and genion to add ions...")

    os.system("gmx grompp -f IONS.mdp -c {0} -p topol.top -o IONS.tpr >> builder.log 2>&1".format(universe.get('d_nameList')[-1]))

    if neutral:
        os.system("gmx genion -s IONS.tpr -o {0}_ION.pdb -p topol.top -pname {1} -nname {2} -conc {3} -neutral >> builder.log 2>&1 << EOF\nSOL\nEOF".format(universe.get('d_pdbName'), pname, nname, conc))
    else:
        os.system("gmx genion -s IONS.tpr -o {0}_ION.pdb -p topol.top -pname {1} -nname {2} -conc {3} >> builder.log 2>&1 << EOF\nSOL\nEOF".format(universe.get('d_pdbName'), pname, nname, conc))

    # To update d_residues.
    load("{0}_ION.pdb".format(universe.get('d_pdbName')))

    # To update d_nameList.
    utils.add_to_nameList("{0}_ION.pdb".format(universe.get('d_pdbName')))
示例#37
0
 def save_player_data(self, arr):
     count_sql = 'select count(*) cc from test.wcl_player where name = %(name)s and class = %(class)s'
     insert_sql = 'insert into test.wcl_player (`name`,`class`) values (%(name)s,%(class)s)'
     with utils.connect_by_code('test001') as conn:
         for i, o in enumerate(arr):
             x = utils.query_one(conn, count_sql, {
                 "name": o['name'],
                 "class": o['class']
             })
             if x.cc == 0:
                 utils.update(conn, insert_sql, {
                     "name": o['name'],
                     "class": o['class']
                 })
     pass
示例#38
0
def main():
    loader = FreednsConfigLoader()
    parser = OptionParser(option_list=loader.options, version=loader.version)
    (options, args) = parser.parse_args()
    try:
        loader.set_timeout(options.timeout)
        loader.set_auth(options.username, options.password)
        res = utils.request(loader.get_request_url(), loader.timeout)
        utils.update(res, loader.timeout)
    except Exception, e:
        import sys
        import traceback

        sys.stderr.write(traceback.format_exc())
        parser.print_help()
示例#39
0
文件: rl.py 项目: yeesian/aima-python
 def __init__(self,mdp,pi,alpha=None):
     update(self,
            pi = pi,
            U = {s:0. for s in mdp.states},
            Ns = {s:0 for s in mdp.states},
            s = None,
            a = None,
            r = None,
            gamma = mdp.gamma,
            terminals = mdp.terminals,
            reached_states = set())
     
     if alpha:
         self.alpha = alpha
     else:
         self.alpha = lambda n: 60./(59+n) # page 837
示例#40
0
def redirect():
    field = ['status']
    if not session:
        return redirect('/login/')
    if request.method == 'POST':
        data = {k: v[0] for k, v in dict(request.form).items()}
        data['status'] = 2
        result = utils.update('ops_jobs', field, data)
        return json.dumps(result)

    data = {k: v[0] for k, v in dict(request.args).items()}
    data['deal_time'] = time.strftime('%Y-%m-%d %H:%M')
    data['status'] = '1'
    data['deal_persion'] = session['username']
    result = utils.update('ops_jobs', field, data)
    return json.dumps(result)
示例#41
0
文件: rl.py 项目: yeesian/aima-python
 def __init__(self,mdp,alpha=None,Ne=5,Rplus=2):
     update(self,
            Q = {s:{a:0. for a in mdp.actlist} if s not in mdp.terminals
                 else {None:0.} for s in mdp.states},
            Nsa = {s:{a:0. for a in mdp.actlist}
                 for s in mdp.states},
            s = None,
            a = None,
            r = None,
            Ne = Ne,
            Rplus = Rplus,
            gamma = mdp.gamma,
            terminals = mdp.terminals)
     
     if alpha is None:
         self.alpha = lambda n: 60./(59+n) # page 837
     else:
         self.alpha = alpha
示例#42
0
def start(user, workout_template=None):
	""" Initializes users workout fields """

	user_id = user.get_id()
	
	user.time = datetime.datetime.now()
	user.status ="workout"

	#=====[ Updates user status state depending on whether workout is guided for free, manual entry ]=====
	if workout_template:
		user.status_state = GUIDED_WORKOUT
		user.workout_guider = WorkoutGuider(user_id, workout_template)

		#=====[ START GUIDED WORKOUT ]=====
	
	else:
		user.current_workout = Workout()
		user.status_state = FREE_WORKOUT
		ut.send_response(START_WORKOUT_MESSAGE, user_id)

	ut.update(user_id, user)
def construct_DNN(n_input, n_output, n_hid_layers=2, archi=128,
                  lr=1e-3, batchsize=40, dropout_rate=0.2, moment=0.95):
    """
    Initialize and construct the deep neural netweok with dropout
    update the DNN using momentum and minibatch
    archi: number of neurons of each hidden layer
    """
    # decide dropout or not, no dropout: stop_dropout > 1.05
    x = T.fmatrix()
    y_hat = T.fmatrix()
    stop_dropout = T.scalar()

    # initialize parameters
    Ws, bs, cache_Ws, cache_bs = initialize_NNet(n_input, n_output,
                                                 archi, n_hid_layers)

    # ############ construct the neural network ###############
    Zs = []
    As = []

    # input layer
    Zs.append(T.dot(x, Ws[0]) + bs[0].dimshuffle('x', 0))
    As.append(maxout(Zs[0], stop_dropout, archi, dropout_rate) / stop_dropout)

    # hidden layers
    for i in range(n_hid_layers):
        Zs.append(T.dot(As[i], Ws[i + 1]) + bs[i + 1].dimshuffle('x', 0))
        act_out = maxout(Zs[i + 1], stop_dropout, archi, dropout_rate)
        As.append(act_out / stop_dropout)

    # output layer
    z_out = T.dot(As[n_hid_layers], Ws[n_hid_layers + 1])
    Zs.append(z_out + bs[n_hid_layers + 1].dimshuffle('x', 0))
    y = softmax(Zs[-1] / stop_dropout)

    # ############ construct the neural network ###############

    forward = th.function([x, stop_dropout], y)
    parameters = Ws + bs
    moment_cache = cache_Ws + cache_bs

    # objective is the binary crossentropy
    Cost = ((-T.log((y * y_hat).sum(axis=1))).sum()) / batchsize

    # calculate gradients
    grads = T.grad(Cost, parameters, disconnected_inputs='ignore')

    # update parameters using momentum
    update_func = update(parameters, grads, moment_cache, lr, moment)
    gradient_update = th.function(inputs=[x, y_hat, stop_dropout],
                                  updates=update_func, outputs=Cost)

    return gradient_update, forward
示例#44
0
def set_timers(user_id, user):
	""" Starts a process for each timer set by a user. """

	if hasattr(user, 'timer'):
		user.timer_processes = []

		print 'setting timer'

		print user.timer
		#=====[ Start new process for each timer ]=====
		for idx, time in enumerate(user.timer):

			if idx == len(user.timer) - 1:
				p = Process(target=send_warning, args=(user_id, FINAL_TIMING_WARNING, time,))
			else:
				p = Process(target=send_warning, args=(user_id, TIMING_WARNING, time,))
			#=====[ Keep reference to process and start it ]=====
			p.start()
			user.timer_processes.append(p.pid)


		ut.update(user_id, user)
示例#45
0
def log_set(curr_set, workout, user, user_id):
	curr_subroutine = workout.curr_subroutine
					
	if curr_subroutine and (not curr_set.exercise or curr_subroutine.has_exercise(curr_set.exercise)):
	#=====[ If we're in the middle of an existing subroutine ]=====

		workout.add_set(curr_set)

	#=====[ Beginning a new subroutine ]=====s
	else:

		if curr_subroutine:
			workout.add_subroutine(curr_subroutine)

		workout.new_subroutine('exercise', [curr_set.exercise], curr_set)

	user.current_workout = workout
	
	
	set_timers(user_id, user)

	user.time = datetime.datetime.now()
	ut.update(user_id, user)
示例#46
0
 def __init__(self, **kw):
     update(self, world=build('morse'))
     home_pos = self.world.robot1_instance.pos
示例#47
0
def process(user, message):

	user_id, text = ut.get_info(user, message)
	workout = user.get_last_workout()

	rating = extract_int(text)
	print rating

	#On feedback question
	if user.status_state == 0:

		if "yes" in text or "ok" in text:
			ut.send_response(RATING_QUESTION, user_id)
			user.status_state = 1

		elif "no" in text:
			ut.send_response(NO_FEEDBACK, user_id)
			user.status = "idle"
			user.status_state = 0

		else:
			ut.send_response(FEEDBACK_CLARIFY, user_id)
			ut.send_response(FEEDBACK_QUESTION, user_id)

		ut.update(user_id, user)


	# On rating question
	elif user.status_state == 1:

		if rating:

			if rating >= 1 and rating <= 10:
				workout.rating = rating
				ut.send_response(QUESTION_END, user_id)
				user.status_state = 2
				ut.update(user_id, user)
				ut.send_response(DIFFICULTY_QUESTION, user_id)
				return

		# If anything goes wrong, send a clarifying message
		ut.send_response(RATING_CLARIFY, user_id)
		ut.send_response(RATING_QUESTION, user_id)

		


	# On difficulty question
	elif user.status_state == 2:
		
		if rating:
			if rating >= 1 and rating <= 5:
				workout.rating = rating
				ut.send_response(QUESTION_END, user_id)
				user.status_state = 3
				ut.update(user_id, user)
				ut.send_response(TIREDNESS_QUESTION, user_id)
				return

		# If anything goes wrong, send a clarifying message
		ut.send_response(DIFF_TIRED_CLARIFY, user_id)
		ut.send_response(DIFFICULTY_QUESTION, user_id)


	# On tiredness question
	elif user.status_state == 3:
		
		if rating:

			if rating >= 1 and rating <= 5:
				workout.rating = rating
				ut.send_response(FEEDBACK_END, user_id)
				user.status = "idle"
				user.status_state = 0
				ut.update(user_id, user)
				return

		# If anything goes wrong, send a clarifying message
		ut.send_response(DIFF_TIRED_CLARIFY, user_id)
		ut.send_response(TIREDNESS_QUESTION, user_id)
示例#48
0
# script for updating the update.db by crontab task

import utils

utils.update()
示例#49
0
文件: agent.py 项目: bok/AI-with-Pyke
 def update_knowledge(self, new_fact):
     """Update this agent's knowledge with a new fact."""
     utils.update(self.knowledge, ('know', self.name, new_fact))
示例#50
0
 def __init__(self, name):
     update(self, name=name, pos=Struct(x=0.0, y=0.0, z=0.0), simulator=Morse())
     inst = getattr(self.simulator, self.name)
     inst.robot_pose.subscribe(self.setpos)
def updated(d, *maps, **entries):
    """A "functional" version of update...
    """
    dd = dict(**d) if isinstance(d, dict) else Struct(d)
    return update(dd, *maps, **entries)
 def __init__(self, **kw):
     update(self, world=build('mock'))
示例#53
0
文件: search.py 项目: 153672/8600_hw1
 def __init__(self, initial_state=None):
     update(self, state=initial_state, seq=[])
示例#54
0
 def __init__(self, name, type, pos, color, size):
     update(self, name=name, type = type, pos=pos, color=color, size = size,simulator=Morse())
示例#55
0
 def __init__(self, h=3, v=3, k=3):
     update(self, h=h, v=v, k=k)
     moves = [(x, y) for x in range(1, h+1)
              for y in range(1, v+1)]
     self.initial = Struct(to_move='X', utility=0, board={}, moves=moves)
示例#56
0
def process(user, message):

	user_id, text = ut.get_info(user, message)

	#==========[ Command used to list all super commands for the workout logger ]==========#
	#																				       #
	#	usage: " list commands "									   					   #
	#																					   #
	########################################################################################

	if ('list' in text and 'commands' in text) or text == 'ls':

		ut.send_response('Here are a list of commands:\n\n' + '\n'.join(command_list.keys()), user_id)


	#=====[ Command used to log thoughts/improvements while using the workout logger ]=====#
	#																				       #
	#	usage: " sudo log: [suggestion to improve] "									   #
	#																					   #
	########################################################################################

	elif 'sudo' in text and 'log' in text and ':' in text:

		with open('to_improve_log','a') as f:
			f.write(text.split(':')[1].strip() + '\n\n')

		ut.send_response(MESSAGE_LOGGED, user_id)

	############################################################################
	############################################################################
	#################TODO TODO TODO TODO TODO TODO TODO#########################
	####################IMPLEMENT LISTING WORKOUTS##############################
	############################################################################

	elif 'list' in text and 'template' in text and 'workouts' in text:

		saved_workouts = '1. Chest Gains | Sets: 24\nTime: 1 hour\nMuscles: Chest, Triceps\n\n2. Ab Attack | Sets: 15\nTime: 20 minutes\nMuscles: Abs, Obliques\n\n3. Leg Day | Sets: 28\nTime: 1 hour 20 minutes\nMuscles: Quads, Hamstrings, Calves'
		ut.send_response(saved_workouts, user_id)


	#=========================[ Command used list recent workouts ]========================#
	#																				       #
	#	usage: " list workouts "									   					   #
	#																					   #
	########################################################################################

	elif 'list' in text and 'workouts' in text:

		ut.send_response('\n'.join([str(idx + 1) + '. ' + str(workout) for idx, workout in enumerate(reversed(user.workouts))]), user_id)


	#=====================[ Command used to review most recent workout ]===================#
	#																				       #
	#	usage: " review last workout "									   				   #
	#																					   #
	########################################################################################

	elif 'review' in text and 'last' in text and 'workout' in text:

		workout = user.workouts[-1]

		ut.send_response(workout.get_summary(), user_id)
		ut.send_response(workout.get_stats(),user_id)

		ut.send_response(workout.summarize_muscle_groups(4), user_id)
		# index = index if len(workout.muscle_groups) >= index else len(workout.muscle_groups)

		# if generate_spider(user_id, dict(workout.muscle_groups.most_common(index))):
		# 	ut.send_response('Check out the muscles you targeted:\nfile:///Users/Brandon/Desktop/Projects/workout_logger/spider.png', user_id)

	
	#==================[ Command used to review a particular workout ]=====================#
	#																				       #
	#	usage: " review workout: [index] "									   			   #
	#																					   #
	########################################################################################

	elif 'review' in text and 'workout' in text:

		try: 
			
			idx = int(ut.extract_int(text))
			workout = user.workouts[-idx]

			ut.send_response(user.workouts[-idx].get_summary(), user_id)
			ut.send_response(user.workouts[-idx].get_stats(), user_id)

			ut.send_response(workout.summarize_muscle_groups(4), user_id)

			# index = 4 if len(workout.muscle_groups) > 3 else len(workout.muscle_groups)

			# if generate_spider(user_id, dict(workout.muscle_groups.most_common(index))):
			# 	ut.send_response('Check out the muscles you targeted:\nfile:///Users/Brandon/Desktop/Projects/workout_logger/spider.png', user_id)

		except Exception as e:
			
			print e


	#==================[ Command used to remove a particular workout ]=====================#
	#																				       #
	#	usage: " remove workout: [index] "									   			   #
	#																					   #
	########################################################################################

	elif 'remove' in text and 'workout' in text:

		try: 
			
			idx = int(ut.extract_int(text))
			workout = user.workouts[-idx]

			ut.send_response('Deleted workout: ' + str(workout), user_id)

			del user.workouts[-idx]

			ut.update(user_id, user)

		except Exception as e:
			
			print e


	#=============[ Command used to review a weeks worth of workout stats ]================#
	#																				       #
	#	usage: " review week "									   			   			   #
	#																					   #
	########################################################################################

	elif 'review' in text and 'week' in text:

		info = 'Here\'s your week in review: \n\n'

		info += 'Total Volume: ' + str(user.get_volume(7)) + '\n'
		info += 'Total Sets: ' + str(user.get_num_sets(7)) + '\n' 
		info += 'Total Time: ' + "{0:.2f}".format(float(user.get_total_set_time(7)/3600.0)) + ' hours' + '\n'
		info += 'Avg. Set Time: ' + "{0:.2f}".format(user.get_avg_set_time(7)) + '\n'

		ut.send_response(info, user_id)

		ut.send_response(user.get_muscle_groups(7, 7), user_id)
		
		if hasattr(user, 'goals'):
			goal.review(user, user_id, 7, 7)

		# index = 6 if len(workout.muscle_groups) > 5 else len(workout.muscle_groups)

		# if generate_spider(user_id, dict(user.get_muscle_groups(7).most_common(index))):
		# 	ut.send_response('Check out the muscles you targeted most:\nfile:///Users/Brandon/Desktop/Projects/workout_logger/spider.png', user_id)
		
	elif 'q:' in text or 'query:' in text:
		exercise = text.split(':')[1].strip()
		info = 'You queried for: %s\n\n' % exercise
		print 'before query'
		sets = user.query_exercise(exercise)
		print 'after query'
		if sets:
			for date in sets:
				workout_sets = sets[date]

				info += "Workout on %s:\n" % date

				for xset in workout_sets:
					info += "%s reps of %s @ %s\n" % (xset.reps, xset.exercise, xset.weight)

			ut.send_response(info, user_id)
		else:
			ut.send_response("Sorry, I couldn't find any sets of " + exercise, user_id)


	#==================[ Command used to drop a user from the database ]===================#
	#																				       #
	#	usage: " reset db "									   			   			   	   #
	#																					   #
	########################################################################################

	elif text == 'reset db':
		
		ut.send_response('BYE FOREVER! :( ', user_id)
		ut.remove_user(user_id)


	#==================[ Command used set goals for targeted muscles ]=====================#
	#																				       #
	#	usage: " set goals: muslce1, muscle2, muscle3"			   			   			   #
	#																					   #
	########################################################################################

	elif 'set' in text and 'goal' in text:

		muscle_groups = text.split(':')

		#=====[ Check to make sure there are muscle groups specified after a colon ]=====
		if len(muscle_groups) == 1:
			ut.send_response(SET_GOALS, user_id)

		#=====[ set goals for user ]=====
		goal.set(user, user_id, muscle_groups[1])

	#================[ Command used set timers at specified intervals ]====================#
	#																				       #
	#	usage: " set timer for 45 and 60 seconds"			   			   			       #
	#																					   #
	########################################################################################

	elif 'set' in text and 'timer' in text:

		times = re.split(',|and',text)
		found_time = False

		#=====[ Checks each comma separated value for a time ]=====
		for time_candidate in times:

			time = extract_int(time_candidate)

			#=====[ If time for timer extracted, save info ]=====
			if time:
				
				found_time = True

				if hasattr(user,'timer'):
					user.timer.append(time)
				else:
					user.timer = [time]

		#=====[ Tell user how to set timer ]=====
		if not found_time:
			ut.send_response(HOW_TO_SET_TIMER, user_id)
		else:
			ut.send_response(SET_TIMER + ', '.join([str(x) for x in user.timer]) + ' seconds', user_id	)
			ut.update(user_id, user)

	#========================[ Command used to clear all timers ]==========================#
	#																				       #
	#	usage: " clear timer "			   			   			       					   #
	#																					   #
	########################################################################################

	elif 'clear' in text and 'timer' in text:

		user.timer = []
		ut.send_response(CLEARED_TIMER, user_id)
		ut.update(user_id, user)

	#========================[ Command used to exit to idle mode ]=========================#
	#																				       #
	#	usage: " exit "			   			   			       					  	 	   #
	#																					   #
	########################################################################################

	elif text == 'exit':
		
		user.status = 'idle'
		ut.send_response(IDLE_MODE, user_id)
		ut.update(user_id, user)

	#=====================[ Command used to get help for any command ]=====================#
	#																				       #
	#	usage: " help [command] "			   			   			       				   #
	#																					   #
	########################################################################################

	elif 'help' in text:

		user_command = text.replace('help','').strip()

		#=====[ Check if user command is in our command shortcut list. If so, send appropriate help response ]=====
		for command in command_shortcuts:
			
			if user_command in command_shortcuts[command]:
				
				ut.send_response(command_list[command], user_id)
				return True

		#=====[ Tell user that we couldn't find specified command and send list of commands ]=====
		ut.send_response(HELP_COMMAND, user_id)
		ut.send_response('Here are a list of commands:\n\n' + '\n'.join(command_list.keys()), user_id)

	#===================[ Command used to learn how to log a workout ]=====================#
	#																				       #
	#	usage: " how to log?" | "how do I log a workout? "  			       				   #
	#																					   #
	########################################################################################

	elif 'how' in text and 'log' in text:

		user.status = "intro"
		user.status_state = 1
		intro.process(user, message, instructions=True)

	#==========================[ Command used to greet user ]==============================#
	#																				       #
	#	usage: Greet Tony: 'Hi'  			       			   							   #
	#																					   #
	########################################################################################
	
	elif text in greetings:

		ut.send_response(GREETING, user_id)

	elif 'thank' in text:

		ut.send_response(NO_PROBLEM, user_id)
		ut.send_response(np.random.choice(INSPIRATIONAL),user_id)

	else:

		return False

	return True
示例#57
0
def process(user, message, instructions=False):
	""" Introduces a user to the workout chatbot and to logging workouts """

	user_id, text, status_state = ut.get_info(user, message, True)

	if status_state == 0:

		#=====[ Send introduction messages to user ]=====
		ut.send_response(WELCOME_MESSAGE, user_id)
		ut.send_response(COMMAND_INTRO, user_id)
		ut.send_response(WORKOUT_INTRO, user_id)

		user.status_state = 1

	#=====[ Begins teaching a user how to log a workout ]=====	
	elif status_state == 1:

		#=====[ Check if user said yes to learning about working out ]=====
		for word in yes_words:			
			if word in text:
				instructions = True
				break

		if instructions:
			#=====[ Send instructions for starting workout, logging sets, and ask if they want to learn about logging circuits ]=====
			ut.send_response(WORKOUT_START_INSTRUCTIONS, user_id)
			ut.send_response(WORKOUT_SET_INITIALIZATION, user_id)
			ut.send_response(WORKOUT_SET_CONTINUATION, user_id)
			ut.send_response(LEARN_ABOUT_CIRCUITS, user_id)

			user.status_state = 2

		else:
			
			user.status = "idle"
			user.status_state = 0
			ut.send_response(DONE_INSTRUCTIONS, user_id)


	#=====[ Processes message when user is learning about logging workouts. Currently, just checks to see if user wants to learn 
	#=====[ about logging circuits ]=====
	elif status_state == 2:

		user_id, text = ut.get_info(user, message)

		#=====[ Check if user gave a 'yes' word. If so gives information about logging circuits ]=====
		for word in yes_words:
			
			if word in text:
			
				#=====[ Teach user how to log circuits ]=====
				ut.send_response(WORKOUT_CIRCUIT_INITIALIZATION, user_id)
				ut.send_response(WORKOUT_CIRCUIT_CONTINUATION, user_id)

		ut.send_response(ASK_SEE_EXAMPLE, user_id)
		user.status_state = 3

	elif status_state == 3:

		#=====[ Update user into idle mode regardless of whether they wish to learn about circuits or not ]=====
		user.status = "idle"
		user.status_state = 0
		ut.update(user_id, user)

		#=====[ Check if user gave a 'yes' word. If so gives information about logging circuits ]=====
		for word in yes_words:
			
			if word in text:
			
				#=====[ Teach user how to log circuits ]=====
				ut.send_response(WORKOUT_EXAMPLE, user_id)
				return

		#=====[ Checks if user gave a 'no' word ]=====
		for word in no_words:

			if word in text:

				ut.send_response(DONE_INSTRUCTIONS, user_id)
				return

		#=====[ If no 'yes' or 'no' word found, then just assume user doesn't want to learn about logging circuits ]=====
		ut.send_response(ASSUME_DONE_INSTRUCTIONS, user_id)

	#=====[ update user (primarily state) in db ]=====
	ut.update(user_id, user)
示例#58
0
 def update_facts(self, fact):
     """Updates the universe with the given fact. It tries to find a fact of same nature (property and user)
     and change its value. If there is not any fact of this kind, then it adds it."""
     utils.update(self.facts, fact)
示例#59
0
 def __init__(self, **entries):
     """Constructor. It needs the __type__, __typesystem__ and __value__ 
     keys be present in **entries.
     """        
     # We want entries passed in to override those in self.
     update(self, **entries)
示例#60
0
文件: spdl.py 项目: skydark/spdlr
 def _update_atoms(self, formula):
     return update(self.atoms,
             [atom.name for atom in collect_atoms(formula)])