def add(env, target): env.Append(BUILDERS = {'ScriptFile': Builder(action=Action(builder_script_file, print_builder_script_file))}) prec="" if env.get('precommand', None): prec= env['precommand'] if env.get('MODELLER_MODPY', None): prec=prec+" "+env['MODELLER_MODPY'] if env.get('datapath', None): externmodules=[x for x in data.get(env).modules.keys()\ if data.get(env).modules[x].external] externdata= env.get('datapath', "") else: externmodules=[] externdata="" bin = env.ScriptFile(target, [env.Value(template), env.Value(env.Dir('#').abspath), env.Value(env.get('pythonpath', "")), env.Value(utility.get_ld_path(env)), env.Value(prec), env.Value(env['ENV']['PATH']), env.Value(":".join([x for x in data.get(env).modules.keys()\ if not data.get(env).modules[x].external])), env.Value(":".join(externmodules)), env.Value(externdata)]) return bin
def parse_glyph(map): ret = [] tzk = data.get(data.load_tree_xmzk) rzk = data.get(data.load_reverse_pyzk) xmcode = map["itmmap"][0][0] intermed = map["itmmap"][0][1] wordptr = map[0] mzk = tzk for k in xmcode: if mzk.has_key(k): lzk, mzk = mzk, mzk[k] if type(mzk).__name__ == "list": for item in mzk: if rzk.has_key(item): ret.append((item+intermed, rzk[item], wordptr)) else: ret.append((item+intermed, "", wordptr)) break else: ret.append((intermed, "", wordptr)) break else: # mzk is a dict and we have exhausted the loop, do traverse the tree xmzk = data.get(data.load_reverse_xmzk) retlist = traverse_tree(mzk) if len(retlist) >= data.g_maxoutput: retlist = retlist[0:data.g_maxoutput] retlist.sort() for item in retlist: start = len(xmcode) if rzk.has_key(item): ret.append((item+intermed, xmzk[item][start:]+rzk[item], wordptr)) else: ret.append((item+intermed, xmzk[item][start:], wordptr)) return ret
def local_parse_quanpin(kbmap, debug): ret = [] pys = kbmap["pinyinstr"] pyl = kbmap["pinyinlist"] if pys == "": ret.append(("", pyl[0][1])) return ret wc = kbmap["word_count"] zk = data.get(data.load_alpha_pyzk) if wc >= 3: zk3 = data.get(data.load_alpha_pyzk3) if wc >= 4: zk4 = data.get(data.load_alpha_pyzk4) try: userzk = data.get(data.load_alpha_userzk) ori = kbmap["originput"] # 按全部解析出的输入判定 index = pyl[wc][1] key = ori if userzk.has_key(key): for item in userzk[key].split(" "): if item[0] == "#": break ret.append((item, index)) # 按带断字符的方式判定 key = pys if userzk.has_key(key): for item in userzk[key].split(" "): if item[0] == "#": break ret.append((item, index)) except Exception: pass # 分别解析多字词、双字词和单字。 if wc >= 4: key, index = getquanpin(pyl, 4) if zk4.has_key(key): for item in zk4[key].split(" "): ret.append((item, index)) elif wc == 3: key, index = getquanpin(pyl, 3) if zk3.has_key(key): for item in zk3[key].split(" "): ret.append((item, index)) if wc > 1: key, index = getquanpin(pyl, 2) if zk.has_key(key): for item in zk[key].split(" "): ret.append((item, index)) if wc > 0: key, index = getquanpin(pyl, 1) if zk.has_key(key): for item in zk[key].split(" "): ret.append((item, index)) if len(ret) == 0: ret.append(("", pyl[0][1])) return ret
def matrix(request, number, template='about/matrix.html'): """Welcome in the matrix!""" try: if int(number) == 0: path = get("Paths of Truth") except: path = get(title__startswith="Path of Truth %s:" % number) return render(request, template, {'path': path, 'number': number})
def index(request, template="alliance/homepage.html"): about, manifesto, take_action = get('About the Alliance'), get('ILA Manifesto'), get('Take Action') news = Entry.objects.filter(tags__name='alliance').order_by('-created')[:5] ctx = {'about': about, 'manifesto': manifesto, 'take_action': take_action, 'news': news} return render(request, template, ctx)
def matrix(request, number): """Welcome in the matrix!""" try: if int(number) == 0: path = get("Paths of Truth") except: path = get(title__startswith="Path of Truth %s:" % number) return render_to_response('about/matrix.html', {'path': path, 'number': number}, context_instance=RequestContext(request))
def add_doc_files(env, files): #pass # currently they are all globbed, should fix for f in files: #print f if str(f).endswith(".dox") or str(f).endswith(".dot"): pass else: b=env.Install("#/build/doc/html/", f) data.get(env).add_to_alias('doc-files', [b])
def _find_python_module(env, modname, dirs): """Given a Python module name of the form a.b, return a list of Nodes for the actual Python files at each level of the hierarchy (e.g. a/__init__.py, a/b/__init.py).""" if env['wine'] or env['PLATFORM'] == 'win32': suffix='.pyd' elif env['PLATFORM'] == 'darwin': suffix=".so" else: suffix=env.subst(env['LDMODULESUFFIX']) ret=[] #print modname if modname == 'IMP': if not data.get(env).modules["kernel"].external: return [File("#/build/lib/_IMP"+env["IMP_PYTHON_SO"])]\ +stp.get_matching_build(env, ["lib/IMP/*.py"])\ +stp.get_matching_build(env, ["data/kernel/*"]) else: return [] elif modname == "RMF": if not data.get(env).modules["RMF"].external: return [File("#/build/lib/_RMF"+env["IMP_PYTHON_SO"]), File("#/build/lib/RMF/_version_check.py"), File("#/build/lib/RMF/__init__.py")] else: return [] elif modname.startswith("IMP."): nm=modname[4:] if nm.find(".") != -1: nm= nm[:nm.find(".")] if nm not in data.get(env).modules.keys(): raise RuntimeError("Please import imp like \"import IMP.container\" or \"from IMP import Model\" in import of "+nm) if not data.get(env).modules[nm].external: # pull in kernel too libf=[File("#/build/lib/_IMP_"+nm+env["IMP_PYTHON_SO"])] pyf= stp.get_matching_build(env, ["lib/IMP/"+nm+"/*.py", "lib/IMP/"+nm+"/*/*.py", "lib/IMP/"+nm+"/*/*/*.py"]) df=stp.get_matching_build_files(env, ["data/"+nm+"/*", "data/"+nm+"/*/*"]) ret=pyf+df+libf if not data.get(env).modules["kernel"].external: klibf=[File("#/build/lib/_IMP"+env["IMP_PYTHON_SO"])] kpyf=stp.get_matching_build(env, ["lib/IMP/*.py"]) kdf=stp.get_matching_build(env, ["data/kernel/*"]) ret+=kpyf ret+=kdf ret+=klibf return ret else: return [] else: return []
def local_parse_shuangpin(kbmap, debug): ret = [] pys = kbmap["pinyinstr"] pyl = kbmap["pinyinlist"] if pys == "": ret.append(("", pyl[0][1])) return ret wc = kbmap["word_count"] zk = data.get(data.load_alpha_pyzk) if wc == 3 or wc > 4: zk3 = data.get(data.load_alpha_pyzk3) if wc == 4 or wc > 5: zk4 = data.get(data.load_alpha_pyzk4) try: userzk = data.get(data.load_alpha_userzk) ori = kbmap["originput"] # 按原始输入来检查用户词库,支持不带断字符的双拼原始码用户词库 index = pyl[wc][1] key = ori if userzk.has_key(key): for item in userzk[key].split(" "): if item[0] == "#": break ret.append((item, index)) except Exception: pass # 分别解析多字词、双字词和单字。 if wc == 4 or wc > 5: key, index = getshuangpin(pyl, 4) if zk4.has_key(key): for item in zk4[key].split(" "): ret.append((item, index)) if wc == 3 or wc > 4: key, index = getshuangpin(pyl, 3) if zk3.has_key(key): for item in zk3[key].split(" "): ret.append((item, index)) if wc >= 2: key, index = getshuangpin(pyl, 2) if zk.has_key(key): for item in zk[key].split(" "): ret.append((item, index)) if wc == 1 or wc == 2: key, index = getshuangpin(pyl, 1) if zk.has_key(key): for item in zk[key].split(" "): ret.append((item, index)) if len(ret) == 0: ret.append(("", pyl[0][1])) return ret
def configure( env, name, type, version, required_modules=[], optional_dependencies=[], optional_modules=[], required_dependencies=[], ): """Returns ok, version, found_optional_modules, found_optional_dependencies""" if not version: version = env["IMP_VERSION"] disabled = [x for x in env.get("disabledmodules", "").split(":")] if name in disabled: print type.capitalize(), name, "explicitly disabled " return (None, None, None, None) found_required_modules = data.get(env).get_found_modules(required_modules) for m in required_modules: if m not in found_required_modules: msg = "%s" + type.capitalize() + " " + name + " disabled due to disabled module IMP." + m + "%s" print msg % (env["IMP_COLORS"]["red"], env["IMP_COLORS"]["end"]) return (None, None, None, None) for m in required_dependencies: if not data.get(env).dependencies[m].ok: msg = "%s" + type.capitalize() + " " + name + " disabled due to missing dependency " + m + "%s" print msg % (env["IMP_COLORS"]["red"], env["IMP_COLORS"]["end"]) return (None, None, None, None) found_optional_modules = data.get(env).get_found_modules(optional_modules) found_optional_dependencies = data.get(env).get_found_dependencies(optional_dependencies) outversion = version if len(found_optional_dependencies + found_optional_modules) > 0: outversion = outversion + " with " + ", ".join(found_optional_dependencies + found_optional_modules) version = outversion msg = "%sConfiguring " + type + " " + name + "%s version " + version print msg % (env["IMP_COLORS"]["green"], env["IMP_COLORS"]["end"]) # if len(required_modules+required_dependencies)>0: # print " (requires " +", ".join(required_modules+required_dependencies) +")" found_optional_modules.sort() found_optional_dependencies.sort() required_modules.sort() required_dependencies.sort() return ( environment.get_named_environment( env, name, required_modules + found_optional_modules, required_dependencies + found_optional_dependencies ), version, found_optional_modules, found_optional_dependencies, )
def _edit_attributedata(request, data): stylename = data["stylename"] entityname = data["entityname"] entityurl = data["entityurl"] klass = data["klass"] aliasklass = data["aliasklass"] template = data["template"] common_name = data.get("common_name", False) items = klass.objects.all() ret = {"items": items, "entityn": entityname, "entitynpl": "%ss" % entityname, "style": stylename, "entityurl": entityurl, "title": "%s editor" % entityname, "common_name": common_name, "alias": aliasklass } if request.method == 'POST': # Add aliases if aliasklass: for i in items: isadd = request.POST.get("item-%s-alias" % i.id) if isadd is not None: i.aliases.create(name=isadd) # Delete alias for a in aliasklass.objects.all(): isdel = request.POST.get("alias-rm-%s" % a.id) if isdel is not None: a.delete() # Add new item refresh = False newname = request.POST.get("newname") newcommon = request.POST.get("newcommon") if newname is not None and newname != "": refresh = True args = {"name": newname} if common_name and newcommon is not None and newcommon != "": args["common_name"] = newcommon klass.objects.create(**args) # Delete item for i in items: isdel = request.POST.get("delete-item-%s" % i.id) if isdel is not None: refresh = True i.delete() if refresh: items = klass.objects.all() ret["items"] = items else: newname = request.GET.get("newname") if newname: ret["newname"] = newname return render(request, template, ret)
def choice(request, number, color, template='about/choice.html'): """The choice of a path.""" if color == "red": path = "Truth" elif color == "blue": path = "Lie" print "Path of Truth %s %s" % (number, color) result = get("Path of Truth %s %s" % (number, color)) ASPECTS = {'I':'rank', 'II':'grade', 'III':'title', 'IV':'role'} aspect = ASPECTS[number] if request.user.is_authenticated: promoted = request.user.profile_set.all()[0].promote(aspect=aspect, level=1) if promoted: messages.add_message(request, messages.SUCCESS, ugettext("You got promoted!")) else: messages.add_message(request, messages.WARNING, ugettext("You were not further promoted.")) ctx = {'number': number, 'color': color, 'result': result, 'promoted': promoted} return render(request, template, ctx)
def _add_flags(env, extra_modules=[], extra_dependencies=[]): if env['IMP_USE_RPATH']: dylinkflags=[] for p in env['LIBPATH']: if p[0] != '#': env.Prepend(RPATH=[p]) modules=extra_modules+env['IMP_CURRENT_MODULES'] dependencies=env['IMP_CURRENT_DEPENDENCIES']+extra_dependencies all_dependencies=dependencies d= data.get(env) all_modules=[] for m in modules: if m not in all_modules: all_modules= all_modules+[m]+d.modules[m].modules final_modules=[] for i,m in enumerate(all_modules): if not m in all_modules[i+1:]: final_modules.append(m) for m in final_modules: all_dependencies= all_dependencies+d.modules[m].dependencies final_dependencies=[] for i,dc in enumerate(all_dependencies): if not dc in all_dependencies[i+1:]: final_dependencies.append(dc) module_libs=[] for m in final_modules: module_libs.append(d.modules[m].libname) _add_dependency_flags(env, final_dependencies) dependency_libs=[] for dc in final_dependencies: dependency_libs+= d.dependencies[dc].libs env.Append(LIBS=module_libs) env.Append(LIBS=dependency_libs)
def achievements(request): entry = get('Achievements') #achievements = Entry.objects.filter(tags_name='achievement') achievements = HierarchyType.objects.all()[:3] ctx = {'entry': entry, 'achievements': achievements} return render_to_response('aspects/achievements.html', ctx, #achievements context_instance=RequestContext(request))
def epistasis(request): entry = get(title="Epistasis of Longevity") data = entry.text.split("\n") description = data[0] pmids = [i for i in data[2:] if i] ctx = {"entry": entry, "description": description, "pmids": pmids} return render_to_response("lifespan/epistasis.html", ctx, context_instance=RequestContext(request))
def _make_example_overview(target, source, env): out= open(target[0].abspath, "w") print >> out, "/** \\page examples_index Example index" dta= data.get(env) for k in dta.examples.keys(): print >> out, " -", dta.examples[k].link print >> out, "*/"
def _make_applications_overview(target, source, env): out= open(target[0].abspath, "w") print >> out, "/** \\page applications_index Application index" dta= data.get(env) for k in dta.applications.keys(): if dta.applications[k].ok: print >> out, " -", dta.applications[k].link print >> out, "*/"
def balance(recs, total): avg = total / len(recs) for rec in recs: rec.balance -= avg ori_rec = data.get(rec.recno) assert(ori_rec) rec.balance += ori_rec.balance return
def epistasis(request): entry = get(title='Epistasis of Longevity') data = entry.text.split('\n') description = data[0] pmids = [i for i in data[2:] if i] ctx = {'entry': entry, 'description': description, 'pmids': pmids} return render_to_response('lifespan/epistasis.html', ctx, context_instance=RequestContext(request))
def shuangpin_parse(keyb, debug): pinyin_table = data.get(data.get_py_table) pytype = pinyin_table["__type__"] map = shuangpin_transform(keyb, pinyin_table) if debug: print map if map["word_count"] == 0: result = [("",0)] elif map["word_count"] < 3 and g_gae: result = local_parse_shuangpin(map, debug) elif map["word_count"] < 5 and not g_gae: result = local_parse_shuangpin(map, debug) else: # 当远程解析超时或者无结果时,启用本地解析 result = remote_parse(map, debug) if len(result) <= 1: result = local_parse_shuangpin(map, debug) xmcode = map["itmmap"][0][0] if len(xmcode) > 0 and map["word_count"] == 0: # 解析纯笔形模式,仅当无任何拼音输入时才进入此模式 ret = parse_glyph(map) else: ret = [] rzk = data.get(data.load_reverse_xmzk) # 解析有拼音输入时的形码过滤 for item,index in result: if index == -1: ret.append((item, "_", index)) continue displayitem, hint = process(item, map, rzk) if displayitem == "": continue if map.has_key(index): ret.append((displayitem, hint, map[index])) else: ret.append((displayitem, hint, index)) if len(ret) >= data.g_maxoutput: break if debug: ret.append((keyb, "_", -1)) if debug: print " %d 个结果:缺省为 %s => %s,提示信息为 %s" % (len(ret)-1, keyb, ret[0][0], ret[0][1]) return ret
def add_tests(env, source, type, expensive_source=[]): # Since all of the test scripts involve "import IMP.test", ensure this # is a source so that any Python dependencies of IMP.test (e.g. IMP.base) # are automatically picked up by pyscanner #testpy = "#/build/lib/IMP/test/__init__.py" dta= data.get(env) test=UnitTest(env, target="fast-test.results", source=["#/tools/imppy.sh"]+source+[env.Value(type)]) # bring in kernel and test to make sure kernel python support is there # and since examples don't tend to import test directly. test will pull # in kernel etest=UnitTest(env, target="test.results", source=["#/tools/imppy.sh"]+source \ +expensive_source+[env.Value(type)]) if "test" in dta.modules.keys(): env.Depends(test, [dta.modules["test"].alias]) env.Depends(etest, [dta.modules["test"].alias]) env.AlwaysBuild("test.results") #env.Requires(test, env.Alias(environment.get_current_name(env))) #env.Requires(test, "tools/imppy.sh") if type.endswith('unit test'): dta.add_to_alias(environment.get_current_name(env)+"-test-fast", test) data.get(env).add_to_alias(environment.get_current_name(env)+"-test", etest) elif type=='example': data.get(env).add_to_alias(environment.get_current_name(env)+"-test-examples", test) elif type=="system": data.get(env).add_to_alias(environment.get_current_name(env)+"-test", test) env.Alias(env.Alias('test'), etest) env.Alias(env.Alias('test-fast'), test) return test, etest
def titles(request): entry = get("Titles") table = TitleTable(Title.objects.all().order_by('level')) RequestConfig(request).configure(table) ctx = {'entry': entry, 'hierarchy_name': 'Titles', 'hierarchy': table} return render_to_response('aspects/hierarchy.html', ctx, context_instance=RequestContext(request))
def intersections(request, ratio=2., pvalue=0.05, fold_change=None, exp=None, set=None, benjamini=None ): entry = get("Intersections") id = 'seq_id' if request.GET: if 'ratio' in request.GET and request.GET['ratio']: ratio = float(request.GET['ratio']) if 'pvalue' in request.GET and request.GET['pvalue']: pvalue = float(request.GET['pvalue']) if 'fold_change' in request.GET and request.GET['fold_change']: fold_change = float(request.GET['fold_change']) if 'benjamini' in request.GET and request.GET['benjamini']: benjamini = float(request.GET['benjamini']) if 'expression__exp' in request.GET and request.GET['expression__exp']: exp = request.GET['expression__exp'] print "Expression exp" if 'set' in request.GET and request.GET['set']: set = request.GET['set'] if 'id' in request.GET and request.GET['id']: id = request.GET['id'] filter = TranscriptFilterSet(request.GET, transcripts) intersections = [] #signatures = Signature.objects.differential(ratio, pvalue) # if set: set = Set.objects.get(pk=set) signatures = set.signatures.all() else: set = Set.objects.get(pk=1) signatures = set.signatures.all() for signature in signatures: # signature.differential(ratio, pvalue, fold_change, exp, benjamini, id) # Might a good function for a custom manager. for a_signature in signatures: for another_signature in signatures[:len(signatures)]: # Prevents duplicated comparisions the other way around. if a_signature != another_signature: # Prevent comparision of the same signatures and intersection = Intersection(a_signature, another_signature) #print intersection.name, len(intersection.up), len(intersection.down) intersections.append(intersection) # Context: ctx = {'title': 'Intersections', 'entry': entry, 'signatures': signatures, 'intersections': intersections, 'ratio': ratio, 'pvalue': pvalue, 'benjamini': benjamini, 'fold_change': fold_change, 'exp': exp, 'filter': filter, 'sets': Set.objects.all(), 'ids': IDs, 'id': id, 'set': set, } return render_to_response('expressions/intersections.html', ctx, context_instance=RequestContext(request))
def _make_module_example_overview(target, source, env): module= source[0].get_contents() out= open(target[0].abspath, "w") print >> out, "/** \\page "+module+"_all_example_index IMP."+module+" example index" dta= data.get(env) for k in dta.examples.keys(): if dta.examples[k].classes.has_key(module) \ or dta.examples[k].methods.has_key(module): print >> out, " - ", dta.examples[k].link print >> out, "*/"
def index(request): aspects = Entry.objects.filter(tags__name="aspect").order_by('id') aspects_entry = get("Aspects") #print len(aspects) hierarchytypes = HierarchyType.objects.all() ctx = {'aspects_entry': aspects_entry, 'aspects': aspects, 'hierarchytypes': hierarchytypes} return render_to_response('aspects/index.html', ctx, context_instance=RequestContext(request))
def get_data(self): more=['name','length','nsamples'] d=dict.fromkeys(data.get_kwargs(ts[0]).keys())#,[]) <- python gotcha! for ak in d: d[ak]=[] #<-soln for am in more: d[am]=[] for s in ts: kw=data.get_kwargs(s) kw[more[0]]=s kw[more[1]]=data.get_series(s).shape[0] kw[more[2]]=len(data.get(s)) for ak in kw: d[ak].append(kw[ak]) return pd.DataFrame.from_dict(d)
def get_benchmark_environment(envi, extra_modules=[]): extra=[] d= data.get(envi) if 'benchmark' in d.modules.keys() and d.modules['benchmark'].ok: if d.dependencies['tcmalloc'].ok: libs=['tcmalloc'] else: libs=[] return get_bin_environment(envi, extra_modules+['benchmark'], extra_dependencies=libs) else: return None
def filter_glyph(input, pt): global g_double_quote_mode punctmap = data.get(data.get_punctmap) imodemap = data.get(data.get_imodemap) glyph = "" intmed = "" mode_u = pt["__uimode__"][0] mode_i = pt["__uimode__"][1] mode_o = "" uimode = mode_o if len(input) == 1 and input[0] == mode_i: return "", "一" for c in input: if c.isdigit() and uimode == mode_o: glyph += c else: if c == mode_i and uimode == mode_o: uimode = c elif c == mode_u and uimode == mode_o: uimode = c intmed += c elif punctmap.has_key(c): if c == '"': if g_double_quote_mode: intmed += punctmap[c][0:3] else: intmed += punctmap[c][3:6] g_double_quote_mode = not g_double_quote_mode else: intmed += punctmap[c] elif uimode == mode_i and imodemap.has_key(c): intmed += imodemap[c] elif uimode[:1] == mode_u: uimode += c else: intmed += c if uimode[:1] == mode_u: intmed = intmed.replace(mode_u, getunicode(uimode)) return glyph, intmed
def configure_application( env, name, link, version, required_modules=[], optional_dependencies=[], optional_modules=[], required_dependencies=[], ): dta = data.get(env) if name in dta.applications.keys(): if dta.applications[name].ok: return environment.get_named_environment( env, name, dta.applications[name].modules, dta.applications[name].dependencies ) else: return None (nenv, version, found_optional_modules, found_optional_dependencies) = configure( env, name, "application", version, required_modules, optional_dependencies, optional_modules, required_dependencies, ) if nenv: data.get(env).add_application( name, link=link, dependencies=required_dependencies + found_optional_dependencies, unfound_dependencies=[x for x in optional_dependencies if not x in found_optional_dependencies], modules=required_modules + found_optional_modules, version=version, ) return nenv else: return None
def home(request, template="homepage.html"): """The root source of all Denigmas URLs. Renders a dynamic home site with altered content.""" searchform = SearchForm() # Depricated? denigma_description = get("Denigma Description") denigma_rationality = get("Denigma Rationality") news = ( Entry.objects.filter(Q(tags__name="news") | Q(categories__name="News")) .order_by("-created", "-id") .distinct()[:8] ) # or Post.objects.filter(tags__name='news') research = get("Research") programming = get("Programming") design = get("Design") dashboard = get("Dashboard") ctx = { "searchform": searchform, "denigma_description": denigma_description, "denigma_rationality": denigma_rationality, "news": news, "dashboard": dashboard, "research": research, "programming": programming, "design": design, "site": Site.objects.get_current, "total": Donation.objects.get_total, "donation_name": settings.DONATION_NAME, "donation_number": settings.DONATION_NUMBER, "paypal_id": settings.PAYPAL_ID, "debug": settings.DEBUG, } return render(request, template, ctx)
#https://www.quantstart.com/articles/Backtesting-a-Moving-Average-Crossover-in-Python-with-pandas import pandas_datareader as pdr import datetime import pandas as pd import matplotlib.pyplot as plt import requests import json import urllib2 #import SciPy import numpy as np import data tickers = ["USDT-NEO","USDT-BTC", "USDT-ETH"] all_data = data.get(tickers) i = tickers[1] omg = all_data.loc[i] # Initialize the short and long windows short_window = 40 long_window = 100 # Initialize the `signals` DataFrame with the `signal` column signals = pd.DataFrame(index=omg.index) signals['signal'] = 0.0 # Create short simple moving average over the short window signals['short_mavg'] = omg['C'].rolling(window=short_window, min_periods=1, center=False).mean() # Create long simple moving average over the long window signals['long_mavg'] = omg['C'].rolling(window=long_window, min_periods=1, center=False).mean()
def get_context_data(self, *args, **kwargs): context = super(TodoList, self).get_context_data(*args, **kwargs) context['entry'] = get('Todos') return context
def test_simple_soundwaves(osc=1, duration=30): """ Play a sine wave for each of the parameters of Madrid in 2014. Depending on the osc parameter 1: Play four sine waves following each of 2t, p, w, c 2: Play two sine waves, modulated in frequency and amplitude, the first by 2t and w, the second by p and c 3: Play two sine waves, each consisting in two oscillators with a base frequency controlled py t or c, where the second oscillator of the instruments is p or w cycles off the main oscillator """ # Get all data loc = "Madrid" mad2t = get(td.T, location=loc) madp = get(td.P, location=loc) madw = get(td.W, location=loc) madc = get(td.C, location=loc) # write orchestra + score points = 16777216 if osc == 1: oscillator = orchestra.oscillator1(points, instrument_number=1) events = [ "i1 0 %s 10000 2 ; " % duration, "i1 0 %s 5000 3 ; " % duration, "i1 0 %s 5000 4 ; " % duration, "i1 0 %s 5000 5 ; " % duration ] elif osc == 2: oscillator = orchestra.oscillator2(points, instrument_number=2) events = [ "i2 0 %s 10000 2 4; " % duration, "i2 0 %s 10000 3 5; " % duration, ] elif osc == 3: oscillator = orchestra.oscillator_dual(points, instrument_number=3) events = [ "i3 0 %s 10000 2 3 ; " % duration, "i3 0 %s 10000 5 4 ; " % duration, ] score = [ "f1 0 8192 10 1 ; Table containing a sine wave.", gen08(2, mad2t, number_of_points=points, comment="Weather parameter table 2"), gen08( 3, madp, number_of_points=points, comment="Weather parameter table 3", ), gen08(4, madw, number_of_points=points, comment="Weather parameter table 4"), gen08(5, madc, number_of_points=points, comment="Weather parameter table 5") ] score += events output.write_and_play(output.get_csd([oscillator], score))
def get_context_data(self, *args, **kwargs): context = super(ReferenceList, self).get_context_data(*args, **kwargs) context['form'] = FilterForm(initial={'filter': ReferenceList.query}) context['entry'] = get(title='References') context['filterset'] = self.filterset return context
def changes(request): changes = Change.objects.all() changes_description = get(title='Biological Changes') ctx = {'changes': changes, 'changes_description': changes_description} return render(request, 'datasets/changes.html', ctx)
ax.grid() fig.show() fig.savefig("test.png") l = 0.35 D = np.array([5, 10, 15, 20]) for m in (1, 4): greedyData = [] geneticData = [] naiveData = [] for d in D: if l < 0.40: n = naive(data.get(l, m, delai=d)) naiveData += [n] g = greedy(data.get(l, m, delai=d)) greedyData += [g] ge = genetic(data.get(l, m, delai=d)) geneticData += [ge] naiveData = np.array(naiveData) greedyData = np.array(greedyData) geneticData = np.array(geneticData) fig, ax = plt.subplots() ax.plot(D[:len(naiveData)], naiveData[:, 0], label='Naive') ax.plot(D[:len(greedyData)], greedyData[:, 0], label='Glouton') ax.plot(D[:len(geneticData)], geneticData[:, 0], label="Génétique") ax.set(xlabel='Le delai maximum [time slot]',
def profiles(request): profiles = Profile.objects.all() ctx = {'entry': get("Profiles"), 'profiles': profiles} return render_to_response('expressions/profiles.html', ctx, context_instance=RequestContext(request))
def lme(): df_atual = get(Datafrom='lme') df_novo = pegaLMEAtual() df_tosave = unique(df_novo, df_atual) saveData(df_tosave, colection='lme') return True
def index(request): entry = get("Expressions") return render_to_response('expressions/index.html', {'entry': entry}, context_instance=RequestContext(request))
def save(fig, filename, format): fig.savefig(f'rapport/{filename}.{format}', format=format) l = 0.45 lam = np.arange(0.25, 3.001, 0.20) lam = np.insert(lam, 1, [0.30, 0.35]) for m in (1, 4): greedyData = [] geneticData = [] naiveData = [] for l in lam: if l < 0.40: n = naive(data.get(l)) naiveData += [n] g = greedy(data.get(l, m)) greedyData += [g] ge = genetic(data.get(l, m)) geneticData += [ge] # print(g) # print(ge) naiveData = np.array(naiveData) greedyData = np.array(greedyData) geneticData = np.array(geneticData) # Energie vs Lambda fig, ax = plt.subplots() ax.plot(lam[:len(naiveData)], naiveData[:, 0], label='Naive')
def profession(request, name): print name.title() profession = get(name.title()) ctx = {'profession': profession} return render_to_response('aspects/profession.html', ctx, context_instance=RequestContext(request))
def professions(request): professions_entry = get("Professions") professions = Entry.objects.filter(tags__name="profession") ctx = {'professions_entry': professions_entry, 'professions': professions} return render_to_response('aspects/professions.html', ctx, context_instance=RequestContext(request))
def programming(request): aspect = get('Programming') return render_to_response('aspects/aspect.html', {'aspect': aspect}, context_instance=RequestContext(request))
def index(request, template='annotations/index.html'): annotations = get("Annotations") return render(request, template, {'annotations': annotations})
def index(request, template='interactions/index.html'): entry = get("Interactions") return render(request, template, {'entry': entry})
print_face([ftl, btl, btr], top, ff) # bottom print_face([fbl, fbr, bbr], back, ff) print_face([fbl, bbr, bbl], back, ff) print("Welcome to ultrazoid_'s PDB renderer: Mac OS X Edition") cont = False while cont == False: fInput = string.upper(raw_input("Please input the *.pdb file name you would like to render(must be in same directory):")) if ".PDB" in fInput: try: print("*.pdb file recognised") print("searching for file...") dart = data.get(fInput) cont = True except IOError: print("File not found...") print("Did you misspell the name?") cont = False elif ".PDB" not in fInput: print("The filename you entered is not a PDB file...") print("Did you forget about the extension?") cont = False pInput = string.upper(raw_input("File Loaded! Would you like to prepare it for rendering?(y/n)")) if pInput == 'Y': cont = False while cont == False: numInput = str(raw_input("Please input point size as a float less than 1:"))
from convert import dict_from_node, dict_from_dicts, list_from_dicts from metadata import now from stib import ID, IGNORED, BBOX, MODE, DESTCODES, HALT, DESTINATIONS from geolocation import scanner, creeper lines = {} itineraries = {} stops = {} # retrieve all lines _lines = get('lines') # build line objects and itineraries for _line in _lines: line = {tag.tag: tag.text for tag in _line} id = line[ID] if id in IGNORED: continue lines[id] = line itineraries[id] = {} for x in DESTCODES:
def intersections(request, ratio=2., pvalue=0.05, fold_change=None, exp=None, set=None, benjamini=None): entry = get("Intersections") id = 'seq_id' if request.GET: if 'ratio' in request.GET and request.GET['ratio']: ratio = float(request.GET['ratio']) if 'pvalue' in request.GET and request.GET['pvalue']: pvalue = float(request.GET['pvalue']) if 'fold_change' in request.GET and request.GET['fold_change']: fold_change = float(request.GET['fold_change']) if 'benjamini' in request.GET and request.GET['benjamini']: benjamini = float(request.GET['benjamini']) if 'expression__exp' in request.GET and request.GET['expression__exp']: exp = request.GET['expression__exp'] print "Expression exp" if 'set' in request.GET and request.GET['set']: set = request.GET['set'] if 'id' in request.GET and request.GET['id']: id = request.GET['id'] filter = TranscriptFilterSet(request.GET, transcripts) intersections = [] #signatures = Signature.objects.differential(ratio, pvalue) # if set: set = Set.objects.get(pk=set) signatures = set.signatures.all() else: set = Set.objects.get(pk=1) signatures = set.signatures.all() for signature in signatures: # signature.differential( ratio, pvalue, fold_change, exp, benjamini, id) # Might a good function for a custom manager. for a_signature in signatures: for another_signature in signatures[:len( signatures )]: # Prevents duplicated comparisions the other way around. if a_signature != another_signature: # Prevent comparision of the same signatures and intersection = Intersection(a_signature, another_signature) #print intersection.name, len(intersection.up), len(intersection.down) intersections.append(intersection) # Context: ctx = { 'title': 'Intersections', 'entry': entry, 'signatures': signatures, 'intersections': intersections, 'ratio': ratio, 'pvalue': pvalue, 'benjamini': benjamini, 'fold_change': fold_change, 'exp': exp, 'filter': filter, 'sets': Set.objects.all(), 'ids': IDs, 'id': id, 'set': set, } return render_to_response('expressions/intersections.html', ctx, context_instance=RequestContext(request))
def signatures(request): signatures = Signature.objects.all() ctx = {'entry': get("Signatures"), 'signatures': signatures} return render_to_response('expressions/signatures.html', ctx, context_instance=RequestContext(request))
def references_archive(request): references = Reference.objects.all() references_entry = get(title='References') ctx = {'references': references, 'references_entry': references_entry} return render_to_response('datasets/reference_archive.html', ctx, context_instance=RequestContext(request))
def index(request): datasets = get(title='Datasets') return render_to_response('datasets/index.html', {'datasets': datasets}, context_instance=RequestContext(request))
def get_context_data(self, **kwargs): context = super(SetList, self).get_context_data(**kwargs) if hasattr(self, 'extra_context'): context.update(self.extra_context) context['entry'] = get('Sets') return context
def fetch(): messages = data.get() index = create_index.create_index(*messages) prior = priors.get_prior("prior_word_freq.txt") output = sort.sort(*index, prior_freq=prior) return output
def what_next(request, template='about/what_next.html'): """Presents what's next to do after registration.""" entry = get("What's Next") return render(request, template, {'entry': entry})
def get(name): return data.get(name)
def index(request, template='about/index.html'): entry = get("Denigma") return render(request, template, {'entry': entry})
def entry(value): return get(value)
from px_build_doc.util import WikipediaManager, fetch_query from px_build_doc.image_util import build_cover, get_font, read_image import data _, results, _ = data.get() # an example that can be used with build cover def test_draw(img, d, text=["title", "subtitle"], locations=[(100, 850), (100, 900)], sizes=[50, 20], colour=(255, 255, 255, 255)): # for txt,loc,size in zip(text,locations,sizes): # d.text(loc, txt, font=get_font(size), fill=colour) images = [ im for im in WikipediaManager().query( # fetch_query() "mastercard").images() if not im.endswith('svg') ] url = images[1] url = 'https://unaavictoria.org.au/wp-content/uploads/2016/08/DFAT-logo.jpg' #url = 'https://www.google.com/url?sa=i&url=https%3A%2F%2Fsharedvalue.org.au%2Fprofiles%2Fdfat%2F&psig=AOvVaw0aPEl_e3z6EE9N48yMTh7i&ust=1582768657746000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCMj8mu-O7ucCFQAAAAAdAAAAABAI' rim = read_image(url, (300, 300)) img.paste(rim, (500, 80)) # build_cover('base_cover.png',test_draw)
def aspect(request, aspect): aspect = get(aspect) return render_to_response('aspects/aspect.html', {'aspect': aspect}, context_instance=RequestContext(request))
def get_context_data(self, **kwargs): context = super(TissueList, self).get_context_data(**kwargs) context['entry'] = get('Tissues') return context