Best JavaScript code snippet using mountebank
test_generics.py
Source:test_generics.py
...658 tracker.append({2: decorated.args})659 def to_call_instead(decorated: Decorated):660 tracker.append({3: decorated.args})661 return decorated(*decorated.args, **decorated.kwargs)662 @decorate(663 before=to_call_before, after=to_call_after, instead=to_call_instead664 )665 def to_call(*args):666 tracker.append({4: args})667 to_call(1, 2)668 assert len(tracker) == 4669 assert tracker[0] == {1: (1, 2)} # before670 assert tracker[1] == {3: (1, 2)} # instead671 assert tracker[2] == {4: (1, 2)} # wrapped672 assert tracker[3] == {2: (1, 2)} # after673 def test_all_decorators_constructed(self):674 """A decorator can be "pre-made" if needed"""675 tracker: t.List[dict] = []676 def to_call_before(decorated: Decorated):677 tracker.append({1: decorated.args})678 def to_call_after(decorated: Decorated):679 tracker.append({2: decorated.args})680 def to_call_instead(decorated: Decorated):681 tracker.append({3: decorated.args})682 return decorated(*decorated.args, **decorated.kwargs)683 pre_made = construct_decorator(684 before=to_call_before, after=to_call_after, instead=to_call_instead685 )686 @pre_made()687 def to_call(*args):688 tracker.append({4: args})689 to_call(1, 2)690 assert len(tracker) == 4691 assert tracker[0] == {1: (1, 2)} # before692 assert tracker[1] == {3: (1, 2)} # instead693 assert tracker[2] == {4: (1, 2)} # wrapped694 assert tracker[3] == {2: (1, 2)} # after695 def test_all_callables_get_extras(self):696 """All of the callables get extra kwargs."""697 tracker: t.List[dict] = []698 def to_call_before(decorated: Decorated, kwarg=None):699 tracker.append({1: kwarg})700 def to_call_after(decorated: Decorated, kwarg=None):701 tracker.append({2: kwarg})702 def to_call_instead(decorated: Decorated, kwarg=None):703 tracker.append({3: kwarg})704 return decorated(*decorated.args, **decorated.kwargs)705 @decorate(706 before=to_call_before,707 after=to_call_after,708 instead=to_call_instead,709 kwarg=0,710 )711 def to_call(*args):712 tracker.append({4: args})713 to_call(1, 2)714 assert len(tracker) == 4715 assert tracker[0] == {1: 0} # before716 assert tracker[1] == {3: 0} # instead717 assert tracker[2] == {4: (1, 2)} # wrapped718 assert tracker[3] == {2: 0} # after719 def test_all_callables_get_specific_extras(self):720 """Specific extras are passed appropriately."""721 tracker: t.List[dict] = []722 def to_call_before(decorated: Decorated, kwarg=None):723 tracker.append({1: kwarg})724 def to_call_after(decorated: Decorated, kwarg=None):725 tracker.append({2: kwarg})726 def to_call_instead(decorated: Decorated, kwarg=None):727 tracker.append({3: kwarg})728 return decorated(*decorated.args, **decorated.kwargs)729 @decorate(730 before=to_call_before,731 before_kwargs={"kwarg": 0},732 after=to_call_after,733 after_kwargs={"kwarg": 1},734 instead=to_call_instead,735 instead_kwargs={"kwarg": 2},736 )737 def to_call(*args):738 tracker.append({4: args})739 to_call(1, 2)740 assert len(tracker) == 4741 assert tracker[0] == {1: 0} # before742 assert tracker[1] == {3: 2} # instead743 assert tracker[2] == {4: (1, 2)} # wrapped744 assert tracker[3] == {2: 1} # after745 def test_all_callables_specific_extras_overridden(self):746 """General kwargs override specific ones."""747 tracker: t.List[dict] = []748 def to_call_before(decorated: Decorated, kwarg=None):749 tracker.append({1: kwarg})750 def to_call_after(decorated: Decorated, kwarg=None):751 tracker.append({2: kwarg})752 def to_call_instead(decorated: Decorated, kwarg=None):753 tracker.append({3: kwarg})754 return decorated(*decorated.args, **decorated.kwargs)755 @decorate(756 before=to_call_before,757 before_kwargs={"kwarg": 0},758 after=to_call_after,759 after_kwargs={"kwarg": 1},760 instead=to_call_instead,761 instead_kwargs={"kwarg": 2},762 kwarg=3,763 )764 def to_call(*args):765 tracker.append({4: args})766 to_call(1, 2)767 assert len(tracker) == 4768 assert tracker[0] == {1: 3} # before769 assert tracker[1] == {3: 3} # instead770 assert tracker[2] == {4: (1, 2)} # wrapped771 assert tracker[3] == {2: 3} # after772 def test_just_before(self):773 """Test adding just before()."""774 tracker: t.List[dict] = []775 def to_call_before(decorated: Decorated):776 tracker.append({1: decorated.args})777 @decorate(before=to_call_before)778 def to_call(*args):779 tracker.append({2: args})780 to_call(1, 2)781 assert len(tracker) == 2782 assert tracker[0] == {1: (1, 2)}783 assert tracker[1] == {2: (1, 2)}784 def test_just_after(self):785 """Test adding just after()."""786 tracker: t.List[dict] = []787 def to_call_after(decorated: Decorated):788 tracker.append({1: decorated.args})789 @decorate(after=to_call_after)790 def to_call(*args):791 tracker.append({2: args})792 to_call(1, 2)793 assert len(tracker) == 2794 assert tracker[0] == {2: (1, 2)}795 assert tracker[1] == {1: (1, 2)}796 def test_just_instead(self):797 """Test adding just instead()."""798 tracker: t.List[dict] = []799 def to_call_instead(decorated: Decorated):800 tracker.append({1: decorated.args})801 @decorate(instead=to_call_instead)802 def to_call(*args):803 tracker.append({2: args})804 to_call(1, 2)805 assert len(tracker) == 1806 assert tracker[0] == {1: (1, 2)}807 def test_all_decorators_implicit_class(self):808 """Test adding one of each decorator type to a class."""809 tracker: t.List[dict] = []810 def to_call_before(decorated: Decorated):811 tracker.append({1: decorated.args})812 def to_call_after(decorated: Decorated):813 tracker.append({2: decorated.args})814 def to_call_instead(decorated: Decorated):815 tracker.append({3: decorated.args})816 return decorated(*decorated.args, **decorated.kwargs)817 @decorate(818 before=to_call_before, after=to_call_after, instead=to_call_instead819 )820 class _ToDecorate:821 def to_call(self, *args):822 tracker.append({4: args})823 _ToDecorate().to_call(1, 2)824 assert len(tracker) == 4825 assert tracker[0] == {1: (1, 2)} # before826 assert tracker[1] == {3: (1, 2)} # instead827 assert tracker[2] == {4: (1, 2)} # wrapped828 assert tracker[3] == {2: (1, 2)} # after829 def test_at_least_one_callable_must_be_specified(self):830 """Not specifying any callables does not work."""831 with pytest.raises(ValueError):832 @decorate()833 def _fn():834 pass835@pytest.mark.parametrize("decorator", [before, after, instead])836def test_extras_persistence(decorator):837 """Test the persistence across calls of extras"""838 def memo_func(_decorated, memo):839 memo.append("called")840 memo: list = []841 decorated = Mock(return_value=None)842 decorated.__name__ = str("decorated_mock")843 decorated = decorator(memo_func, memo=memo,)(decorated)844 for _ in range(5):845 decorated()846 assert len(memo) == 5...
mkhtml.py
Source:mkhtml.py
1#!/usr/bin/env python2import sys3import random4import re5from operator import itemgetter6import math7from itertools import islice8from datetime import datetime9from scipy.sparse import csr_matrix10from numpy import array, zeros, matrix11from sklearn import linear_model12from sklearn import cross_validation 13from sklearn import metrics14from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor15from data import loadTestJson, loadTrainJson16from LM import KneserNeyLM, ngrams17from wordshape import wordShape, capCount18from features import *19from model import *20# Make submission using model21def mkSub(modelF, trainFile, testFile, outFile):22 printNow("make submission")23 trainRows = list(loadTrainJson(trainFile))24 printNow(" load train rows")25 m = modelF()26 m.train(trainRows)27 printNow(" trained")28 29 makeSubmission(m, testFile, outFile)30 return m31def makeSubmission(model, testFile, outFile):32 rows = loadTestJson(testFile)33 printNow(" load test rows")34 with open(outFile, 'w') as f:35 f.write('Insult,Date,Comment\n')36 f.writelines(['%f,%s,%s\n' % (model.classify1(row), row.dt, row.rawText) for row in rows])37 printNow(" submission created")38def printNow(msg):39 print '%s [%s]' % (msg, datetime.strftime(datetime.now(), '%H:%M:%S'))40def printOutliers(outliers, outFile):41 def insultText(insult):42 if insult: return 'Insult'43 return ''44 def norm(s):45 s = s.replace('\n', '<br>')46 return s47 with open(outFile, 'w') as f:48 f.write('<html><table border="1">\n')49 f.writelines('<tr><td><b>%s</b></td><td><b>%.3f</b></td></tr>\n<tr><td colspan="2">%s</td></tr>\n' % (insultText(insult), score, norm(text)) for diff, insult, score, text in outliers)50 f.write('</table></html>')51def getOutliers(modelF, rows, n = 20, insult = True, k = 4):52 kfold = cross_validation.KFold(len(rows), k = k, indices = True, shuffle = True)53 rows = array(rows)54 train, test = next(islice(kfold, 1))55 model = modelF()56 model.train(rows[train])57 def out(row):58 score = model.classify1(row)59 return (abs(float(row.insult) - score), row.insult, score, row.text)60 return sorted(map(out, filter(lambda row: insult == row.insult, rows[test])), key = itemgetter(0), reverse = True)[:n]61def printOutliersRF(outliers, outFile):62 def insultText(insult):63 if insult: return 'Insult'64 return ''65 def norm(s):66 s = s.replace('\n', '<br>')67 return s68 with open(outFile, 'w') as f:69 f.write('<html><table border="1">\n')70 f.writelines('<tr><td><b>%s</b></td><td><b>%.3f</b></td><td>%s</td></tr>\n<tr><td colspan="3">%s</td></tr>\n' % (insultText(insult), score, ' '.join(['<b>%.3f</b>' % f for f in features]), norm(text)) for diff, insult, score, features, text in outliers)71 f.write('</table></html>')72def getOutliersRF(model, rows, n = 20, insult = True):73 def out(row):74 score = model.classify1(row.text)75 return (abs(float(row.insult) - score), row.insult, score, model.featurize(row.text), row.text)76 return sorted(map(out, filter(lambda row: insult == row.insult, rows)), key = itemgetter(0), reverse = True)[:n]77#78# Print important features79def topFeatures(model, n = 10, reverse = 1):80 return sorted([(word, weight) for ((word, c), weight) in zip(model.featDict.items(), model.estimator.coef_[0])], key = itemgetter(1), reverse = reverse)[:n]81# some models82def wordsLogistic():83 return LogRegModel(SetExtractor(decorateFeat('w[%s]', textFeat(getWords)), probScore))84def words2Logistic():85 return LogRegModel(SetExtractor(decorateFeat('n2[%s]', textFeat(getNgrams(2))), probScore))86def words12Logistic():87 f1 = decorateFeat('w[%s]', textFeat(getWords))88 f2 = decorateFeat('n2[%s]', textFeat(getNgrams(2)))89 return LogRegModel(SetExtractor(combine(f1, f2), probScore))90def words12SortedLogistic():91 f1 = decorateFeat('w[%s]', textFeat(getWords))92 f2 = decorateFeat('n2[%s]', textFeat(getNgramsSorted(2)))93 return LogRegModel(SetExtractor(combine(f1, f2), probScore))94def ngramsLogistic(n):95 mask = 'ss' + str(n) + '[%s]'96 return lambda: LogRegModel(SetExtractor(decorateFeat(mask, textFeat(getCharNgrams(n))), probScore))97def ngramsRank(n):98 mask = 'ss' + str(n) + '[%s]'99 return lambda: RankModel(SetExtractor(decorateFeat(mask, textFeat(getCharNgrams(n))), probScore))100def ngramsTfLogistic(n):101 mask = 'ss' + str(n) + '[%s]'102 return lambda: LogRegModel(TFExtractor(decorateFeat(mask, textFeat(getCharNgrams(n)))))103def ngramsTfRank(n):104 mask = 'ss' + str(n) + '[%s]'105 return lambda: RankModel(TFExtractor(decorateFeat(mask, textFeat(getCharNgrams(n)))))106def wordShapesLogistic():107 return LogRegModel(SetExtractor(decorateFeat('shape[%s]', textFeat(wordShapes)), probScore))108def wordShapesTfLogistic():109 return LogRegModel(TFExtractor(decorateFeat('shape[%s]', textFeat(wordShapes))))110def stemLogistic():111 return LogRegModel(SetExtractor(decorateFeat('stem[%s]', getStems1), probScore))112def stemRank():113 return RankModel(SetExtractor(decorateFeat('stem[%s]', getStems1), probScore))114def stem2Logistic():115 f1 = decorateFeat('stem2[%s]', getStemNgrams(2))116 return LogRegModel(SetExtractor(f1, probScore), C = 11)117def stem12Logistic():118 f1 = decorateFeat('stem1[%s]', getStems1)119 f2 = decorateFeat('stem2[%s]', getStemNgrams(2))120 return LogRegModel(SetExtractor(combine(f1, f2), probScore), C = 11)121def stem12Rank():122 f1 = decorateFeat('stem1[%s]', getStems1)123 f2 = decorateFeat('stem2[%s]', getStemNgrams(2))124 return RankModel(SetExtractor(combine(f1, f2), probScore))125def stem12Ridge():126 f1 = decorateFeat('stem1[%s]', getStems1)127 f2 = decorateFeat('stem2[%s]', getStemNgrams(2))128 return RegModel(SetExtractor(combine(f1, f2), probScore), estimator = linear_model.Ridge(alpha = 14))129def stem12SortedLogistic():130 f1 = decorateFeat('stem1[%s]', getStems1)131 f2 = decorateFeat('stem2[%s]', getStemNgramsSorted(2))132 return LogRegModel(SetExtractor(combine(f1, f2), probScore))133def stem12SortedRank():134 f1 = decorateFeat('stem1[%s]', getStems1)135 f2 = decorateFeat('stem2[%s]', getStemNgramsSorted(2))136 return RankModel(SetExtractor(combine(f1, f2), probScore))137def tagsLogistic():138 f1 = decorateFeat('stem1[%s]', getTags)139 return LogRegModel(SetExtractor(f1, probScore))140def tags12Logistic():141 f1 = decorateFeat('tag[%s]', getTags)142 f2 = decorateFeat('tag2[%s]', getTagNgrams(2))143 return LogRegModel(SetExtractor(combine(f1, f2), probScore))144def tags12TfLogistic():145 f1 = decorateFeat('tag[%s]', getTags)146 f2 = decorateFeat('tag2[%s]', getTagNgrams(2))147 return LogRegModel(TFExtractor(combine(f1, f2)))148#149# LM classifiers150def wordsLm(n):151 return lambda: LMModel(WordsSeqExtractor(wordsSeq), n = n)152def stemLm(n):153 return lambda: LMModel(WordsSeqExtractor(getStems), n = n)154def tagLm(n):155 return lambda: LMModel(SeqExtractor(getTags), n = n)156#157# Subseq classifiers158def wordsSubseq2Logistic(n):159 return lambda: LogRegModel(SetExtractor(getSubseq2(wordsSeq, n), probScore))160def wordsSubseq3Logistic(n):161 return lambda: LogRegModel(SetExtractor(getSubseq3(wordsSeq, n), probScore))162def stemsSubseq2Logistic(n):163 return lambda: LogRegModel(SetExtractor(getSubseq2(getStems, n), probScore))164def stemsSubseq2Rank(n):165 return lambda: RankModel(SetExtractor(getSubseq2(getStems, n), probScore))166def stemsSubseq3Logistic(n):167 return lambda: LogRegModel(SetExtractor(getSubseq3(getStems, n), probScore))168def tagsSubseq2Logistic(n):169 return lambda: LogRegModel(SetExtractor(getSubseq2(getTags, n), probScore))170def tagsSubseq3Logistic(n):171 return lambda: LogRegModel(SetExtractor(getSubseq3(getTags, n), probScore))172def stemsSubseq2SortedLogistic(n):173 return lambda: LogRegModel(SetExtractor(getSubseq2Sorted(getStems, n), probScore))174def stemsSubseq2SortedRank(n):175 return lambda: RankModel(SetExtractor(getSubseq2Sorted(getStems, n), probScore))176def stemsSubseq2SortedRank(n):177 return lambda: RankModel(SetExtractor(getSubseq2Sorted(getStems, n), probScore))178def stemsSubseq3SortedLogistic(n):179 return lambda: LogRegModel(SetExtractor(getSubseq3Sorted(getStems, n), probScore))180def tagsSubseq2SortedLogistic(n):181 return lambda: LogRegModel(SetExtractor(getSubseq2Sorted(getTags, n), probScore))182def tagsSubseq3SortedLogistic(n):183 return lambda: LogRegModel(SetExtractor(getSubseq3Sorted(getTags, n), probScore))184#185# Mixed ngrams classifiers186def mixedST():187 return LogRegModel(SetExtractor(mixedNgramsST, probScore))188def mixedTS():189 return LogRegModel(SetExtractor(mixedNgramsTS, probScore))190def mixedST_TS():191 f1 = mixedNgramsST192 f2 = mixedNgramsTS193 return LogRegModel(SetExtractor(combine(f1, f2), probScore))194def mixedSST():195 return LogRegModel(SetExtractor(mixedNgramsSST, probScore))196def mixedSTS():197 return LogRegModel(SetExtractor(mixedNgramsSTS, probScore))198def mixedSTT():199 return LogRegModel(SetExtractor(mixedNgramsSTT, probScore))200def mixedTSS():201 return LogRegModel(SetExtractor(mixedNgramsTSS, probScore))202def mixedTST():203 return LogRegModel(SetExtractor(mixedNgramsTST, probScore))204def mixedTTS():205 return LogRegModel(SetExtractor(mixedNgramsTTS, probScore))206def mixedSTT_TST_TTS():207 f1 = mixedNgramsSTT208 f2 = mixedNgramsTST209 f3 = mixedNgramsTTS210 return LogRegModel(SetExtractor(combine(f1, f2, f3), probScore))211# Syntax classifiers212def syntaxStems12():213 f1 = decorateFeat('stem1[%s]', getStems1)214 f2 = decorateFeat('syn[%s]', synStems2)215 return LogRegModel(SetExtractor(combine(f1, f2), probScore))216def syntaxStems2():217 return LogRegModel(SetExtractor(synStems2, probScore))218def syntaxStems2Dep():219 return LogRegModel(SetExtractor(synStems2Dep, probScore))220def syntaxStemsL():221 return LogRegModel(SetExtractor(synStemsL, probScore))222def syntaxStemsR():223 return LogRegModel(SetExtractor(synStemsR, probScore))224def syntaxStemsLR():225 f1 = decorateFeat('synL[%s]', synStemsL)226 f2 = decorateFeat('synR[%s]', synStemsR)227 return LogRegModel(SetExtractor(combine(f1, f2), probScore))228def syntaxStems12_LR():229 f1 = decorateFeat('stem1[%s]', getStems1)230 f2 = decorateFeat('syn[%s]', synStems2)231 f3 = decorateFeat('synL[%s]', synStemsL)232 f4 = decorateFeat('synR[%s]', synStemsR)233 return LogRegModel(SetExtractor(combine(f1, f2, f3, f4), probScore))234# syntax - from dependency graph235def syntaxStems3():236 return LogRegModel(SetExtractor(synStems3, probScore))237def syntaxStems123():238 f1 = decorateFeat('stem1[%s]', getStems1)239 f2 = decorateFeat('syn2[%s]', synStems2)240 f3 = decorateFeat('syn3[%s]', synStems3)241 return LogRegModel(SetExtractor(combine(f1, f2, f3), probScore))242def syntaxTags2():243 return LogRegModel(SetExtractor(synTags2, probScore))244def syntaxTags3():245 return LogRegModel(SetExtractor(synTags3, probScore))246def syntaxTags12():247 f1 = decorateFeat('tags1[%s]', getTags)248 f2 = decorateFeat('tags2[%s]', synTags2)249 return LogRegModel(SetExtractor(combine(f1, f2), probScore))250def syntaxTags123():251 f1 = decorateFeat('tags1[%s]', getTags)252 f2 = decorateFeat('tags2[%s]', synTags2)253 f3 = decorateFeat('tags3[%s]', synTags3)254 return LogRegModel(SetExtractor(combine(f1, f2, f3), probScore))255def syntaxMixedST():256 return LogRegModel(SetExtractor(synMixedST, probScore))257def syntaxMixedTS():258 return LogRegModel(SetExtractor(synMixedTS, probScore))259def syntaxMixedST_TS():260 f1 = synMixedST261 f2 = synMixedTS262 return LogRegModel(SetExtractor(combine(f1, f2), probScore))263def syntaxMixedSST():264 return LogRegModel(SetExtractor(synMixedSST, probScore))265def syntaxMixedSTS():266 return LogRegModel(SetExtractor(synMixedSTS, probScore))267def syntaxMixedSTT():268 return LogRegModel(SetExtractor(synMixedSTT, probScore))269def syntaxMixedTSS():270 return LogRegModel(SetExtractor(synMixedTSS, probScore))271def syntaxMixedTST():272 return LogRegModel(SetExtractor(synMixedTST, probScore))273def syntaxMixedTTS():274 return LogRegModel(SetExtractor(synMixedTTS, probScore))275def syntaxMixedSTT_TST_TTS():276 f1 = synMixedSTT277 f2 = synMixedTST278 f3 = synMixedTTS279 return LogRegModel(SetExtractor(combine(f1, f2, f3), probScore))280# syntax - sentence level281def syntaxStems12Sen():282 return SenModel(syntaxStems12())283def syntaxStems2Sen():284 return SenModel(syntaxStems2())285def syntaxStems2DepSen():286 return SenModel(syntaxStems2Dep())287def syntaxStemsLSen():288 return SenModel(syntaxStemsL())289def syntaxStemsRSen():290 return SenModel(syntaxStemsR())291def syntaxStemsLRSen():292 return SenModel(syntaxStemsLR())293def syntaxStems12_LRSen():294 return SenModel(syntaxStems12_LR())295#296# Basic exctractors297def logLen():298 return Basic(lambda row: math.log(1.0 + sum(map(lambda sen: len(sen.tokens), row.sentences))))299def logSentencesCount():300 return Basic(lambda row: math.log(1.0 + len(row.sentences)))301def upperPortion():302 def f(row):303 u, l, d, p, o = capCount(row.text)304 return (1.0 + u)/(1.0 + u + l + d + p + o)305 return Basic(f)306def lowerPortion():307 def f(row):308 u, l, d, p, o = capCount(row.text)309 return (1.0 + l)/(1.0 + u + l + d + p + o)310 return Basic(f)311def digitPortion():312 def f(row):313 u, l, d, p, o = capCount(row.text)314 return (1.0 + d)/(1.0 + u + l + d + p + o)315 return Basic(f)316def puncPortion():317 def f(row):318 u, l, d, p, o = capCount(row.text)319 return (1.0 + p)/(1.0 + u + l + d + p + o)320 return Basic(f)321def otherPortion():322 def f(row):323 u, l, d, p, o = capCount(row.text)324 return (1.0 + o)/(1.0 + u + l + d + p + o)325 return Basic(f)326#327# Combined classifiers328def sub5():329 f1 = getStems1330 f2 = getStemNgrams(2)331 f3 = textFeat(getCharNgrams(2))332 return LogRegModel(SetExtractor(combine(f1, f2, f3), probScore))333def sub8():334 f1 = getStems1335 f2 = getStemNgrams(2)336 e1 = SetExtractor(combine(f1, f2), probScore)337 f3 = textFeat(getCharNgrams(2))338 e2 = TFExtractor(f3)339 return LogRegModel(CombinedExtractor(e1, e2), C = 6)340def sub8Ridge():341 f1 = getStems1342 f2 = getStemNgrams(2)343 e1 = SetExtractor(combine(f1, f2), probScore)344 f3 = textFeat(getCharNgrams(2))345 e2 = TFExtractor(f3)346 return RegModel(CombinedExtractor(e1, e2), estimator = linear_model.Ridge(alpha = 1))347def sub5_1():348 f1 = getStems1349 f2 = getStemNgramsSorted(2)350 f3 = textFeat(getCharNgrams(2))351 return LogRegModel(SetExtractor(combine(f1, f2, f3), probScore))352# specialized353def ngramsLogistic_2():354 return ngramsLogistic(2)()355def ngramsLogistic_3():356 return ngramsLogistic(3)()357def ngramsLogistic_4():358 return ngramsLogistic(4)()359def ngramsTfLogistic_2():360 return ngramsLogistic(2)()361def ngramsTfLogistic_3():362 return ngramsLogistic(3)()363def ngramsTfLogistic_4():364 return ngramsLogistic(4)()365def ngramsRank_2():366 return ngramsLogistic(2)()367def ngramsRank_3():368 return ngramsLogistic(3)()369def ngramsRank_4():370 return ngramsLogistic(4)()371def ngramsTfRank_2():372 return ngramsLogistic(2)()373def ngramsTfRank_3():374 return ngramsLogistic(3)()375def ngramsTfRank_4():376 return ngramsLogistic(4)()377def ngramsLogisticSen_2():378 return SenModel(ngramsLogistic(2)())379def ngramsLogisticSen_3():380 return SenModel(ngramsLogistic(3)())381def ngramsLogisticSen_4():382 return SenModel(ngramsLogistic(4)())383def ngramsTfLogisticSen_2():384 return SenModel(ngramsLogistic(2)())385def ngramsTfLogisticSen_3():386 return SenModel(ngramsLogistic(3)())387def ngramsTfLogisticSen_4():388 return SenModel(ngramsLogistic(4)())389def ngramsRankSen_2():390 return SenModel(ngramsLogistic(2)())391def ngramsRankSen_3():392 return SenModel(ngramsLogistic(3)())393def ngramsRankSen_4():394 return SenModel(ngramsLogistic(4)())395def ngramsTfRankSen_2():396 return SenModel(ngramsLogistic(2)())397def ngramsTfRankSen_3():398 return SenModel(ngramsLogistic(3)())399def ngramsTfRankSen_4():400 return SenModel(ngramsLogistic(4)())401#402# LM403def wordsLm_2():404 return wordsLm(2)()405def wordsLm_3():406 return wordsLm(3)()407def wordsLm_4():408 return wordsLm(4)()409def stemLm_2():410 return stemLm(2)()411def stemLm_3():412 return stemLm(3)()413def stemLm_4():414 return stemLm(4)()415def stemLm_5():416 return stemLm(5)()417def stemLm_6():418 return stemLm(6)()419def stemLm_7():420 return stemLm(7)()421def stemLmSen_2():422 return SenModel(stemLm(2)())423def stemLmSen_3():424 return SenModel(stemLm(3)())425def stemLmSen_4():426 return SenModel(stemLm(4)())427def stemLmSen_5():428 return SenModel(stemLm(5)())429def stemLmSen_6():430 return SenModel(stemLm(6)())431def stemLmSen_7():432 return SenModel(stemLm(7)())433def tagLm_2():434 return tagLm(2)()435def tagLm_3():436 return tagLm(3)()437def tagLm_4():438 return tagLm(4)()439def tagLm_5():440 return tagLm(5)()441def tagLm_6():442 return tagLm(6)()443def tagLm_7():444 return tagLm(7)()445def tagLmSen_2():446 return SenModel(tagLm(2)())447def tagLmSen_3():448 return SenModel(tagLm(3)())449def tagLmSen_4():450 return SenModel(tagLm(4)())451def tagLmSen_5():452 return SenModel(tagLm(5)())453def tagLmSen_6():454 return SenModel(tagLm(6)())455def tagLmSen_7():456 return SenModel(tagLm(7)())457# subseq2458def stemsSubseq2Logistic_5():459 return stemsSubseq2Logistic(5)()460def stemsSubseq2Logistic_6():461 return stemsSubseq2Logistic(6)()462def stemsSubseq2SortedLogistic_5():463 return stemsSubseq2SortedLogistic(5)()464def stemsSubseq2SortedLogistic_6():465 return stemsSubseq2SortedLogistic(6)()466def stemsSubseq2Rank_5():467 return stemsSubseq2Rank(5)()468def stemsSubseq2SortedRank_5():469 return stemsSubseq2SortedRank(5)()470def tagsSubseq2Logistic_5():471 return tagsSubseq2Logistic(5)()472def tagsSubseq2Logistic_6():473 return tagsSubseq2Logistic(6)()474def tagsSubseq2SortedLogistic_5():475 return tagsSubseq2SortedLogistic(5)()476def tagsSubseq2SortedLogistic_6():477 return tagsSubseq2SortedLogistic(6)()478# subseq3479def stemsSubseq3Logistic_5():480 return stemsSubseq3Logistic(5)()481def stemsSubseq3Logistic_6():482 return stemsSubseq3Logistic(6)()483def stemsSubseq3SortedLogistic_5():484 return stemsSubseq3SortedLogistic(5)()485def stemsSubseq3SortedLogistic_6():486 return stemsSubseq3SortedLogistic(6)()487def tagsSubseq3Logistic_4():488 return tagsSubseq3Logistic(4)()489def tagsSubseq3Logistic_5():490 return tagsSubseq3Logistic(5)()491def tagsSubseq3Logistic_6():492 return tagsSubseq3Logistic(6)()493def tagsSubseq3SortedLogistic_5():494 return tagsSubseq3SortedLogistic(5)()495def tagsSubseq3SortedLogistic_6():...
mapped.py
Source:mapped.py
...93def read_key(k):94 if isinstance(k, dict):95 return k['k']96 return k97def decorate(ax, d, m, **kwargs):98 if 'x' in kwargs:99 ax.set_xlabel(read_key(m[kwargs['x']]))100 if 'y' in kwargs:101 ax.set_ylabel(read_key(m[kwargs['y']]))102 if 'z' in kwargs:103 ax.set_zlabel(read_key(m[kwargs['z']]))104 if any([k in ('xt', 'xtl', 'yt', 'ytl', 'zt', 'ztl') for k in m]):105 rm = remap(d, m, asdocs=False)106 else:107 return108 if 'xt' in m:109 ax.set_xticks(rm['xt'])110 if 'xtl' in m:111 ax.set_xticklabels(rm['xtl'])112 if 'yt' in m:113 ax.set_yticks(rm['yt'])114 if 'ytl' in m:115 ax.set_yticklabels(rm['ytl'])116 if 'zt' in m:117 ax.set_zticks(rm['zt'])118 if 'ztl' in m:119 ax.set_zticklabels(rm['ztl'])120@pfunc(required=('left', 'height'))121def bar(d, m, *args, **kwargs):122 if kwargs.get('decorate', False):123 decorate(pylab.gca(), d, m, x='left', y='height')124 return125@pfunc(required=('bottom', 'width'))126def barh(d, m, *args, **kwargs):127 if kwargs.get('decorate', False):128 decorate(pylab.gca(), d, m, x='width', y='bottom')129 return130@pfunc(required=('x'), optional='y', auto=False)131def bin(d, m, *args, **kwargs):132 ax = pylab.gca()133 g = grouping.group(args[0], gtype='d') # thing to group134 lefts = [i for i in range(len(g))]135 labels = sorted(g.keys())136 if len(args) == 1:137 values = [len(g[k]) for k in labels]138 elif len(args) > 1: # a y was provided139 stat = np.flookup.lookup(kwargs.get('stat', 'mean'))140 d = np.convert.labeled_array(x=args[0], y=args[1])141 values = []142 for l in labels:143 values.append(stat(d[d['x'] == l]['y']))144 r = ax.bar(lefts, values)145 if kwargs.get('decorate', False):146 decorate(ax, d, m, x='x', y='y')147 # make xticks & xticklabels if they're not defined148 if 'xt' not in m:149 ax.set_xticks([i + 0.5 for i in lefts])150 if 'xtl' not in m:151 ax.set_xticklabels(labels)152 return r153@pfunc(required=('x', 'y'))154def errorbar(d, m, *args, **kwargs):155 if kwargs.get('decorate', False):156 decorate(pylab.gca(), d, m, x='x', y='y')157 return158@pfunc(required='x')159def hist(d, m, *args, **kwargs):160 if kwargs.get('decorate', False):161 decorate(pylab.gca(), d, m, x='x')162 return163@pfunc(required='x', optional=('y', 'fmt'))164def plot(d, m, *args, **kwargs):165 if kwargs.get('decorate', False):166 decorate(pylab.gca(), d, m, x='x', y='y')167 return168@pfunc(required=('x', 'y'))169def scatter(d, m, *args, **kwargs):170 if kwargs.get('decorate', False):171 decorate(pylab.gca(), d, m, x='x', y='y')172 return173@pfunc(required='x')174def boxplot(d, m, *args, **kwargs):175 if kwargs.get('decorate', False):176 decorate(pylab.gca(), d, m, x='x')177 return178@pfunc(required='y')179def axhline(d, m, *args, **kwargs):180 if kwargs.get('decorate', False):181 decorate(pylab.gca(), d, m, y='y')182 return183@pfunc(required='x')184def axvline(d, m, *args, **kwargs):185 if kwargs.get('decorate', False):186 decorate(pylab.gca(), d, m, x='x')187 return188@pfunc(required=('ymin', 'ymax'))189def axhspan(d, m, *args, **kwargs):190 if kwargs.get('decorate', False):191 decorate(pylab.gca(), d, m, y='ymin')192 return193@pfunc(required=('xmin', 'xmax'))194def axvspan(d, m, *args, **kwargs):195 if kwargs.get('decorate', False):196 decorate(pylab.gca(), d, m, x='xmin')197 return198@pfunc(required=('x', 'y'), optional='c')199def fill(d, m, *args, **kwargs):200 if kwargs.get('decorate', False):201 decorate(pylab.gca(), d, m, x='x', y='y')202 return203@pfunc(required=('x', 'y1'))204def fill_between(d, m, *args, **kwargs):205 if kwargs.get('decorate', False):206 decorate(pylab.gca(), d, m, x='x', y='y1')207 return208@pfunc(required=('y', 'x1'))209def fill_betweenx(d, m, *args, **kwargs):210 if kwargs.get('decorate', False):211 decorate(pylab.gca(), d, m, x='x1', y='y')212 return213@pfunc(required=('y', 'xmin', 'xmax'))214def hlines(d, m, *args, **kwargs):215 if kwargs.get('decorate', False):216 decorate(pylab.gca(), d, m, x='xmin', y='y')217 return218@pfunc(required=('x', 'ymin', 'ymax'))219def vlines(d, m, *args, **kwargs):220 if kwargs.get('decorate', False):221 decorate(pylab.gca(), d, m, x='x', y='ymin')222 return223# ======= 3D =======224def get_3d_axes():225 ax = pylab.gca()226 if not isinstance(ax, mplot3d.Axes3D):227 # remove axis from plot228 axg = ax.get_geometry()229 # replace with a 3d projected one230 f = pylab.gcf()231 f.delaxes(ax)232 ax = f.add_subplot(*axg, projection='3d')233 return ax234@pfunc(required=('x', 'y'), optional='z', auto=False)235def plot3d(d, m, *args, **kwargs):236 ax = get_3d_axes()237 d = kwargs.pop('decorate', False)238 r = ax.plot(*args, **kwargs)239 if d:240 decorate(ax, d, m, x='x', y='y', z='z')241 return r242@pfunc(required=('x', 'y'), optional='z', auto=False)243def scatter3d(d, m, *args, **kwargs):244 ax = get_3d_axes()245 d = kwargs.pop('decorate', False)246 r = ax.scatter(*args, **kwargs)247 if d:248 decorate(ax, d, m, x='x', y='y', z='z')249 return r250@pfunc(required=('x', 'y', 'z'), auto=False)251def wireframe3d(d, m, *args, **kwargs):252 ax = get_3d_axes()253 d = kwargs.pop('decorate', False)254 r = ax.plot_wireframe(*args, **kwargs)255 if d:256 decorate(ax, d, m, x='x', y='y', z='z')257 return r258@pfunc(required=('x', 'y', 'z'), auto=False)259def surface3d(d, m, *args, **kwargs):260 ax = get_3d_axes()261 d = kwargs.pop('decorate', False)262 r = ax.plot_surface(*args, **kwargs)263 if d:264 decorate(ax, d, m, x='x', y='y', z='z')265 return r266@pfunc(required=('x', 'y', 'z'), auto=False)267def trisurf3d(d, m, *args, **kwargs):268 ax = get_3d_axes()269 d = kwargs.pop('decorate', False)270 r = ax.plot_trisurf(*args, **kwargs)271 if d:272 decorate(ax, d, m, x='x', y='y', z='z')273 return r274@pfunc(required=('x', 'y', 'z'), auto=False)275def contour3d(d, m, *args, **kwargs):276 ax = get_3d_axes()277 d = kwargs.pop('decorate', False)278 r = ax.contour(*args, **kwargs)279 if d:280 decorate(ax, d, m, x='x', y='y', z='z')281 return r282@pfunc(required=('x', 'y', 'z'), auto=False)283def contourf3d(d, m, *args, **kwargs):284 ax = get_3d_axes()285 d = kwargs.pop('decorate', False)286 r = ax.contourf(*args, **kwargs)287 if d:288 decorate(ax, d, m, x='x', y='y', z='z')289 return r290@pfunc(required='col', auto=False)291def collection3d(d, m, *args, **kwargs):292 ax = get_3d_axes()293 kwargs.pop('decorate', False)294 r = ax.add_collection3d(*args, **kwargs)295 return r296@pfunc(required=('left', 'height'), optional='zs', auto=False)297def bar3d(d, m, *args, **kwargs):298 ax = get_3d_axes()299 d = kwargs.pop('decorate', False)300 r = ax.bar3d(*args, **kwargs)301 if d:302 decorate(ax, d, m, x='left', y='height', z='zs')303 return r304@pfunc(required=('x', 'y', 'z', 's'), auto=False)305def text3d(d, m, *args, **kwargs):306 ax = get_3d_axes()307 d = kwargs.pop('decorate', False)308 r = ax.text3d(*args, **kwargs)309 if d:310 decorate(ax, d, m, x='x', y='y', z='z')...
testWff.py
Source:testWff.py
...29 def test_false(self):30 self.assertEqual("FALSE", str(Wff.false()))31 self.assertEqual(0, Wff.false().depth)32 33 def test_decorate(self):34 for prop in glob.prop_database():35 # can decorate a property36 dec = Wff.decorate(prop.exprcore)37 self.assertEqual(str(dec), str(prop.exprcore))38 39 # can decorate a plain node40 x = self.enc.by_name["x"]41 _x = Wff.decorate(x.name)42 self.assertEqual("x", str(_x))43 44 # combination possible between plain nodes and specs45 self.assertEqual(str(dec | _x), '('+str(prop.exprcore)+" | x)")46 47 def test_depth(self):48 # raw symbol has no depth49 x = self.enc.by_name["x"]50 y = self.enc.by_name["y"]51 52 x_ = Wff.decorate(x.name)53 y_ = Wff.decorate(y.name)54 55 # propositional connectives do not increase the depth56 self.assertEqual(0, (x_ & y_).depth)57 self.assertEqual(0, (x_ | y_).depth)58 self.assertEqual(0, (- x_).depth)59 self.assertEqual(0, (x_.implies(y_)).to_negation_normal_form().depth)60 self.assertEqual(0, (x_.iff(y_)).to_negation_normal_form().depth)61 62 # temporal operators do increase the depth63 self.assertEqual(42, x_.next_times(42).depth) # 42 times X ( .. X(x))64 self.assertEqual( 1, x_.opnext().depth) # X x65 self.assertEqual( 1, x_.opprec().depth) # Y x66 self.assertEqual( 1, x_.opnotprecnot().depth) # Z x67 self.assertEqual( 1, x_.globally().depth) # G x68 self.assertEqual( 1, x_.historically().depth) # H x69 self.assertEqual( 1, x_.eventually().depth) # F x70 self.assertEqual( 1, x_.once().depth) # O x71 self.assertEqual( 1, x_.until(y_).depth) # x U y72 self.assertEqual( 1, x_.since(y_).depth) # x S y73 self.assertEqual( 1, x_.releases(y_).depth) # x V y74 self.assertEqual( 1, x_.triggered(y_).depth) # x T y75 76 def test_to_negation_normal_form(self):77 x = self.enc.by_name["x"]78 y = self.enc.by_name["y"]79 80 x_ = Wff.decorate(x.name)81 y_ = Wff.decorate(y.name)82 83 self.assertEqual("(x -> y)", str(x_.implies(y_)))84 self.assertEqual("(!x | y)", str(x_.implies(y_).to_negation_normal_form()))85 86 self.assertEqual("(x <-> y)", str(x_.iff(y_)))87 self.assertEqual("((!x | y) & (x | !y))", str(x_.iff(y_).to_negation_normal_form()))88 89 def test_to_node(self):90 x = self.enc.by_name["x"]91 x_ = Wff.decorate(x.name)92 93 self.assertEqual(x.name, x_.to_node())94 95 def test_to_boolean_wff(self):96 x = self.enc.by_name["x"]97 x_ = Wff.decorate(x.name).to_boolean_wff(glob.bdd_encoding())98 # TODO: find something better to validate this99 self.assertIsNotNone(x_)100 101 def test_to_be(self):102 x = self.enc.by_name["x"]103 x_ = Wff.decorate(x.name).to_be(self.enc)104 self.assertIsNotNone(self.enc.by_expr[x_], x.boolean_expression)105 106 def test_not_(self):107 x = self.enc.by_name["x"]108 x_ = Wff.decorate(x.name)109 self.assertEqual("!x", str(x_.not_()))110 111 def test_and_(self):112 x = self.enc.by_name["x"]113 y = self.enc.by_name["y"]114 115 x_ = Wff.decorate(x.name)116 y_ = Wff.decorate(y.name)117 self.assertEqual("(x & y)", str(x_.and_(y_)))118 119 def test_or_(self):120 x = self.enc.by_name["x"]121 y = self.enc.by_name["y"]122 123 x_ = Wff.decorate(x.name)124 y_ = Wff.decorate(y.name)125 self.assertEqual("(x | y)", str(x_.or_(y_)))126 127 def test_implies(self):128 x = self.enc.by_name["x"]129 y = self.enc.by_name["y"]130 131 x_ = Wff.decorate(x.name)132 y_ = Wff.decorate(y.name)133 self.assertEqual("(x -> y)", str(x_.implies(y_)))134 135 def test_iff(self):136 x = self.enc.by_name["x"]137 y = self.enc.by_name["y"]138 139 x_ = Wff.decorate(x.name)140 y_ = Wff.decorate(y.name)141 self.assertEqual("(x <-> y)", str(x_.iff(y_)))142 143 def test_next(self):144 x = self.enc.by_name["x"]145 x_ = Wff.decorate(x.name)146 self.assertEqual("next(x)", str(x_.next_()))147 148 def test_next_times(self):149 x = self.enc.by_name["x"]150 x_ = Wff.decorate(x.name)151 self.assertEqual("x", str(x_.next_times(0)))152 self.assertEqual(" X x", str(x_.next_times(1)))153 self.assertEqual(" X ( X ( X x))", str(x_.next_times(3)))154 155 def test_opnext(self):156 x = self.enc.by_name["x"]157 x_ = Wff.decorate(x.name)158 self.assertEqual(" X x", str(x_.opnext()))159 def test_opprec(self):160 x = self.enc.by_name["x"]161 x_ = Wff.decorate(x.name)162 self.assertEqual(" Y x", str(x_.opprec()))163 164 def test_opnotprecnot(self):165 x = self.enc.by_name["x"]166 x_ = Wff.decorate(x.name)167 self.assertEqual(" Z x", str(x_.opnotprecnot()))168 169 def test_globally(self):170 x = self.enc.by_name["x"]171 x_ = Wff.decorate(x.name)172 self.assertEqual(" G x", str(x_.globally()))173 174 def test_historically(self):175 x = self.enc.by_name["x"]176 x_ = Wff.decorate(x.name)177 self.assertEqual(" H x", str(x_.historically()))178 179 def test_eventually(self):180 x = self.enc.by_name["x"]181 x_ = Wff.decorate(x.name)182 self.assertEqual(" F x", str(x_.eventually()))183 184 def test_once(self):185 x = self.enc.by_name["x"]186 x_ = Wff.decorate(x.name)187 self.assertEqual(" O x", str(x_.once()))188 189 def test_until(self):190 x = self.enc.by_name["x"]191 y = self.enc.by_name["y"]192 193 x_ = Wff.decorate(x.name)194 y_ = Wff.decorate(y.name)195 self.assertEqual("(x U y)", str(x_.until(y_)))196 197 def test_since(self):198 x = self.enc.by_name["x"]199 y = self.enc.by_name["y"]200 201 x_ = Wff.decorate(x.name)202 y_ = Wff.decorate(y.name)203 self.assertEqual("(x S y)", str(x_.since(y_)))204 205 def test_releases(self):206 x = self.enc.by_name["x"]207 y = self.enc.by_name["y"]208 209 x_ = Wff.decorate(x.name)210 y_ = Wff.decorate(y.name)211 self.assertEqual("(x V y)", str(x_.releases(y_)))212 213 def test_triggered(self):214 x = self.enc.by_name["x"]215 y = self.enc.by_name["y"]216 217 x_ = Wff.decorate(x.name)218 y_ = Wff.decorate(y.name)219 self.assertEqual("(x T y)", str(x_.triggered(y_)))220 221 def test_magicmethod_and(self):222 x = self.enc.by_name["x"]223 y = self.enc.by_name["y"]224 225 x_ = Wff.decorate(x.name)226 y_ = Wff.decorate(y.name)227 self.assertEqual("(x & y)", str(x_ & y_))228 229 def test_magicmethod_or(self):230 x = self.enc.by_name["x"]231 y = self.enc.by_name["y"]232 233 x_ = Wff.decorate(x.name)234 y_ = Wff.decorate(y.name)235 self.assertEqual("(x | y)", str(x_ | y_))236 237 def test_magicmethod_neg(self):238 x = self.enc.by_name["x"]239 240 x_ = Wff.decorate(x.name)241 self.assertEqual("!x", str( - x_ ))242 243 def test_magicmethod_invert(self):244 x = self.enc.by_name["x"]245 246 x_ = Wff.decorate(x.name)...
decorators.py
Source:decorators.py
...1112 self._params_decoration = None13 self._result_decoration = None1415 def _decorate(self, fn, mode, **kwargs):16 if mode == self.MODE_OVERRIDE:17 self._decorate_full(fn, **kwargs)18 elif mode == self.MODE_PARAMS:19 self._decorate_params(fn)20 elif mode == self.MODE_RESULT:21 self._decorate_result(fn, **kwargs)2223 def _decorate_full(self, fn, needs_origin=True):24 origin = self._callable2526 if needs_origin:27 if self.is_method:28 self._callable = lambda inst, *args, **kwargs: fn(inst, origin, *args, **kwargs)29 else:30 self._callable = lambda *args, **kwargs: fn(origin, *args, **kwargs)31 else:32 self._callable = fn3334 def _decorate_params(self, fn):35 if not self._params_decoration:36 self._params_decoration = []3738 self._params_decoration.append(fn)3940 def _decorate_result(self, fn, needs_params=False):41 if not self._result_decoration:42 self._result_decoration = []4344 fn._needs_params = needs_params45 self._result_decoration.append(fn)4647 def __call__(self, *args, **kwargs):48 if self._params_decoration:49 for dec in self._params_decoration:50 try:51 args, kwargs = dec(*args, **kwargs)52 except ReturnImediatelyException, e:53 return e.ret5455 res = self._callable(*args, **kwargs)5657 if self._result_decoration:58 for dec in self._result_decoration:59 if dec._needs_params:60 res = dec(res, *args, **kwargs)61 else:62 res = dec(res)6364 return res6566class ReturnImediatelyException(Exception):67 def __init__(self, ret):68 super(Exception, self).__init__()69 self.ret = ret7071def _check_decoratable(origin, install=True):72 if not hasattr(origin, '_decoratable_obj'):73 if inspect.ismethod(origin) and not hasattr(origin, '_decoratable_obj'):74 decoratable = DecoratableObject(origin)7576 def decoratable_method(self, *args, **kwargs):77 return decoratable(self, *args, **kwargs)7879 decoratable_method._decoratable_obj = decoratable8081 def decoratable_decorate(fn, mode, **kwargs):82 decoratable._decorate(fn, mode, **kwargs)8384 decoratable_method._decorate = decoratable_decorate8586 if install:87 setattr(origin.im_class, origin.__name__, decoratable_method)8889 return decoratable_method90 91 elif inspect.isfunction(origin):92 decoratable = DecoratableObject(origin)9394 def decorated(*args, **kwargs):95 return decoratable(*args, **kwargs)9697 decorated._decoratable_obj = decoratable9899 if install:100 setattr(inspect.getmodule(origin), origin.__name__, decorated)101102 decorated.__name__ = origin.__name__103 decorated.__module__ = origin.__module__104105 return decorated106107 return origin108109110def decorate(origin, needs_origin=True):111 origin = _check_decoratable(origin)112113 def decorator(fn):114 origin._decoratable_obj._decorate(fn, DecoratableObject.MODE_OVERRIDE, needs_origin=needs_origin)115 116 return decorator117118119def _decorate_params(origin):120 origin = _check_decoratable(origin)121122 def decorator(fn):123 origin._decoratable_obj._decorate(fn, DecoratableObject.MODE_PARAMS)124125 return decorator126127decorate.params = _decorate_params128129def _decorate_result(origin, needs_params=False):130 origin = _check_decoratable(origin)131132 def decorator(fn):133 origin._decoratable_obj._decorate(fn, DecoratableObject.MODE_RESULT, needs_params=needs_params)134135 return decorator136137decorate.result = _decorate_result138139def _decorate_with(fn):140 def decorator(origin):141 origin = _check_decoratable(origin)142 origin._decoratable_obj._decorate(fn, DecoratableObject.MODE_OVERRIDE, needs_origin=True)143 return origin144 return decorator145146decorate.withfn = _decorate_with147148def _decorate_result_with(fn, needs_params=False):149 def decorator(origin):150 origin = _check_decoratable(origin)151 origin._decoratable_obj._decorate(fn, DecoratableObject.MODE_RESULT, needs_params=needs_params)152 return origin153 return decorator154155decorate.result.withfn = _decorate_result_with156157def _decorate_params_with(fn):158 def decorator(origin):159 origin = _check_decoratable(origin)160 origin._decoratable_obj._decorate(fn, DecoratableObject.MODE_PARAMS)161 return origin162 return decorator163
...
metadata.py
Source:metadata.py
1"""2.. module:: metadata3 :platform: Darwin, Linux, Unix, Windows4 :synopsis: Module that contains decorators that can be utilized to attach metadata to automation5 tasks, tests, scopes, and integrations.6.. moduleauthor:: Myron Walker <myron.walker@gmail.com>7"""8# pylint: disable=too-few-public-methods9__author__ = "Myron Walker"10__copyright__ = "Copyright 2020, Myron W Walker"11__credits__ = []12__version__ = "1.0.0"13__maintainer__ = "Myron Walker"14__email__ = "myron.walker@gmail.com"15__status__ = "Development" # Prototype, Development or Production16__license__ = "MIT"17class Category:18 """19 The 'Category' decorator allows test engineers to associate categories with individual test20 cases or collections of tests.21 """22 def __init__(self, *categories):23 if len(categories) == 0:24 raise ValueError("The 'Category' decorator requires at least one category arguement.")25 self._categories = categories26 return27 def __call__(self, obj_to_decorate):28 if not hasattr(obj_to_decorate, "_metadata_"):29 obj_to_decorate._metadata_ = {}30 if "categories" in obj_to_decorate._metadata_:31 obj_to_decorate._metadata_["categories"].extend(self._categories)32 else:33 obj_to_decorate._metadata_["categories"] = self._categories34 return obj_to_decorate35class Keywords:36 """37 The 'Keywords' decorator allows test engineers to associate keywords with individual test38 cases or collections of tests.39 """40 def __init__(self, *keywords):41 if len(keywords) == 0:42 raise ValueError("The 'Keyword' decorator requires at least one keyword arguement.")43 self._keywords = keywords44 return45 def __call__(self, obj_to_decorate):46 if not hasattr(obj_to_decorate, "_metadata_"):47 obj_to_decorate._metadata_ = {}48 if "keywords" in obj_to_decorate._metadata_:49 obj_to_decorate._metadata_["keywords"].extend(self._keywords)50 else:51 obj_to_decorate._metadata_["keywords"] = self._keywords52 return obj_to_decorate53class Priority:54 """55 The 'Priority' decorator allows test engineers to associate a test priority with56 individual test cases or collections of tests.57 """58 def __init__(self, priority):59 self._priority = priority60 return61 def __call__(self, obj_to_decorate):62 if not hasattr(obj_to_decorate, "_metadata_"):63 obj_to_decorate._metadata_ = {}64 if "priority" in obj_to_decorate._metadata_:65 obj_to_decorate._metadata_["priority"].extend(self._priority)66 else:67 obj_to_decorate._metadata_["priority"] = self._priority...
decoall-deco-any3.py
Source:decoall-deco-any3.py
1# Class decorator factory: apply any decorator to all methods of a class2from types import FunctionType3from decotools import tracer, timer4def decorateAll(decorator):5 def DecoDecorate(aClass):6 for attr, attrval in aClass.__dict__.items():7 if type(attrval) is FunctionType:8 setattr(aClass, attr, decorator(attrval)) # Not __dict__9 return aClass10 return DecoDecorate11#@decorateAll(tracer) # Use a class decorator12#@decorateAll(tracer(timer(label='@@'))) 13#@decorateAll(timer(label='@@')(tracer)) # Times applying the tracer!14#@decorateAll(tracer(timer(label='@@'))) # Traces applying the timer!15#@decorateAll(tracer) # Traces onCall wrapper, times methods16#@decorateAll(timer(label='@@'))17#@decorateAll(timer(label='@@'))18#@decorateAll(tracer) # Times onCall wrapper, traces methods19 20@decorateAll(timer(label='@@'))21@decorateAll(tracer) # Times onCall wrapper, traces methods22class Person: # Applies func decorator to methods23 def __init__(self, name, pay): # Person = decorateAll(..)(Person)24 self.name = name # Person = DecoDecorate(Person)25 self.pay = pay26 def giveRaise(self, percent):27 self.pay *= (1.0 + percent)28 def lastName(self):29 return self.name.split()[-1]30bob = Person('Bob Smith', 50000)31sue = Person('Sue Jones', 100000)32print(bob.name, sue.name)33sue.giveRaise(.10)34print('%.2f' % sue.pay)35print(bob.lastName(), sue.lastName())36# If using timer: total time per method37"""38print('-'*40)39print('%.5f' % Person.__init__.alltime)40print('%.5f' % Person.giveRaise.alltime)41print('%.5f' % Person.lastName.alltime)...
decorate.py
Source:decorate.py
...45class DecoratePlan(Decorate):46 call('plan')47 def __call__(self):48 return None49def decorate(binding):50 decorations = {}51 for name in Decorate.__catalogue__():52 value = Decorate.__invoke__(name, binding)53 decorations[name] = value54 return Profile(**decorations)55def decorate_void():...
Using AI Code Generation
1var mb = require('mountebank');2mb.create({3}, function () {4 console.log('mountebank started');5});6mb.post('/imposters', {7 {8 {9 equals: {10 }11 }12 {13 is: {14 headers: {15 },16 body: {17 }18 }19 }20 }21}, function () {22 console.log('imposter created');23});24mb.get('/imposters', function (error, response) {25 console.log(response.body);26});27mb.del('/imposters/2525', function () {28 console.log('imposter deleted');29});30mb.stop(function () {31 console.log('mountebank stopped');32});
Using AI Code Generation
1var mb = require('mountebank');2var imposter = {3 stubs: [{4 responses: [{ is: { body: 'Hello World!' } }]5 }]6};7mb.create(imposter).then(function (imposter) {8 console.log('Imposter created at: ' + imposter.url);9});10var mb = require('mountebank');11var imposter = {12 stubs: [{13 responses: [{ is: { body: 'Hello World!' } }]14 }]15};16mb.create(imposter).then(function (imposter) {17 console.log('Imposter created at: ' + imposter.url);18});19var mb = require('mountebank');20var imposter = {21 stubs: [{22 responses: [{ is: { body: 'Hello World!' } }]23 }]24};25mb.create(imposter).then(function (imposter) {26 console.log('Imposter created at: ' + imposter.url);27});28var mb = require('mountebank');29var imposter = {30 stubs: [{31 responses: [{ is: { body: 'Hello World!' } }]32 }]33};34mb.create(imposter).then(function (imposter) {35 console.log('Imposter created at: ' + imposter.url);36});37var mb = require('mountebank');38var imposter = {39 stubs: [{40 responses: [{ is: { body: 'Hello World!' } }]41 }]42};43mb.create(imposter).then(function (imposter) {44 console.log('Imposter created at: ' + imposter.url);45});46var mb = require('mountebank');47var imposter = {
Using AI Code Generation
1var mb = require('mountebank');2mb.create({port:2525, pidfile: 'mb.pid', logfile: 'mb.log', protofile: 'mb.proto', ipWhitelist: ['*']}, function (error, server) {3 server.post('/imposters', {protocol: 'http', port: 3000, stubs: [{responses: [{is: {statusCode: 200, body: 'Hello World!'}}]}]}, function (error, response) {4 console.log('Server started on port 3000');5 });6});7server.delete('/imposters', 3000, function (error, response) {8 console.log('Server stopped on port 3000');9});
Using AI Code Generation
1const mb = require('mountebank');2const port = 2525;3const protocol = 'http';4const host = 'localhost';5 {6 {7 {8 is: {9 }10 }11 }12 }13];14mb.start({ port: port, pidfile: 'pidfile', logfile: 'logfile', ipWhitelist: ['*'] }, () => {15 mb.post('/imposters', imposters, () => {16 console.log('Imposter created');17 });18});19const mb = require('mountebank');20const port = 2525;21const protocol = 'http';22const host = 'localhost';23 {24 {25 {26 is: {27 }28 }29 }30 }31];32mb.start({ port: port, pidfile: 'pidfile', logfile: 'logfile', ipWhitelist: ['*'] }, () => {33 mb.post('/imposters', imposters, () => {34 console.log('Imposter created');35 });36});37const mb = require('mountebank');38const port = 2525;39const protocol = 'http';40const host = 'localhost';41 {42 {43 {44 is: {45 }46 }47 }48 }49];50mb.start({ port: port, pidfile: 'pidfile', logfile: 'logfile', ipWhitelist: ['*'] }, () => {51 mb.post('/imposters', imposters, () => {52 console.log('Imposter created');53 });54});
Using AI Code Generation
1var mb = require('mountebank');2var fs = require('fs');3var imposter = JSON.parse(fs.readFileSync('imposter.json', 'utf8'));4var port = 2525;5var protocol = 'http';6var options = { allowInjection: true };7mb.create(url, options, function (error, api) {8 api.createImposter(imposter, function (error, result) {9 console.log(JSON.stringify(result));10 });11});12{13 {14 {15 "is": {16 }17 }18 }19}20function (request, state, logger) {21 var response = {22 headers: {23 },24 body: JSON.stringify({25 })26 };27 return response;28}29function (request, state, logger) {30 var response = {31 headers: {32 },33 body: JSON.stringify({34 })35 };36 return response;37}38{39 {40 {41 "is": {42 }43 }44 }45 {46 }47}48{49 {50 {51 "is": {52 }53 }54 }55 {56 }57}
Using AI Code Generation
1var decorate = require("mountebank").decorate;2var response = {3 headers: {4 },5 body: {6 }7};8decorate(function (request, response) {9 response.statusCode = 200;10 response.headers = {11 };12 response.body = {13 };14});15var decorate = require("mountebank").decorate;16var response = {17 headers: {18 },19 body: {20 }21};22decorate(function (request, response) {23 response.statusCode = 200;24 response.headers = {25 };26 response.body = {27 };28});29var decorate = require("mountebank").decorate;30var response = {31 headers: {32 },33 body: {34 }35};36decorate(function (request, response) {37 response.statusCode = 200;38 response.headers = {39 };40 response.body = {41 };42});43var decorate = require("mountebank").decorate;44var response = {45 headers: {46 },47 body: {48 }49};50decorate(function (request, response) {51 response.statusCode = 200;52 response.headers = {
Using AI Code Generation
1const mb = require('mountebank');2const mbHelper = require('mountebank-helper');3const mbHelperObj = new mbHelper();4const port = 2525;5const protocol = 'http';6const host = 'localhost';7const imposterPort = 4545;8const imposterProtocol = 'http';9const imposterHost = 'localhost';10const imposterName = 'testImposter';11const endpoint = '/testEndpoint';12const stub = {13 {14 is: {15 headers: {16 },17 }18 }19};20const imposter = {21};22const options = {23 headers: {24 }25};26const decorateOptions = {27 path: `/imposters/${imposterPort}/stubs/${endpoint}`,28 headers: {29 }30};31const decorateBody = {32 {33 is: {34 headers: {35 },36 },37 _behaviors: {38 }39 }40};41const decorateBody2 = {42 {43 is: {44 headers: {45 },46 },47 _behaviors: {48 }49 }50};51const decorateBody3 = {52 {53 is: {54 headers: {55 },56 },57 _behaviors: {58 }59 }60};61const decorateBody4 = {
Using AI Code Generation
1var imposter = require('mountebank').createImposter(2525, 'http');2var request = require('request');3imposter.addStub({4 {5 is: {6 },7 _behaviors: {8 decorate: {9 {10 matches: {11 },12 generates: {13 }14 }15 function: function (request, state, logger) {16 var externalRequest = {17 };18 request(externalRequest, function (error, response, body) {19 if (error) {20 logger.error('Error calling external service: ' + error);21 } else {22 request.body = body;23 request.statusCode = response.statusCode;24 }25 });26 }27 }28 }29 }30});31imposter.start();32var express = require('express');33var app = express();34app.get('/api/external', function (req, res) {35 res.send('External Service!');36});37app.listen(3000);38{39 {40 "is": {41 },42 "_behaviors": {43 "decorate": {44 {45 "matches": {46 },47 "generates": {
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!