def personal_gberg(self, charList, gPath): full_text = "" while full_text == "": try: full_text = get_zip(gPath) except: full_text = "" gPath = rc(gPaths.values()) endPart = full_text.split("*** START OF THIS PROJECT GUTENBERG EBOOK ")[-1] theMeat = endPart.split("*** END OF THIS PROJECT GUTENBERG EBOOK")[0] theMeat = string.replace(theMeat, "\r\n", " ") if len(theMeat) < DEN+5: text = theMeat else: startLoc = int(len(theMeat)/2.0 - DEN/2.0) text = theMeat[startLoc:startLoc+DEN] spLoc = text.find(" ") text = text[spLoc+1:] try: pos = en.sentence.tag(text) wordtag = map(list, zip(*pos)) words = wordtag[0] tags = wordtag[1] for i in range(len(words)): charRef = rc([rc(charList), charList[0]]) if tags[i] == "PRP": words[i] = charRef.firstName elif tags[i] == "PRP$": words[i] = charRef.firstName+"\'s" elif tags[i] in ["VBD", "VBG", "VBN", "VBZ"]: try: words[i] = en.verb.past(words[i], person=3, negate=False) except: pass else: pass punc = [".", ",", ";", ":", "!", "?"] for i in range(len(words)): if words[i] in punc: words[i] = '\b'+words[i] final_text = " ".join(words) except: final_text = "" return final_text
def makeManyFiles(self, nfiles=200, nsamples=100000): import tempfile import random from random import choice as rc abc = 'abcdefghijklmnopqrstuvwxyz' def rn(n): return ''.join([random.choice(abc) for i in xrange(n)]) stations = [rn(4) for i in xrange(10)] components = [rn(3) for i in xrange(3)] networks = ['xx'] datadir = tempfile.mkdtemp() for i in xrange(nfiles): tbeg = 1234567890 + i * 60 * 60 * 24 * 10 # random.randint(1,int(time.time())) srate = 1.0 tend = tbeg + (1.0 / srate) * (nsamples - 1) data = num.ones(nsamples) trtup = (rc(networks), rc(stations), '', rc(components), int(tbeg * HPTMODULUS), int(tend * HPTMODULUS), srate, data) fn = pjoin(datadir, '%s_%s_%s_%s_%s.mseed' % (trtup[:4] + (rn(5), ))) store_traces([trtup], fn) return datadir
def set_symptoms_in_session(intent, session): card_title = intent['name'] sesh_attribs = session['attributes'] if 'Symptom' in intent['slots']: symptom = intent['slots']['Symptom']['value'] if symptom in ["that's it", "no", "nope", "nothing else", "nah"]: diagnosis_string = get_diagnosis(sesh_attribs['symptoms'], sesh_attribs['age'], sesh_attribs['sex']) return build_response(sesh_attribs, build_speechlet_response("Session Ended", diagnosis_string, None, True)) # TODO do more things after here after merely telling diagnosis elif symptom in ['right']: speech_output = "Your symptoms are " + ', '.join(sesh_attribs['symptoms']) + ". Anything else?" reprompt_text = "Any other symptoms I should know about?" return build_response(sesh_attribs, build_speechlet_response(card_title, speech_output, reprompt_text, False)) elif symptom in ['wrong']: sesh_attribs = pop_symptom(session) speech_output = ' '.join([rc(APOLOGY_1), rc(APOLOGY_2), rc(APOLOGY_3)]) reprompt_text = "Any other symptoms I should know about?" return build_response(sesh_attribs, build_speechlet_response(card_title, speech_output, reprompt_text, False)) else: sesh_attribs = add_symptom(symptom, session) speech_output = "Is " + symptom + " right or wrong?" reprompt_text = speech_output return build_response(sesh_attribs, build_speechlet_response(card_title, speech_output, reprompt_text, False)) else: speech_output = "I'm not sure what you mean by " + symptom + "." reprompt_text = speech_output return build_response(sesh_attribs, build_speechlet_response(card_title, speech_output, reprompt_text, False))
def genElements(recurseCount=0): global usedIds, usedClasses, usedElements BADLEN = 20 usedElements += [rc(elements) for j in range(BADLEN)] divString = b"\n" closer = b"\n" if recurseCount: BADLEN = int(BADLEN / 2) for j in range(BADLEN): selfCloser = (ri(0, 10) >= 7) tagName = rc(selfclosers) if selfCloser else rc(elements) if tagName not in usedElements: usedElements.append(tagName) tagName = tagName.encode("UTF-8") clsId = ri(1, 2) divString += b"<%s %s=\"%s\">%s</%s>" % ( tagName, b"class" if clsId == 1 else b"id", rc(usedClasses).encode( "UTF-8") if clsId == 1 else rc(usedIds).encode("UTF-8"), genElements(recurseCount=recurseCount + 1) if ri(1, 10) == 3 and recurseCount <= 2 else genContent(), tagName) if not selfCloser: closer = b"</%s>\n" % tagName + closer if ri(1, 2) == 1 else b"" divString += closer + b"\n" return divString
def replacementDict(tc, dc, cc, tr): MAX_PREDICATES = 3 repl = {} for i in range(len(tc)): repl["tag_%i" % i] = tc[i] repl["tag_%i_aan" % i] = a_or_an(tc[i]) if dc[i]: if len(dc[i].keys()) < MAX_PREDICATES: relVerbs = dc[i].keys() lemmas = [rc(dc[i][relVerb]) for relVerb in relVerbs] for j in range(MAX_PREDICATES - len(relVerbs)): useAgain = rc(dc[i].keys()) relVerbs.append(useAgain) lemmas.append(rc(dc[i][useAgain])) else: relVerbs = rs(dc[i].keys(), MAX_PREDICATES) lemmas = [rc(dc[i][relVerb]) for relVerb in relVerbs] zipped = zip(relVerbs, lemmas) for j in range(MAX_PREDICATES): repl["tag_%i_predicate_%i" % (i, j)] = " ".join(zipped[j]) dump = [] for rv in dc[i].keys(): for lemma in dc[i][rv]: dump.append("%s it %s %s." % (rc(tr), rv, lemma)) random.shuffle(dump) repl["tag_%i_dump" % i] = dump else: for j in range(MAX_PREDICATES): repl["tag_%i_predicate_%i" % (i, j)] = "remains unknown" repl["tag_%i_dump" % i] = [] return repl
def makeManyFiles(self, nfiles=200, nsamples=100000): import tempfile import random from random import choice as rc abc = 'abcdefghijklmnopqrstuvwxyz' def rn(n): return ''.join( [ random.choice(abc) for i in xrange(n) ] ) stations = [ rn(4) for i in xrange(10) ] components = [ rn(3) for i in xrange(3) ] networks = [ 'xx' ] datadir = tempfile.mkdtemp() for i in xrange(nfiles): tbeg = 1234567890+i*60*60*24*10 # random.randint(1,int(time.time())) srate = 1.0 tend = tbeg + (1.0/srate)*(nsamples-1) data = num.ones(nsamples) trtup = (rc(networks),rc(stations),'',rc(components), int(tbeg*HPTMODULUS), int(tend*HPTMODULUS), srate, data) fn = pjoin( datadir, '%s_%s_%s_%s_%s.mseed' % (trtup[:4]+(rn(5),))) store_traces([trtup], fn) return datadir
def title_maker(self): charTitle = ri(0, 2) if not bool(charTitle): ttl = self.charObj.firstName + " " + self.charObj.lastName else: titleSource = ri(0, 3) if titleSource == 0: textSource = rc(self.charObj.scenes) elif titleSource == 1: textSource = rc(self.charObj.drugTrips) elif titleSource == 2: textSource = rc(self.charObj.scpReports) elif titleSource == 3: textSource = rc(self.charObj.gbergExcerpts) tokens = nltk.word_tokenize(textSource) if len(tokens) > 20: index = ri(0, len(tokens)-10) titleLen = ri(2, 6) ttl = ' '.join(tokens[index:index+titleLen]) else: ttl = self.charObj.firstName + " " + self.charObj.lastName self.title = ttl
def replacementDict(tc, dc, cc, tr): MAX_PREDICATES = 3 repl = {} for i in range(len(tc)): repl["tag_%i"%i] = tc[i] repl["tag_%i_aan"%i] = a_or_an(tc[i]) if dc[i]: if len(dc[i].keys()) < MAX_PREDICATES: relVerbs = dc[i].keys() lemmas = [rc(dc[i][relVerb]) for relVerb in relVerbs] for j in range(MAX_PREDICATES - len(relVerbs)): useAgain = rc(dc[i].keys()) relVerbs.append(useAgain) lemmas.append(rc(dc[i][useAgain])) else: relVerbs = rs(dc[i].keys(), MAX_PREDICATES) lemmas = [rc(dc[i][relVerb]) for relVerb in relVerbs] zipped = zip(relVerbs, lemmas) for j in range(MAX_PREDICATES): repl["tag_%i_predicate_%i"%(i,j)] = " ".join(zipped[j]) dump = [] for rv in dc[i].keys(): for lemma in dc[i][rv]: dump.append("%s it %s %s." % (rc(tr), rv, lemma)) random.shuffle(dump) repl["tag_%i_dump"%i] = dump else: for j in range(MAX_PREDICATES): repl["tag_%i_predicate_%i"%(i,j)] = "remains unknown" repl["tag_%i_dump"%i] = [] return repl
def genSelector(recurseCount=0): global usedElements, usedClasses selStr = "" j = ri(1, 5) if j == 1: selStr += "#" + rc(usedIds) elif j >= 2 and j < 4: selStr += rc(usedElements) else: selStr += "." + rc(usedClasses) if ri(1, 4) == 1: selStr += rc(combinators) j = ri(1, 5) if j == 1: selStr += "#" + rc(usedIds) elif j == 2: selStr += rc(usedElements) else: selStr += "." + rc(usedClasses) if ri(1, 5) == 1: selStr += rc(numericPseudo) + "(" + str(ri(1, 5)) + ")" if ri(1, 5) == 1 and recurseCount <= 10: selStr += rc(complexPseudo) + "(" + genSelector( recurseCount=recurseCount + 1) + ")" return selStr
def personal_trip(self, charList, tripPath): fileText = get_file(tripPath) splitText = fileText.split('\\vspace{2mm}') endOfText = splitText[-1] text = endOfText[:len(endOfText)-15] try: pos = en.sentence.tag(text) wordtag = map(list, zip(*pos)) words = wordtag[0] tags = wordtag[1] for i in range(len(words)): charRef = rc([rc(charList), charList[0]]) if tags[i] == "PRP": words[i] = charRef.firstName elif tags[i] == "PRP$": words[i] = charRef.firstName+"\'s" elif tags[i] in ["VBD", "VBG", "VBN", "VBZ"]: try: words[i] = en.verb.past(words[i], person=3, negate=False) except: pass else: pass punc = [".", ",", ";", ":", "!", "?"] for i in range(len(words)): if words[i] in punc: words[i] = '\b'+words[i] final_text = " ".join(words) final_text = string.replace(final_text, "\\end{itemize}", "") final_text = string.replace(final_text, "\\begin{itemize}", "") final_text = string.replace(final_text, "\\end{center}", "") final_text = string.replace(final_text, "\\begin{center}", "") final_text = string.replace(final_text, "\\ldots", " . . . ") final_text = string.replace(final_text, "\\egroup", "") final_text = string.replace(final_text, "EROWID", "GOVERNMENT") final_text = string.replace(final_text, "erowid", "government") final_text = string.replace(final_text, "Erowid", "Government") except: final_text = "" return final_text
def result(): playerTotal = 0 computerTotal = 0 if request.method == 'POST': player = request.form.getlist('player[]') computer = request.form.getlist('computer[]') player.append(rc(cards)) computer.append(rc(cards)) playerTotal = getTotalCardValue(player) computerTotal = getTotalCardValue(computer) data = {"player": playerTotal, "computer": computerTotal} return render_template("second.html", data=json.dumps(data))
def generate(numWords, seed=rc(nGramDict.keys())): if len(seed) != 2: raise Exception("Exactly 2 seed tokens required!") w1, w2 = seed result = list(seed) for _ in range(numWords): try: w3 = rc( nGramDict[(w1, w2)] ) except IndexError: raise Exception("Seed tokens not present in corpus!") result.append(w3) w1, w2 = w2, w3 # Why do we need to do it this way? return result
def makeManyFiles( nfiles, nsamples, networks, stations, channels, tmin): datadir = tempfile.mkdtemp() traces = [] deltat=1.0 for i in xrange(nfiles): ctmin = tmin+i*nsamples*deltat # random.randint(1,int(time.time())) data = num.ones(nsamples) traces.append(trace.Trace(rc(networks), rc(stations),'',rc(channels), ctmin, None, deltat, data)) fnt = pjoin( datadir, '%(network)s-%(station)s-%(location)s-%(channel)s-%(tmin)s.mseed') io.save(traces, fnt, format='mseed') return datadir
def urlGen(): digLet = s.ascii_letters + s.digits tinyURL = '' for i in range(6): char = rc(digLet) tinyURL += char return tinyURL
def BatchStringGenerator(n, a=8, b=12): r = [] if a == b: b = b + 1 elif a > b: sys.exit('Incorrect min and max string lengths. Try again.') return [r.append(RandomStringGenerator(rc(range(a, b)))) for i in range(n)]
def __init__(self, ID=rc(["Giant Goomba"]), x=None, y=None) : self.ID = ID self.life = 3 self.coords = (Coords(x=x, y=y) if x!=None and y!=None else Coords()) if self.ID == "Bowser" : pass elif self.ID == "Giant Goomba" : # I didn't really want this boss, but animation takes forever, and this allows me to reuse the Goomba animation. myMultiplier = 4 # This was just to help me get a better size for the Giant Goomba: It doesn't change, so you don't really need it. self.shapes = [ # stem/body makeOval(self.coords.x, self.coords.y+uh(2)*squish*myMultiplier, uh(8)*myMultiplier, uh(7)*squish*myMultiplier, fill="#ec8"), # top makeRPolygon(self.coords.x, self.coords.y-uh(8)*squish*myMultiplier, uh(8)*myMultiplier, uh(-4)*squish*myMultiplier, uh(11)*myMultiplier, uh(2)*squish*myMultiplier, uh(8)*myMultiplier, uh(8)*squish*myMultiplier, fill="#840"), makeOval(self.coords.x, self.coords.y-uh(10)*squish*myMultiplier, uh(16)*myMultiplier, uh(17)*squish*myMultiplier, fill="#840"), makeOval(self.coords.x-uh(8)*myMultiplier, self.coords.y-uh(4)*squish*myMultiplier, uh(7)*myMultiplier, uh(7)*squish*myMultiplier, fill="#840"), makeOval(self.coords.x+uh(8)*myMultiplier, self.coords.y-uh(4)*squish*myMultiplier, uh(7)*myMultiplier, uh(7)*squish*myMultiplier, fill="#840"), # eyes makeOvalArc(self.coords.x+uh(4)*myMultiplier, self.coords.y-uh(10)*squish*myMultiplier, uh(5)*myMultiplier, uh(7)*squish*myMultiplier, fill="#fff", start=190, extent=250, style="chord"), makeOval(self.coords.x+uh(4)*myMultiplier, self.coords.y-uh(10)*squish*myMultiplier, uh(2.5)*myMultiplier, uh(4)*squish*myMultiplier, fill="#000"), makeOvalArc(self.coords.x-uh(4)*myMultiplier, self.coords.y-uh(10)*squish*myMultiplier, uh(5)*myMultiplier, uh(7)*squish*myMultiplier, fill="#fff", start=100, extent=250, style="chord"), makeOval(self.coords.x-uh(4)*myMultiplier, self.coords.y-uh(10)*squish*myMultiplier, uh(2.5)*myMultiplier, uh(4)*squish*myMultiplier, fill="#000"), # mouth makeRectangle(self.coords.x, self.coords.y-uh(3)*squish*myMultiplier, uh(10)*myMultiplier, uh(1)*squish*myMultiplier, fill="#000"), # feet makeOval(self.coords.x+uh(5)*myMultiplier, self.coords.y+uh(5.25)*squish*myMultiplier, uh(6)*myMultiplier, uh(4)*squish*myMultiplier, fill="#421"), makeOval(self.coords.x-uh(5)*myMultiplier, self.coords.y+uh(5.25)*squish*myMultiplier, uh(6)*myMultiplier, uh(4)*squish*myMultiplier, fill="#421") ] self.talk(1) self.AI()
def __init__(self, ID=rc(["grow"]), x=None, y=None) : self.instances.append(self) self.ID = ID self.coords = (Coords(x=x, y=y) if x!=None and y!=None else Coords()) if self.ID == "grow" : self.shapes = [ # top makeOval(self.coords.x, self.coords.y-uh(2), uh(18), uh(14), fill="#f00"), makeCircle(self.coords.x, self.coords.y-uh(4.5), uh(3.5), fill="#fff"), makeOval(self.coords.x-uh(8), self.coords.y-uh(2), uh(2), uh(5), fill="#fff"), makeOval(self.coords.x+uh(8), self.coords.y-uh(2), uh(2), uh(5), fill="#fff"), # stem makeOval(self.coords.x, self.coords.y+uh(4), uh(10), uh(7), fill="#fc8"), # eyes makeOval(self.coords.x-uh(1.5), self.coords.y+uh(3), uh(1), uh(3), fill="#000"), makeOval(self.coords.x+uh(1.5), self.coords.y+uh(3), uh(1), uh(3), fill="#000") ] elif self.ID == "1Up" : self.shapes = [ # top makeOval(self.coords.x, self.coords.y-uh(2), uh(18), uh(14), fill="#0d0"), makeCircle(self.coords.x, self.coords.y-uh(4.5), uh(3.5), fill="#fff"), makeOval(self.coords.x-uh(8), self.coords.y-uh(2), uh(2), uh(5), fill="#fff"), makeOval(self.coords.x+uh(8), self.coords.y-uh(2), uh(2), uh(5), fill="#fff"), # stem makeOval(self.coords.x, self.coords.y+uh(4), uh(10), uh(7), fill="#fc8"), # eyes makeOval(self.coords.x-uh(1.5), self.coords.y+uh(3), uh(1), uh(3), fill="#000"), makeOval(self.coords.x+uh(1.5), self.coords.y+uh(3), uh(1), uh(3), fill="#000") ] self.touch()
def generate(model, length, seed=False): if not seed: seed = rc(model.keys()) elif not seed in model: raise Exception("Seed not in model!") result = list(seed) for _ in range(length): next_token = rc(model[seed]) result.append(next_token) prior_tokens = list(seed)[1:] prior_tokens.append(next_token) seed = tuple(prior_tokens) return ' '.join(result)
def testWriteRead(self): now = time.time() n = 10 deltat = 0.1 networks = [ rn(2) for i in range(5) ] traces1 = [ trace.Trace(rc(networks), rn(4), rn(2), rn(3), tmin=now+i*deltat*n*2, deltat=deltat, ydata=num.arange(n, dtype=num.int32), mtime=now) for i in range(3) ] tempdir = tempfile.mkdtemp() for format in ('mseed', 'sac', 'yaff'): fns = io.save(traces1, pjoin(tempdir, '%(network)s_%(station)s_%(location)s_%(channel)s'), format=format) for fn in fns: assert io.detect_format(fn) == format traces2 = [] for fn in fns: traces2.extend(io.load(fn, format='detect')) for tr in traces1: assert tr in traces2, 'failed for format %s' % format for fn in fns: os.remove(fn) shutil.rmtree(tempdir)
def randoccupation(dic): tmp = dic.copy() tmp.pop("Total") # Remove Total and 99.8 from the temporary dictionary. keys = list(tmp.keys()) values = [value[0] for value in tmp.values()] # Associates occupations to corresponding percentages. return rc(keys, values)[0] # Return an occupation based on the percentages.
def int_test(): k = 16180 b = BloomFilter() for i in xrange(k): s = int("".join([rc(digits) for j in xrange(64)])) b.store(s) assert s in b
def basic_test(): k = 16180 b = BloomFilter() for i in xrange(k): s = "".join([rc(ascii) for j in xrange(64)]) b.store(s) assert s in b
def extract_yes(self): return { 'curid': self.place.article_data['pageid'], 'extract': "{} : {}………".format( rc(self.babble['extract_yes']), self.place.article_data['extract'][:200], ) }
def genPart(): # j = ri(1,15) # if j == 6: # return genSelector() + """ # {animation-duration:.00001ms;animation-name:XYXX;animation-iteration-count: infinite;} # @keyframes XYXX { from { %s } to { %s } } # """ % (rc(rules),rc(rules)) # else: return genSelector() + "{" + rc(rules) + "}"
def address_yes(self): return { 'map_img_src': self.place.get_map_src(), 'map_link': APP['MAP_LINK'].format(**self.place.geo_data['location']), 'address': "{} : {}".format( rc(self.babble['address_yes']), self.place.geo_data['formatted_address'], ), }
def eulerian_path(adj_grph): all_edges = count_all_edges(adj_grph) start_node = rc(list(adj_grph.keys())) cycle, nodes_unused = random_walk(start_node, adj_grph, already_walked=None, nodes_unused=None) while set(cycle) != all_edges: new_start = rc(list(nodes_unused)) nodes_unused.remove(new_start) cycle = walk_previous_cycle(new_start, cycle) cycle, nodes_unused = random_walk( start_node=new_start, adj_grph=adj_grph, already_walked=cycle, nodes_unused=nodes_unused, ) return cycle
def makeManyFiles(nfiles, nsamples, networks, stations, channels, tmin): datadir = tempfile.mkdtemp() traces = [] deltat = 1.0 for i in xrange(nfiles): ctmin = tmin + i * nsamples * deltat # random.randint(1,int(time.time())) data = num.ones(nsamples) traces.append( trace.Trace(rc(networks), rc(stations), '', rc(channels), ctmin, None, deltat, data)) fnt = pjoin( datadir, '%(network)s-%(station)s-%(location)s-%(channel)s-%(tmin)s.mseed') io.save(traces, fnt, format='mseed') return datadir
def generate(id, secret, username, password): reddit = praw.Reddit(client_id=id, client_secret=secret, username=username, password=password, user_agent="script by u/uwu-izzy") subreddit = reddit.subreddit("Animemes") hot = subreddit.new(limit=25) post = rc([(post.title, post.url) for post in hot]) return post
def createPaths(): for layer in range(len(pathMatrix)): for index in range(size): for item in range(size): cell = pathMatrix[layer][index][item] if cell == "O": change = str(rc(pathTypeCells)) pathMatrix[layer][index][item] = change else: pass
def read_input(n): for _ in range(n): path = 'nonexistent' while not os.path.exists(path): auth = rc(all_authors) n = ri(1, all_paintings[all_authors.index(auth)]) path = images_dir + auth + '/' + auth+'_'+str(n)+'.jpg' print('Current Author: %s\tNumber: %i' %(auth, n), file=sys.stderr) #For debugging image = plt.imread(path) new_image = resize(image, (512, 512), anti_aliasing=True) new_image = new_image/256 yield new_image.flatten()
def long_sentence(): opt_adj1 = "" if randint(0, 9) < 5 else rc(adjs) opt_adj2 = "" if randint(0, 9) < 5 else rc(adjs) opt_adv1 = "" if randint(0, 9) < 5 else rc(advs) return ( "%s My %s %s %s %s your %s %s" % (last, opt_adj1, rc(nouns), opt_adv1, rc(verbs), opt_adj2, rc(nouns)))
def __init__(self,p,v,a,rgb=None,exp=False,numch=25): self.pos = Vector(*p) self.vel = Vector(*v) self.acc = Vector(*a) self.color = rgb if rgb is not None else (ri(0,255), ri(0,255), ri(0,255)) self.exploded = exp if int(numch) > 0: self.children = [] for i in range(numch): # New Particles get radial velocity, and some drag (neg radial acc) vfire = mdVector(rc([5,7,9]), ri(0,359), True) self.children.append(Particle(self.pos, vfire, G, rgb=self.color, exp=False, numch=0)) return None
def get_gif(wordlist): endpt = "http://api.giphy.com/v1/gifs/search" payload = { 'q': wordlist, 'api_key': "dc6zaTOxFJmzC" } r = requests.get(endpt, params=payload) try: gifs_data = r.json()['data'] gif_choice = rc(gifs_data) return gif_choice['images']['fixed_height']['url'] except: return "Something went wrong... I'm sorry."
def testWriteText(self): networks = [rn(2) for i in range(5)] deltat = 0.1 tr = trace.Trace( rc(networks), rn(4), rn(2), rn(3), tmin=time.time()+deltat, deltat=deltat, ydata=num.arange(100, dtype=num.int32), mtime=time.time()) io.save( tr, pjoin( self.tmpdir, '%(network)s_%(station)s_%(location)s_%(channel)s'), format='text')
def get_lnk(query,sort = 'random'): url = "https://www.shitpostbot.com/gallery/sourceimages?review_state=accepted&query=" + query +"&order=total_rating&direction=DESC" response = urllib.request.urlopen(url) soup = bs(response,'lxml') result = [] for div in soup.findAll('div', attrs={'class':'img'}): result.append(div.find('a')['href']) if len(result) == 0: raise Exception('Sorry, couldn\'t find anything :(') else: if sort == 'random': fin = rc(result) elif sort == 'top': fin = result[0] return 'https://www.shitpostbot.com' + fin
def testWriteText(self): networks = [rn(2) for i in range(5)] deltat = 0.1 tr = trace.Trace(rc(networks), rn(4), rn(2), rn(3), tmin=time.time() + deltat, deltat=deltat, ydata=num.arange(100, dtype=num.int32), mtime=time.time()) io.save(tr, pjoin(self.tmpdir, '%(network)s_%(station)s_%(location)s_%(channel)s'), format='text')
def get_location_str(self): i = 0 key_set = ['lat', 'lon', 'alt', 'speed'] fancy_str = None for new_data in self.gps_socket: if new_data: i += 1 try: json_data = json.loads(new_data) except: json_data = {} if not set(key_set) - set(json_data.keys()): lat, lng, alt_meters, speed_kph = map(lambda x: json_data[x], key_set) speed_mph = 0.621371 * speed_kph alt_feet = 3.28084 * alt_meters # return "", lat, lng, speed_mph, alt_feet # break try: response = self.client.venues.search(params={'ll': ','.join(map(str, [lat, lng]))}) except: response = {} fancy_str = None if 'venues' in response: venues = response['venues'] if venues: v = rc(venues) loc_obj = v['location'] cats = v['categories'] if cats and 'city' in loc_obj: c = cats[0] fancy_str = v['name'] + ': ' 'a ' + c['name'].lower() + ' in ' + loc_obj['city'] return fancy_str, lat, lng, speed_mph, alt_feet # if fancy_str: # return fancy_str, lat, lng, alt_feet, speed_mph elif i > 9: try: return "", lat, lng, alt_feet, speed_mph except: return "(?)", 0, 0, 0, 0
def _k(a): k = be(a) d = { b'746D6462': ('GE4DIMLFMVRGCOLCMEZDMMZTG5TGEZBUGJSDANRQME3DONBRMZRQ====', 'MY3GEZBWHA3WMZTBGYZWGZBSHAZGENTGMYZGGNRYG43WMMRWGY4Q===='), b'796F7574756265': ('IFEXUYKTPFBU65JVJNUGCUZZK5RVIZSOOZXFES32PJFE2ZRWPIWTMTSHMIZDQTI=', ), b'7472616B74': ('GZQWMNZQGU3WMYLBMNSTANRQGJQWENDEMI4TKZDGHBSDINDDMVSTIMBVMZSWCM3GGE4GCZRWMU3DQOJWGAYDGYRVME4DGOBTMQZDQYQ=', ) } return bd(rc(d[k])).decode('ascii') # looooooooooooooooool
def _k(a): k = a.encode('hex') d = { '746d6462': [ u'GE4DIMLFMVRGCOLCMEZDMMZTG5TGEZBUGJSDANRQME3DONBRMZRQ====', u'MY3WMNJRG43TKOBXG5STAYTCGY3TAMZVGIYDSNJSMIZWGNZYGQYA====', u'MEZWIYZRGEYWKNRWGEYDKZRWGM4DOZJZHEZTSMZYGEZWCZJUMQ2Q====', u'MY3GEZBWHA3WMZTBGYZWGZBSHAZGENTGMYZGGNRYG43WMMRWGY4Q====' ], '796f7574756265': [ u'IFEXUYKTPFBU65JVJNUGCUZZK5RVIZSOOZXFES32PJFE2ZRWPIWTMTSHMIZDQTI=' ] } return bd(rc((d[k])))
def __init__(self, conn_uri=None): self.conn_uri = conn_uri if conn_uri else 'http://localhost:6800/jsonrpc' self.r_rpcver = '2.0' self.r_id = ''.join([rc([x for x in sl + sg]) for x in xrange(1,8)]) self.known_commands = [ 'addUri', 'addTorrent', 'addMetalink', 'remove', 'forceRemove', 'pause', 'pauseAll', 'forcePause', 'forcePauseAll', 'unpause', 'unpauseAll', 'tellStatus', 'getUris', 'getFiles', 'getPeers', 'getServers', 'tellActive', 'tellWaiting', 'tellStopped', 'changePosition', 'changeUri', 'getOption', 'changeOption', 'getGlobalOption', 'changeGlobalOption', 'getGlobalStat', 'purgeDownloadResult', 'removeDownloadResult', 'getVersion', 'getSessionInfo', 'shutdown', 'forceShutdown' ]
def generate(grammar, axiom): """Generate a list of tokens from grammar, starting with axiom. The grammar should take the form of a dictionary, mapping rules (strings) to lists of expansions for those rules. Expansions will be split on whitespace. Any token in the expansion that doesn't name a rule in the grammar will be included in the expansion as-is.""" s = list() if grammar[axiom]: # Termination condition for defaultdict(list) expansion = rc(grammar[axiom]) for token in expansion.split(): if token in ['.', ',', ':']: s.append(token) else: s.extend(generate(grammar, token)) # RECURSION! else: s.append(axiom) return s
def getCards(): try: cards = list(range(1, 52)) playerHand = [] computerHand = [] imageName = [] data = {} # if (request.form.playerCoin): # playerCoin=int(request.form.playerCoin)-10 # else: # playerCoin=90 msg = "No Message" #Player Hand playerHand.append(rc(cards)) cards.remove(playerHand[0]) imageName.append(getImageName(playerHand[0])) playerHand.append(rc(cards)) cards.remove(playerHand[1]) imageName.append(getImageName(playerHand[1])) playerTotal = getTotalCardValue(playerHand) #If players total is less than 21 then select computer cards if playerTotal < 21: #Computer Hand computerHand.append(rc(cards)) cards.remove(computerHand[0]) imageName.append(getImageName(computerHand[0])) computerHand.append(rc(cards)) cards.remove(computerHand[1]) imageName.append(getImageName(computerHand[1])) computerTotal = getTotalCardValue(computerHand) if computerTotal > 21: #If computers total is greater than 21 select cards again cards.append(computerHand[0]) cards.append(computerHand[1]) computerHand[0] = rc(cards) cards.remove(computerHand[0]) computerHand[1] = rc(cards) msg = "Hit?" elif playerTotal == 21: msg = "You won" elif playerTotal > 21: msg = "Computer Won" data = { "player": playerHand, "computer": computerHand, "imageName": imageName, "msg": msg } except ImportError: print("error :", sys.exc_info()[0]) return jsonify(data)
def personal_scp(self, charList, scpPath): text = get_file(scpPath) text = string.replace(text, "SCP", charList[0].lastName) text = string.replace(text, "Foundation", charList[0].lastName) try: pos = en.sentence.tag(text) wordtag = map(list, zip(*pos)) words = wordtag[0] tags = wordtag[1] for i in range(len(words)): charRef = rc(charList) if tags[i] == "PRP": words[i] = charRef.firstName elif tags[i] == "PRP$": words[i] = charRef.firstName+"\'s" elif tags[i] in ["VBD", "VBG", "VBN", "VBZ"]: try: words[i] = en.verb.past(words[i], person=3, negate=False) except: pass else: pass punc = [".", ",", ";", ":", "!", "?"] for i in range(len(words)): if words[i] in punc: words[i] = '\b'+words[i] final_text = " ".join(words) except: final_text = "" return final_text
def testWriteRead(self): now = time.time() n = 10 deltat = 0.1 networks = [ rn(2) for i in range(5) ] traces1 = [ trace.Trace(rc(networks), rn(4), rn(2), rn(3), tmin=now+i*deltat*n*2, deltat=deltat, ydata=num.arange(n, dtype=num.int32), mtime=now) for i in range(100) ] tempdir = tempfile.mkdtemp() fns = mseed.save(traces1, pjoin(tempdir, '%(network)s')) traces2 = [] for fn in fns: traces2.extend(mseed.load(fn)) for tr in traces1: assert tr in traces2 for fn in fns: os.remove(fn) shutil.rmtree(tempdir)
dWin = 0 # dealer win counter pWin = 0 # player win counter chipsBalance = CHIPS_INITIAL while True: playerBusted = False dealerBusted = False totalDealer = DEFAULT_VALUE totalPlayer = DEFAULT_VALUE totalChipsHand = DEFAULT_VALUE chipsHand = DEFAULT_VALUE + 1 player = [] print "-------------------------------------------------------------------" make_bet() #Card 1 pickedCard = rc(deck) deck.remove(pickedCard) player.append(pickedCard) #Card 2 pickedCard = rc(deck) deck.remove(pickedCard) player.append(pickedCard) totalPlayer = total(player) if totalPlayer == BLACK_JACK: print "Player has a Black Jack, wins automatically!" print "Player's cards are %s" % (player) chipsBalance += BLACK_JACK_MULTIPLIER * totalChipsHand pWin += 1 else:
def pick_sentiment(c, i, s): # Sonnet if arg_dict['<poem>'] == 'sonnet': pos = i % len(c) # ADD CYCLE HERE if arg_dict['--cycle'] is not None: cyclen = int(arg_dict['--cycle']) pos = i % cyclen # Negative to positive if arg_dict['--pos']: ix = int( scale(pos, (0.0, float(cyclen-1)), (0.0, float(len(tgtLinesBySent)-1))) ) # Positive to negative elif arg_dict['--neg']: ix = int( scale(pos, (0.0, float(cyclen-1)), (float(len(tgtLinesBySent)-1), 0.0)) ) # Back and forth elif arg_dict['--neu']: if pos <= (cyclen-1)/2.0: ix = int( scale(pos, (0.0, float(cyclen-1)/2.0), (0.0, float(len(tgtLinesBySent)-1))) ) else: ix = int( scale(pos, (float(cyclen-1)/2.0, float(cyclen-1)), (float(len(tgtLinesBySent)-1), 0.0)) ) else: raise Exception("--cycle requires choice of --pos, --neg, or --neu") return tgtLinesBySent[ix] elif arg_dict['--pos']: # CHANGE ALL TO REFLECT THIS.... tgtLinesAdjust = tgtLinesBySent[-14:] return tgtLinesAdjust[pos] elif arg_dict['--neg']: tgtLinesAdjust = tgtLinesBySent[14::-1] return tgtLinesAdjust[pos] elif arg_dict['--rise']: tgtLinesAdjust = tgtLinesBySent[:14] return tgtLinesAdjust[pos] elif arg_dict['--fall']: tgtLinesAdjust = tgtLinesBySent[:-14:-1] return tgtLinesAdjust[pos] else: return c[pos] # Rising sentiment elif arg_dict['--rise']: by_sent = sorted(c, key=lambda x: sentiment(x)[0]) ix = int( scale(i, (0.0, float(s-1)), (0.0, float(len(by_sent)-1))) ) return by_sent[ix] # Falling sentiment elif arg_dict['--fall']: by_sent = sorted(c, key=lambda x: sentiment(x)[0]) ix = int( scale(i, (0.0, float(s-1)), (float(len(by_sent)-1), 0.0)) ) return by_sent[ix] # Cycling sentiment elif arg_dict['--cycle'] is not None: cyclen = int(arg_dict['--cycle']) pos = i % cyclen by_sent = sorted(c, key=lambda x: sentiment(x)[0]) # Negative to positive if arg_dict['--pos']: ix = int( scale(pos, (0.0, float(cyclen-1)), (0.0, float(len(by_sent)-1))) ) # Positive to negative elif arg_dict['--neg']: ix = int( scale(pos, (0.0, float(cyclen-1)), (float(len(by_sent)-1), 0.0)) ) # Back and forth elif arg_dict['--neu']: if pos <= (cyclen-1)/2.0: ix = int( scale(pos, (0.0, float(cyclen-1)/2.0), (0.0, float(len(by_sent)-1))) ) else: ix = int( scale(pos, (float(cyclen-1)/2.0, float(cyclen-1)), (float(len(by_sent)-1), 0.0)) ) else: raise Exception("--cycle requires choice of --pos, --neg, or --neu") return by_sent[ix] elif arg_dict['--maxlike']: r = rnd() total = sum(map(lambda x: abs(sentiment(x)[0]), c)) x = r * total for cand in c: x -= abs(sentiment(cand)[0]) if x <= 0: return cand return rc(c) else: # Purely positive, negative, or neutral if arg_dict['--pos']: return max(c, key=lambda x: sentiment(x)[0]) elif arg_dict['--neg']: return min(c, key=lambda x: sentiment(x)[0]) elif arg_dict['--neu']: by_sent = sorted(c, key=lambda x: sentiment(x)[0]) return by_sent[len(by_sent)/2] # If no options, random lines else: return rc(c)
def on_click(event): x = event.x y = event.y global id27, id28, id23_1, id23_2,id23_3,id23_4 global bet_done, in_game, stop_color, pbust, bjp, already_doubled, already_stood global A_tr, A_pi, A_co, A_ca global player, comp tp = total(player) tc = total(comp) lose = False win = False with open("bet.txt", "r") as file: bet = int(file.readline()) with open("save.txt", "r") as file: money = int(file.readline()) if not bet_done: if money >=0 : canvas.delete(id27) canvas.delete(id28) if money >= 1: if x >= 0 and x <= 80 and y >= 763 and y <= 843:#jeton1 with open("bet.txt", "r") as file: bet = int(file.readline()) bet += 1 with open("bet.txt", "w") as file: file.write(str(bet)) canvas.delete(id27) with open("save.txt", "r") as file: money = int(file.readline()) money -= 1 with open("save.txt", "w") as file: file.write(str(money)) canvas.delete(id28) if money >= 5: if x >= 81 and x <= 160 and y >= 763 and y <= 843:#jeton5 with open("bet.txt", "r") as file: bet = int(file.readline()) bet += 5 with open("bet.txt", "w") as file: file.write(str(bet)) canvas.delete(id27) with open("save.txt", "r") as file: money = int(file.readline()) money -= 5 with open("save.txt", "w") as file: file.write(str(money)) canvas.delete(id28) if money >= 25: if x >= 161 and x <= 240 and y >= 763 and y <= 843:#jeton25 with open("bet.txt", "r") as file: bet = int(file.readline()) bet += 25 with open("bet.txt", "w") as file: file.write(str(bet)) canvas.delete(id27) with open("save.txt", "r") as file: money = int(file.readline()) money -= 25 with open("save.txt", "w") as file: file.write(str(money)) canvas.delete(id28) if money >= 50: if x >= 241 and x <= 320 and y >= 763 and y <= 843:#jeton50 with open("bet.txt", "r") as file: bet = int(file.readline()) bet += 50 with open("bet.txt", "w") as file: file.write(str(bet)) canvas.delete(id27) with open("save.txt", "r") as file: money = int(file.readline()) money -= 50 with open("save.txt", "w") as file: file.write(str(money)) canvas.delete(id28) if money >= 100: if x >= 321 and x <= 400 and y >= 763 and y <= 843:#jeton100 with open("bet.txt", "r") as file: bet = int(file.readline()) bet += 100 with open("bet.txt", "w") as file: file.write(str(bet)) canvas.delete(id27) with open("save.txt", "r") as file: money = int(file.readline()) money -= 100 with open("save.txt", "w") as file: file.write(str(money)) canvas.delete(id28) if money >= 500: if x >= 401 and x <= 480 and y >= 763 and y <= 843:#jeton500 with open("bet.txt", "r") as file: bet = int(file.readline()) bet += 500 with open("bet.txt", "w") as file: file.write(str(bet)) canvas.delete(id27) with open("save.txt", "r") as file: money = int(file.readline()) money -= 500 with open("save.txt", "w") as file: file.write(str(money)) canvas.delete(id28) if money >= 1000: if x >= 0 and x <= 80 and y >= 682 and y <= 762:#jeton1000 with open("bet.txt", "r") as file: bet = int(file.readline()) bet += 1000 with open("bet.txt", "w") as file: file.write(str(bet)) canvas.delete(id27) with open("save.txt", "r") as file: money = int(file.readline()) money -= 1000 with open("save.txt", "w") as file: file.write(str(money)) canvas.delete(id28) if money >= 5000: if x >= 81 and x <= 160 and y >= 682 and y <= 762:#jeton5000 with open("bet.txt", "r") as file: bet = int(file.readline()) bet += 5000 with open("bet.txt", "w") as file: file.write(str(bet)) canvas.delete(id27) with open("save.txt", "r") as file: money = int(file.readline()) money -= 5000 with open("save.txt", "w") as file: file.write(str(money)) canvas.delete(id28) if money >= 10000: if x >= 161 and x <= 240 and y >= 682 and y <= 762:#jeton10000 with open("bet.txt", "r") as file: bet = int(file.readline()) bet += 10000 with open("bet.txt", "w") as file: file.write(str(bet)) canvas.delete(id27) with open("save.txt", "r") as file: money = int(file.readline()) money -= 10000 with open("save.txt", "w") as file: file.write(str(money)) canvas.delete(id28) if x >= 75 and x <= 145 and y >= 370 and y <= 440:#cross to delete money += bet bet=0 with open("bet.txt", "w") as file: file.write(str(bet)) canvas.delete(id27) with open("save.txt", "w") as file: file.write(str(money)) canvas.delete(id28) if not in_game: player = [] # draw 2 cards for the player to start player.append(rc(cards)) player.append(rc(cards)) # draw 2 cards for the computer to start comp = [] comp.append(rc(cards)) pbust = False # player busted flag cbust = False # computer busted flag if bet > 0: if x >= 500 and x <= 650 and y >= 390 and y <= 460: bet_done = True in_game = True canvas.delete(id29) if bet_done: print(player) print(comp) canvas.delete(id23_3, id23_4) if not stop_color: for i in range(len(player)): if player[i] == 11: card = rc([tr_A, pi_A, co_A, ca_A]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 2: card = rc([tr_2, pi_2, co_2, ca_2]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 3: card = rc([tr_3, pi_3, co_3, ca_3]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 4: card = rc([tr_4, pi_4, co_4, ca_4]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 5: card = rc([tr_5, pi_5, co_5, ca_5]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 6: card = rc([tr_6, pi_6, co_6, ca_6]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 7: card = rc([tr_7, pi_7, co_7, ca_7]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 8: card = rc([tr_8, pi_8, co_8, ca_8]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 9: card = rc([tr_9, pi_9, co_9, ca_9]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 10: card = rc([tr_10, pi_10, co_10, ca_10, tr_J, pi_J, co_J, ca_J, tr_Q, pi_Q, co_Q, ca_Q, tr_K, pi_K, co_K, ca_K]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) canvas.delete(id23_1) for i in range(len(comp)): if comp[i] == 11: card = rc([tr_A, pi_A, co_A, ca_A]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 2: card = rc([tr_2, pi_2, co_2, ca_2]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 3: card = rc([tr_3, pi_3, co_3, ca_3]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 4: card = rc([tr_4, pi_4, co_4, ca_4]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 5: card = rc([tr_5, pi_5, co_5, ca_5]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 6: card = rc([tr_6, pi_6, co_6, ca_6]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 7: card = rc([tr_7, pi_7, co_7, ca_7]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 8: card = rc([tr_8, pi_8, co_8, ca_8]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 9: card = rc([tr_9, pi_9, co_9, ca_9]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 10: card = rc([tr_10, pi_10, co_10, ca_10, tr_J, pi_J, co_J, ca_J, tr_Q, pi_Q, co_Q, ca_Q, tr_K, pi_K, co_K, ca_K]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) stop_color = True if tp == 21: win = True id31 = canvas.create_image(430,380, anchor=NW, image=photo31) money = money + 2*bet bet = 0 with open("bet.txt", "w") as file: file.write(str(bet)) with open("save.txt", "w") as file: file.write(str(money)) if tp < 21: if not (already_stood or already_doubled) : if x >= 935 and x <= 1010 and y >= 600 and y <= 650:#hit player.append(rc(cards)) print(player) for i in range(2,len(player)): if player[i] == 11: card = rc([tr_A, pi_A, co_A, ca_A]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 2: card = rc([tr_2, pi_2, co_2, ca_2]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 3: card = rc([tr_3, pi_3, co_3, ca_3]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 4: card = rc([tr_4, pi_4, co_4, ca_4]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 5: card = rc([tr_5, pi_5, co_5, ca_5]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 6: card = rc([tr_6, pi_6, co_6, ca_6]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 7: card = rc([tr_7, pi_7, co_7, ca_7]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 8: card = rc([tr_8, pi_8, co_8, ca_8]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 9: card = rc([tr_9, pi_9, co_9, ca_9]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 10: card = rc([tr_10, pi_10, co_10, ca_10, tr_J, pi_J, co_J, ca_J, tr_Q, pi_Q, co_Q, ca_Q, tr_K, pi_K, co_K, ca_K]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) else: lose = True if not (already_doubled or already_stood): if x >= 50 and x <= 250 and y >= 600 and y <= 650: #double if money >= bet: money -= bet bet *= 2 with open("bet.txt", "w") as file: file.write(str(bet)) canvas.delete(id27) with open("save.txt", "w") as file: file.write(str(money)) canvas.delete(id28) print(bet) player.append(rc(cards)) for i in range(2,len(player)): if player[i] == 11: card = rc([tr_A, pi_A, co_A, ca_A]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 2: card = rc([tr_2, pi_2, co_2, ca_2]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 3: card = rc([tr_3, pi_3, co_3, ca_3]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 4: card = rc([tr_4, pi_4, co_4, ca_4]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 5: card = rc([tr_5, pi_5, co_5, ca_5]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 6: card = rc([tr_6, pi_6, co_6, ca_6]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 7: card = rc([tr_7, pi_7, co_7, ca_7]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 8: card = rc([tr_8, pi_8, co_8, ca_8]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 9: card = rc([tr_9, pi_9, co_9, ca_9]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) elif player[i] == 10: card = rc([tr_10, pi_10, co_10, ca_10, tr_J, pi_J, co_J, ca_J, tr_Q, pi_Q, co_Q, ca_Q, tr_K, pi_K, co_K, ca_K]) canvas.create_image(450+40*(i), 500, anchor=NW, image=card) already_doubled = True canvas.delete(id23_2) while tc<=16 : comp.append(rc(cards)) tc = total(comp) for i in range(1,len(comp)): if comp[i] == 11: card = rc([tr_A, pi_A, co_A, ca_A]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 2: card = rc([tr_2, pi_2, co_2, ca_2]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 3: card = rc([tr_3, pi_3, co_3, ca_3]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 4: card = rc([tr_4, pi_4, co_4, ca_4]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 5: card = rc([tr_5, pi_5, co_5, ca_5]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 6: card = rc([tr_6, pi_6, co_6, ca_6]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 7: card = rc([tr_7, pi_7, co_7, ca_7]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 8: card = rc([tr_8, pi_8, co_8, ca_8]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 9: card = rc([tr_9, pi_9, co_9, ca_9]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 10: card = rc([tr_10, pi_10, co_10, ca_10, tr_J, pi_J, co_J, ca_J, tr_Q, pi_Q, co_Q, ca_Q, tr_K, pi_K, co_K, ca_K]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) if not (already_stood or lose) : if x >= 935 and x <= 1085 and y >= 675 and y <= 725:#stand print(comp) canvas.delete(id23_2) while tc<=16 : comp.append(rc(cards)) tc = total(comp) for i in range(1,len(comp)): if comp[i] == 11: card = rc([tr_A, pi_A, co_A, ca_A]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 2: card = rc([tr_2, pi_2, co_2, ca_2]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 3: card = rc([tr_3, pi_3, co_3, ca_3]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 4: card = rc([tr_4, pi_4, co_4, ca_4]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 5: card = rc([tr_5, pi_5, co_5, ca_5]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 6: card = rc([tr_6, pi_6, co_6, ca_6]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 7: card = rc([tr_7, pi_7, co_7, ca_7]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 8: card = rc([tr_8, pi_8, co_8, ca_8]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 9: card = rc([tr_9, pi_9, co_9, ca_9]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) elif comp[i] == 10: card = rc([tr_10, pi_10, co_10, ca_10, tr_J, pi_J, co_J, ca_J, tr_Q, pi_Q, co_Q, ca_Q, tr_K, pi_K, co_K, ca_K]) canvas.create_image(450+40*(i), 50, anchor=NW, image=card) already_stood = True id27 = canvas.create_text(950, 400, text="$"+str(bet), font=("Bookman Old Style",30,'bold','italic'), fill="yellow") id28 = canvas.create_text(930, 810, text="$"+str(money), font=("Bookman Old Style",20,'bold','italic'), fill="yellow") if already_stood or already_doubled: tp = total(player) tc = total(comp) if tp >= tc: win = True elif (tc > 21 and tp<21) : win = True elif (tp>21): lose = True elif (tp<21 and tc>tp and tc<21): lose=True if lose: bet = 0 with open("bet.txt", "w") as file: file.write(str(bet)) canvas.delete(id27) id30 = canvas.create_image(415,380, anchor=NW, image=photo30) if win: id31 = canvas.create_image(430,380, anchor=NW, image=photo31) money = money + 2*bet bet = 0 with open("bet.txt", "w") as file: file.write(str(bet)) canvas.delete(id27) with open("save.txt", "w") as file: file.write(str(money)) canvas.delete(id28)
cwin = 0 # computer counter pwin = 0 # player counter nchips = 100 # number of chips to begin with while True: if nchips >= 1: nchips -= 1 else: print "You do not have enough balance to continue playing." break playchipshand = 1 # number of chips bet on a hand print "Your initial stake for this hand is 1 chip. You now have %d chips on hand" % (nchips) print player = [] # start with 2 cards player.append(rc(cards)) player.append(rc(cards)) pbust = False # player busted flag cbust = False # computer busted flag while True: # player's turn ... tp = total(player) print "The player has these cards %s with a total value of %d" % (player, tp) if tp > 21: print "**** Player loses! ****" pbust = True break elif tp == 21: print "Player wins **** BLACKJACK!!! ****" break else:
# Customer.Id c.execute("select distinct id from [Employee]") employees = [row[0] for row in c.fetchall()] # Shipper.Id c.execute("select distinct id from [Shipper]") shippers = [row[0] for row in c.fetchall()] # Customer.Id c.execute("select distinct id from [Customer]") customers = [row[0] for row in c.fetchall()] # Create a bunch of new orders for i in range(randint(15000,16000)): sql = 'INSERT INTO [Order] (CustomerId, EmployeeId, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' location = rc(locations) order_date = random_date(datetime.strptime('2012-07-10', '%Y-%m-%d'), datetime.today()) required_date = random_date(order_date, order_date+timedelta(days=randint(14,60))) shipped_date = random_date(order_date, order_date+timedelta(days=randint(1,30))) params = ( rc(customers), # CustomerId rc(employees), # EmployeeId order_date, # OrderDate required_date, # RequiredDate shipped_date, # ShippedDate rc(shippers), # ShipVia 0.00, # Freight location[0], # ShipName location[1], # ShipAddress location[2], # ShipCity location[3], # ShipRegion
def personal_trope(self, charList, filePath): text = get_file(filePath) # text = text.decode('utf8') # text = text.encode('ascii', 'ignore') if len(charList) == 1: characterTrope = True else: characterTrope = False try: pos = en.sentence.tag(text) wordtag = map(list, zip(*pos)) words = wordtag[0] tags = wordtag[1] for i in range(len(words)): charRef = rc([rc(charList), charList[0]]) if words[i].lower() == "character" and i > 0: words[i-1] = charRef.firstName words[i] = charRef.lastName elif tags[i] == "PRP": words[i] = charRef.firstName elif tags[i] == "PRP$": words[i] = charRef.firstName+"\'s" elif tags[i] in ["VBD", "VBG", "VBN", "VBZ"]: try: words[i] = en.verb.past(words[i], person=3, negate=False) except: pass if characterTrope: if words[i] == "have": words[i] = "has" elif words[i] == "are": words[i] = "is" punc = [".", ",", ";", ":", "!", "?"] for i in range(len(words)): if words[i] in punc: words[i] = '\b'+words[i] final_text = " ".join(words) if characterTrope: mainCharRef = rc(charList) index = string.find(final_text, mainCharRef.firstName) if final_text[index+len(mainCharRef.firstName)+1:index+len(mainCharRef.firstName)+1+len(mainCharRef.lastName)] == mainCharRef.lastName: final_text = final_text[index:] else: final_text = mainCharRef.firstName+" "+mainCharRef.lastName+final_text[index+len(mainCharRef.firstName):] replacements = {"trope": "clue", "Trope": "clue", "TROPE": "CLUE"} for x, y in replacements.iteritems(): final_text = string.replace(final_text, x, y) except: final_text = "" return final_text
def make_chars(self): # establish gender ratio charGenders = [ri(0,1) for _ in range(CC)] # initialize list of characters chars = [] # add user defined characters for firstlast in args.charnames: fl_list = firstlast.split('_') # Note that split is an underscore! chars.append(Character(fl_list[0], fl_list[1])) # add generated characters for b in charGenders: if b: chars.append(Character(rc(fFirstNames), rc(surnames))) else: chars.append(Character(rc(mFirstNames), rc(surnames))) # establish list of intro scenes introScenePaths = rs(characterTropeFiles, len(chars)) # establish list of settings settings = rs(settingTropeFiles, len(chars)*TSV) # establish list of drug trips trips = rs(erowidExpPaths, len(chars)*DTV) # establish list of scp articles scps = rs(scpPaths, len(chars)*SCP) # establish list of gberg excerpts gbergs = rs(gPaths.values(), len(chars)*GGV) i = 0 j = 0 m = 0 p = 0 s = 0 for c in chars: # make friends c.friends += rs(chars, ri(1,len(chars)-1)) if c in c.friends: c.friends.remove(c) # add introduction description c.introDesc = self.personal_trope([c], introScenePaths[i]) # add setting scenes for k in range(TSV): c.scenes.append(self.personal_trope([c]+c.friends, settings[j+k])) # add drug trip scenes for n in range(DTV): c.drugTrips.append(self.personal_trip([c]+c.friends, trips[m+n])) # add scp articles for q in range(SCP): c.scpReports.append(self.personal_scp([c]+c.friends, scps[p+q])) # add gberg excerpts for t in range(GGV): c.gbergExcerpts.append(self.personal_gberg([c]+c.friends, gbergs[s+t])) i += 1 j += TSV m += DTV p += SCP s += GGV self.characters = chars
def rs (length): """Generate a random string""" return ''.join(rc(string.ascii_lowercase + string.digits) for _ in range(length))
def get_word(l): word = rc(jsonObj[l]) return word[0].upper() + word[1:]
def total(hand): # how many aces in the hand aces = hand.count(11) # to complicate things a little the ace can be 11 or 1 # this little while loop figures it out for you t = sum(hand) # you have gone over 21 but there is an ace if t > 21 and aces > 0: while aces > 0 and t > 21: # this will switch the ace from 11 to 1 t -= 10 aces -= 1 return t # a suit of cards in blackjack assume the following values cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11] # there are 4 suits per deck and usually several decks # this way you can assume the cards list to be an unlimited pool cwin = 0 # computer win counter pwin = 0 # player win counter while True: player = [] # draw 2 cards for the player to start player.append(rc(cards)) player.append(rc(cards)) pbust = False # player busted flag cbust = False # computer busted flag while True: # loop for the player's play ... tp = total(player) print "The player has these cards %s with a total value of %d" % (player, tp) if tp > 21: print "--> The player is busted!" pbust = True break elif tp == 21: print "\a BLACKJACK!!!" break else: hs = raw_input("Hit or Stand/Done (h or s): ").lower() if 'h' in hs: player.append(rc(cards)) else: break while True: # loop for the computer's play ... comp = [] comp.append(rc(cards)) comp.append(rc(cards)) # dealer generally stands around 17 or 18 while True: tc = total(comp) if tc < 18: comp.append(rc(cards)) else: break print "the computer has %s for a total of %d" % (comp, tc) # now figure out who won ... if tc > 21: print "--> The computer is busted!" cbust = True if pbust == False: print "The player wins!" pwin += 1 elif tc > tp: print "The computer wins!" cwin += 1 elif tc == tp: print "It's a draw!" elif tp > tc: if pbust == False: print "The player wins!" pwin += 1 elif cbust == False: print "The computer wins!" cwin += 1 break print print "Wins, player = %d computer = %d" % (pwin, cwin) exit = raw_input("Press Enter (q to quit): ").lower() if 'q' in exit: break print print print "Thanks for playing blackjack with the computer!"
def rDNA (length): """Generate a random DNA string""" return ''.join(rc(["A","T","C","G"]) for _ in range(length))
def parse_message(self, text, usernick, channel): if channel != self.chan: userOrFalse = usernick else: userOrFalse = False words = re.findall(r"\b[\w]+\b", text.lower()) tokens = text.lower().split() original_words = words[:] try: words.remove(self.nick) except: pass try: words.remove('hst') except: pass try: tree = parsetree(' '.join(words)) firstNoun = match('NN|NNS|NNP|NNPS', tree) except: firstNoun = None # print original_words if self.nick in original_words: if set(words) & set(['help', 'commands']): commandsTemp = Template(self.commands) self.send_msg( commandsTemp.substitute(usernick=usernick, botnick=self.nick), channel=userOrFalse ) elif '?' in text or (set(words) & set(['who', 'where', 'when', 'what', 'why', 'how'])): fileObj = open('weird_grammar.json', 'r') jsonObj = json.load(fileObj) fileObj.close() s = sentiment(text)[0] if s > 0: print s * 2500 + 1 self.send_msg( make_polar(jsonObj, int(s * 2500 + 1)), channel=userOrFalse ) else: print s * 2500 - 1 self.send_msg( make_polar(jsonObj, int(s * -2500 - 1), sent=0), channel=userOrFalse ) elif firstNoun is not None: print firstNoun.string.replace('_', ' ') s = sentiment(text)[0] sentences = sorted( pf_sentences(abs(s*1000+3), firstNoun.string.replace('_', ' ')), key = lambda x: sentiment(x)[0] ) if s > 0: # print s * 2500 + 1 self.send_msg( ' '.join(sentences[-3:]), channel=userOrFalse ) else: # print s * 2500 - 1 self.send_msg( ' '.join(sentences[:3]), channel=userOrFalse ) else: snarkTemp = Template(rc(self.snarklist)) self.send_msg( snarkTemp.substitute(usernick=usernick, botnick=self.nick), channel=userOrFalse ) if tokens[0] == '.seen': tgt_user = tokens[1] if tgt_user in self.seen_dict: last_time, last_msg = self.seen_dict[tgt_user] self.send_msg( "%s: %s last seen on %s saying: %s" % (usernick, tgt_user, last_time, last_msg), channel=userOrFalse ) else: self.send_msg( "%s: I haven't seen %s." % (usernick, tgt_user), channel=userOrFalse ) elif tokens[0] == '.tell': tgt_user = tokens[1] if not tgt_user in self.tells_dict: self.tells_dict[tgt_user] = [] self.tells_dict[tgt_user].append((usernick, ' '.join(tokens[2:]))) self.send_msg( "%s: Ok, I'll tell %s that for you." % (usernick, tgt_user), channel=userOrFalse ) with open('tells_dict.json', 'w') as outfile: json.dump(self.tells_dict, outfile) elif tokens[0] == '.showtells': if not usernick in self.tells_dict or not self.tells_dict[usernick]: self.send_msg("%s: I have nothing for you." % usernick, channel=usernick) else: while self.tells_dict[usernick]: src_user, tell_msg = self.tells_dict[usernick].pop() self.send_msg("%s said: %s" % (src_user, tell_msg), channel=usernick) with open('tells_dict.json', 'w') as outfile: json.dump(self.tells_dict, outfile) elif tokens[0] == '.gif': gif_url = get_gif(tokens[1:]) self.send_msg("%s: %s" % (usernick, gif_url), channel=userOrFalse) elif tokens[0] == '.wiki': try: wiki_url, wiki_text = get_wiki_article(tokens[1:]) except: self.send_msg( "%s: I'm sorry, but something went wrong!" % usernick, channel=userOrFalse ) else: if wiki_text: safe_wiki_text = ''.join(list(wiki_text)[:300]).replace('\n', ' ') + '...' safe_wiki_text = safe_wiki_text.encode('ascii', 'ignore') self.send_msg( "%s: %s | %s" % (usernick, wiki_url, safe_wiki_text), channel=userOrFalse ) else: self.send_msg( "%s: I'm sorry, but something went wrong!" % usernick, channel=userOrFalse ) elif tokens[0] == '.yt': try: result = youtube_search(tokens[1:]) result = map(lambda x: x.encode('ascii', 'ignore'), result) title, desc, vidId = result self.send_msg( "%s: %s | %s | https://www.youtube.com/watch?v=%s" % (usernick, title, desc, vidId), channel=userOrFalse ) except: self.send_msg( "%s: I'm sorry, but something went wrong!" % usernick, channel=userOrFalse ) elif tokens[0] == '.hst': # self.send_msg('/nick drgonzo') if firstNoun is not None: lookupFile = open("hst_lookup.json", 'r') lookup = json.load( lookupFile ) lookupFile.close() nounStem = stem(firstNoun, stemmer=PORTER) idHash = None print nounStem try: # switch to descending idHash = rc(lookup[nounStem]) print idHash except KeyError: pass try: idHash = rc(lookup[firstNoun]) print idHash except KeyError: pass if idHash is not None: bookFile = open("hst_text.json", 'r') books = json.load( bookFile ) bookFile.close() text = books[idHash].encode('ascii', 'ignore') # print text self.send_msg("%s: %s"%(usernick,text), channel=userOrFalse) else: self.send_msg("%s: Can't say I know it." % usernick, channel=userOrFalse) else: self.send_msg("%s: Nothing to say about that." % usernick, channel=userOrFalse) # self.send_msg('/nick itpbot') if "ross" in words: self.send_msg("%s: I hope you're not speaking ill of my creator." % usernick, channel=userOrFalse) if "itp" in words: message = rand_itp_acronym() self.send_msg(message, channel=userOrFalse)