blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
133
path
stringlengths
2
333
src_encoding
stringclasses
30 values
length_bytes
int64
18
5.47M
score
float64
2.52
5.81
int_score
int64
3
5
detected_licenses
listlengths
0
67
license_type
stringclasses
2 values
text
stringlengths
12
5.47M
download_success
bool
1 class
965aa705c9603a5e1bfc3a3178bab0d87412086d
Python
Crastchet/DeezerToRekordbox
/main.py
UTF-8
4,340
2.515625
3
[]
no_license
#!/usr/bin/python # -*-coding:utf-8 -* import requests import json from lxml import etree import sys def getPlaylists_Id_Title_FromUser(userId): requ = requests.get('https://api.deezer.com/user/{}/playlists'.format(userId)) resp = requ.json() playlists_id_title = [] for playlist in resp['data']: playlists_id_title.append( { 'id':playlist['id'], 'title':playlist['title'] } ) return playlists_id_title def getTracksFromPlaylistId(playlistId): requ = requests.get('https://api.deezer.com/playlist/{}/tracks'.format(playlistId)) resp = requ.json() tracks = [] while resp != None: for track in resp['data']: tracks.append( { 'id':track['id'], 'title':track['title'], 'artist':track['artist']['name'] # Here I made the choice to only keep artist.name, and not the object artist (will change to make match more accurate) } ) if 'next' in resp: requ = requests.get(resp['next']) resp = requ.json() else: resp = None return tracks def getPlaylists_Tracks_FromUser(userId): playlists = [] playlists_id_title = getPlaylists_Id_Title_FromUser(userId) for playlist_id_title in playlists_id_title: playlists.append( { 'infos':playlist_id_title, 'tracks':getTracksFromPlaylistId(playlist_id_title['id']) } ) return playlists # Extract the tracks from the file generated with RekordBox def getAllTracksFromCollection(xmlFile): tree = etree.parse(xmlFile) tracks = [] for track in tree.xpath("/DJ_PLAYLISTS/COLLECTION/TRACK"): tracks.append( { 'TrackID':track.get("TrackID"), 'Name':track.get("Name"), 'Artist':track.get("Artist") } ) return tracks # Find in which playlists a track from RekordBox appears def findPlaylists_Title_ForTrack(playlists, track_to_find): playlists_title_to_return = [] for playlist in playlists: for track in playlist['tracks']: if track_to_find['Name'] == track['title'] and track_to_find['Artist'].split("/")[0] == track['artist']: playlists_title_to_return.append(playlist['infos']['title']) break return playlists_title_to_return def generateCollectionPlaylists(playlists,tracks): collection_playlists = {} for track in tracks: for playlist in findPlaylists_Title_ForTrack(playlists,track): if playlist in collection_playlists: collection_playlists[playlist].append(track['TrackID']) else: collection_playlists[playlist] = [ track['TrackID'] ] return collection_playlists def addPlaylistsIntoXML(collection_playlists, fileName): tree = etree.parse(fileName) node_playlists_root = tree.xpath("/DJ_PLAYLISTS/PLAYLISTS/NODE")[0] node_playlists_root.set("Count", str( len(collection_playlists) )) for playlistTitle in collection_playlists: node_playlists_root_playlist = etree.SubElement(node_playlists_root, "NODE") node_playlists_root_playlist.set("Name", playlistTitle) node_playlists_root_playlist.set("Type", "1") node_playlists_root_playlist.set("KeyType", "0") node_playlists_root_playlist.set("Entries", str(len(collection_playlists[playlistTitle]))) for trackID in collection_playlists[playlistTitle]: track = etree.SubElement(node_playlists_root_playlist, "TRACK") track.set("Key", trackID) node_djplaylists = tree.xpath("/DJ_PLAYLISTS")[0] # file = open('new_'+fileName, "w") et = etree.ElementTree(node_djplaylists) et.write('new_'+fileName, pretty_print=True, xml_declaration=True, encoding="utf-8") if __name__ == "__main__": print(type(sys.argv[0])) print(type(sys.argv[1])) print(type(sys.argv[2])) # Load the tracks fom RekordBox tracks = getAllTracksFromCollection(sys.argv[2]) # Load the playlist of user playlists = getPlaylists_Tracks_FromUser(sys.argv[1]) # Match playlists with RekorBox's tracks collection_playlists = generateCollectionPlaylists(playlists,tracks) # Write in xml file for RekordBox addPlaylistsIntoXML(collection_playlists,sys.argv[2])
true
0890485ae911c89d3bf8bfb60e15400d8d1afd45
Python
MatiNem/Intro_Biocom_ND_319_Tutorial7
/exercise7.py
UTF-8
614
3.234375
3
[]
no_license
import pandas InFile=open("Lecture11.fasta","r") sequenceLength=[] percentGC = [] for line in InFile: line = line.strip() #remove extra space if ">" in line: next else: sequenceLength.append(len(line)-1) percentGC.append(1.0*(line.count("G")+line.count("C"))/len(line)) print(percentGC) #Puts data in dataframe data=pandas.DataFrame({"Sequence Length": sequenceLength, "Percent GC": percentGC}) from plotnine import * length=ggplot(data,aes(x="Sequence Length")) length+geom_histogram()+theme_classic() gc=ggplot(data,aes(x="Percent GC")) gc+geom_histogram()+theme_classic()
true
abcbe962aa44ccc98624f1e88bb53220a212d82a
Python
Shoshin23/A-Crawler
/linkfetcher.py
UTF-8
1,731
2.5625
3
[]
no_license
#! /usr/bin/env python from BeautifulSoup import BeautifulSoup from cgi import escape import sys import urllib2 import urlparse __version__ = "0.0.1" Agent = "%s/%s" % (__name__, __version__) class Linkfetcher(object): def __init__(self, url): self.url = url self.urls = [] def _addHeaders(self, request): request.add_header("User-Agent", Agent) def __getitem__(self, x): return self.urls[x] def open(self): url = self.url try: request = urllib2.Request(url) handle = urllib2.build_opener() except IOError: return None return (request, handle) def linkfetch(self): request, handle = self.open() self._addHeaders(request) if handle: try: content = unicode(handle.open(request).read(), "utf-8", errors="replace") soup = BeautifulSoup(content) tags = soup('a') except urllib2.HTTPError, error: if error.code == 404: print >> sys.stderr, "ERROR: %s -> %s" % (error, error.url) raise SystemExit, 0 else: print >> sys.stderr, "ERROR: %s" % error raise SystemExit, 0 tags = [] except urllib2.URLError, error: print >> sys.stderr, "ERROR: %s" % error tags = [] for tag in tags: href = tag.get("href") if href is not None: url = urlparse.urljoin(self.url, escape(href)) if url not in self: self.urls.append(url)
true
0e9586d212b4d6e2f4a741c4bdb08fa78a395141
Python
vricha216/Projects
/resume.py
UTF-8
4,757
2.921875
3
[]
no_license
Header = '>>>This resume is totally made up with the help of python.' Name = 'Richa Verma' Title = 'vricha211697@gmail.com' Contact = '632607' add ='Lakhimpur-Kheri' SkillsHeader = 'SKILLS' SkillsDesc= '. Python\n. C\n. DBMS\n. Creative Thinking\n. SQL\n. Operating System\n. Data Structure and Algorithms\n. Mathematics\n. Problem Solving' Languages = 'LANGUAGES' LanguagesDesc = ' Hindi\n English\n Punjabi' Objective='OBJECTIVE' Obj = ' As a recent graduate,I am seeking a role which allows\n me to continue learning and perfecting my skills as I\n provide high-quality work,and encourages me to\n flourish as a Software Engineer.' MyTime = 'MY WORKS' mytimedesc = '. Billing Software\n. Resume with lot of Annotations\n. Student Management System \n. Chatbot using IBM WATSON' quote='let\'s speak the CODE' Education = 'EDUCATION' a='Bachelor Of Technology' b='APJ Abdul Kalam Technical University' c='2016-2020' d='Higher Secondary Certificate ' e='City Montessori School' f='2014-2015' g='Seconary School Certificate' h='Jawahar Navodaya Vidyalya' i='2012-2013' j='PASSION' k=' Chess\n Writing\n Sketching\n Solving Puzzles' l='FIND ME ONLINE' m=' @vricha211697\n @/richa-verma-20895315a' n='MY LIFE PHILOSOPHY' o=' Anyone who has ever made anything of\n importance was Hardwork,Determination\n and Disciplined.' import matplotlib.pyplot as plt from matplotlib.offsetbox import TextArea,DrawingArea,OffsetImage,AnnotationBbox import matplotlib.image as mpimg #import numpy as np #import pandas as pd plt.rcParams['font.family'] = 'DejaVu Sans' #runtime configuration contains the default styles for every plot element you create fig,ax = plt.subplots(figsize=(8.5,11)) #new.axis('off') ax.set_title('RESUME',weight="bold") ax.axvline(x=.5,ymin=0,ymax=1,color='#007ACC',alpha=0.0,linewidth = 50) plt.axvline(x=0.1,color='#000000',alpha=0.5,linewidth=300) #plt.axhline(y=.88,xmin=0,xmax=1,color='black',linewidth=3) ax.set_facecolor('White') plt.axis('off') plt.annotate(Header,(0.45,0.98),weight='regular',fontsize=8,alpha = 0.75) plt.annotate(Name,(0.04,.96),weight='bold',fontsize=22) plt.annotate(Title,(0.06,.93),weight='regular',color='blue',fontsize=10) plt.annotate(Contact,(0.12,.91),weight='regular',fontsize=10,color='#ffffff') plt.annotate(add,(0.1,.89),weight='regular',fontsize=10,color='#ffffff') plt.axhline(y=.85,xmin=0,xmax=0.396,color='black',linewidth=20) plt.annotate(SkillsHeader,(0.02,.84),weight='bold',color='white',fontsize=14) plt.annotate(SkillsDesc,(0.02,.66),weight='bold',color='white',fontsize=10) plt.axhline(y=.60,xmin=0,xmax=0.396,color='black',linewidth=20) plt.annotate(Languages,(0.02,.59),weight='bold',color='white',fontsize=14) plt.annotate(LanguagesDesc,(0.02,.51),weight='bold',color='white',fontsize=10) plt.axhline(y=.45,xmin=0,xmax=0.396,color='black',linewidth=20) plt.annotate(MyTime,(0.02,.44),weight='bold',color='white',fontsize=14) plt.annotate(mytimedesc,(0.02,.36),weight='bold',color='white',fontsize=10) plt.annotate(quote,(0.02,.32),weight='bold',color='#C5B53B',fontsize=10) plt.annotate(Objective,(0.44,.95),weight='bold',color='black',fontsize=14) plt.annotate(Obj,(0.44,.87),weight='regular',color='black',fontsize=10) plt.axhline(y=.86,xmin=0.44,xmax=1,color='black',linewidth=1) plt.annotate(Education,(0.44,.82),weight='bold',color='black',fontsize=14) plt.annotate(a,(0.44,.78),weight='bold',color='black',fontsize=12) plt.annotate(b,(0.44,.76),weight='bold',color='#C5B53B',fontsize=10) plt.annotate(c,(0.44,.74),weight='regular',color='black',fontsize=10) plt.annotate(d,(0.44,.70),weight='bold',color='black',fontsize=12) plt.annotate(e,(0.44,.68),weight='bold',color='#C5B53B',fontsize=10) plt.annotate(f,(0.44,.66),weight='regular',color='black',fontsize=10) plt.annotate(g,(0.44,.62),weight='bold',color='black',fontsize=12) plt.annotate(h,(0.44,.60),weight='bold',color='#C5B53B',fontsize=10) plt.annotate(i,(0.44,.58),weight='regular',color='black',fontsize=10) plt.axhline(y=.56,xmin=0.44,xmax=1,color='black',linewidth=1) plt.annotate(j,(0.44,.52),weight='bold',color='black',fontsize=14) plt.annotate(k,(0.44,.44),weight='regular',color='black',fontsize=10) plt.axhline(y=.40,xmin=0.44,xmax=1,color='black',linewidth=1) plt.annotate(l,(0.44,.36),weight='bold',color='black',fontsize=14) plt.annotate(m,(0.44,.31),weight='regular',color='black',fontsize=10) plt.axhline(y=.28,xmin=0.44,xmax=1,color='black',linewidth=1) plt.annotate(n,(0.44,.24),weight='bold',color='black',fontsize=14) plt.annotate(o,(0.44,.18),weight='bold',fontsize=10,color='#C5B53B') #adding image #img = mpimg.imread('C:\\shitty\\MSTI\\imagefiles\\richhh.jpg') #imagebox = OffsetImage(img,zoom=0.025) #ab = AnnotationBbox(imagebox,(0.06,0.91)) #ax.add_artist(ab) #plt.show() plt.savefig('resumeeeee.png',dpi=300,bbox_inches='tight')
true
e2d49ea3761ac85485ada7345b2ce7893b9c179f
Python
znnznn/coursera
/week3/сложний процент.py
UTF-8
254
3.15625
3
[]
no_license
import math p = float(input()) x = float(input()) y = float(input()) k = int(input()) i = 0 m = x * 100 + y while k > i: m1 = ((m * (100 + p)) / 100) m = int(m1) x = int(m1 // 100) y = int(m1 - (x * 100)) i += 1 print(int(x), int(y))
true
36a3c7f537076ba23975d6d29a40206a5e4f7bfe
Python
MatthewZhuang/ML
/classifier/test.py
UTF-8
1,101
2.546875
3
[]
no_license
if __name__ == '__main__': # pcti = [1] * 2 # pct = [pcti for i in range(3)] # print pct[2][1] # print 1/float(2) # # pc = [0]*5 # pc[0:3] = [1]*3 # pc[3:5] = [2]*2 # print pc # import re # s = 'hello999.' # res = re.findall('[0-9\.]', s) # for re in res: # s = s.replace(re, '') # print s # # # for i in range(10): # print i pcti = [0]*9 pct_tmp = [pcti for i in range(9)] print pct_tmp d = {} d['h'] = 'hello' l = [] l.append(d) print l[0]['h'] files = open("/Users/Matthew/Documents/python/data/zkread/internetfinance.txt", 'r') c1 = files.readlines() print len(c1) # files = open("/Users/Matthew/Documents/python/data/Project Annual Review/1.txt", 'r') # c2 = files.readlines() # print len(c2) from DataPreProcess import cut_words segwords1 = cut_words(c1) file1 = "/Users/Matthew/Documents/python/data/zkread/segwords.txt" # segwords1 = loadSegFile(file1) from DataPreProcess import writeSegResult writeSegResult(segwords1, file1)
true
50191052b26f1c8a27f4c0dd14122819712bd6c8
Python
Tusharsaxena3112/Sorting_in_Python
/bubble_sort.py
UTF-8
160
3.046875
3
[]
no_license
l = [1, 3, 5, 1, 4, 1] for i in range(len(l)): for j in range(1, len(l)): if l[j - 1] > l[j]: l[j - 1], l[j] = l[j], l[j - 1] print(l)
true
aa1c125d5f79cbd7fa5f5902b9e06f90daec91f1
Python
radup99/wc.py
/check_arguments.py
UTF-8
2,854
3.109375
3
[]
no_license
import sys default_options = { # if no options are specified through command line "-l": True, "-w": True, "-c": True, "-m": False, "-L": False, } long_options = { "--lines": "-l", "--words": "-w", "--bytes": "-c", "--chars": "-m", "--max-line-length": "-L" } def check_arguments(args): options = { "-l": False, "-w": False, "-c": False, "-m": False, "-L": False, } option_count = 0 files = [] files_count = 0 for arg in args: # first checks if the argument is a double dash command if arg == "--help": help_text = open("help.txt").read() print(help_text) return -1, -1 elif arg.startswith("--files0-from="): count = get_files_from_txt(arg, files) if count != -1: files_count += count else: return -1, -1 elif arg.startswith("--"): if arg not in long_options: print(f"wc: unrecognized option \'{arg}\'") return -1, -1 else: options[long_options[arg]] = True option_count += 1 # checks if it's a single dash command elif arg == "-": files.append("-") files_count += 1 elif arg.startswith("-"): if arg not in options: print(f"wc: invalid option -- \'{arg[1:]}\'") return -1, -1 else: options[arg] = True option_count += 1 # if it's not either type of command, the argument is considered a file else: if is_file_valid(arg): files.append(arg) files_count += 1 else: return -1, -1 # selects the default options since no options were specified by the user if option_count == 0: options = default_options if files_count == 0: files = [" "] # keyboard input instead of files return options, files def is_file_valid(arg): try: open(arg) except FileNotFoundError: print(f"wc: {arg}: No such file or directory") return False else: return True def get_files_from_txt(arg, files): source_file = arg[14:] count = 0 if source_file == "-": source = sys.stdin.read() print("") else: try: source = open(source_file).read() except FileNotFoundError: print(f"wc: cannot open '{source_file}' for reading: " "No such file or directory") return -1 for file in source.split("\n"): if is_file_valid(file): files.append(file) count += 1 else: return -1 return count
true
8522e007d49b0a9b05936445645452786b4818f9
Python
luheeslo/design_patterns_python
/Work/commandv2.py
UTF-8
607
3.84375
4
[]
no_license
# Command def buy_stock_order(stock): stock.buy() # Command def sell_stock_order(stock): stock.sell() # Receiver class StockTrade: def buy(self): print("You will buy stocks.") def sell(self): print("You will sell stocks.") # Invoker class Agent: def __init__(self): self.__orderQueue = [] def placeOrder(self, stock, order): self.__orderQueue.append(order) order(stock) if __name__ == "__main__": stock = StockTrade() agent = Agent() agent.placeOrder(stock, buy_stock_order) agent.placeOrder(stock, sell_stock_order)
true
68ac49f324e7461e092abfd2832380172b15292f
Python
oldman3483/Parrot-groundSDK
/out/olympe-linux/staging/usr/lib/python3.6/site-packages/olympe/doc/examples/maxtilt.py
UTF-8
972
2.546875
3
[]
no_license
# -*- coding: UTF-8 -*- from __future__ import print_function # python2/3 compatibility for the print function import olympe from olympe.messages.ardrone3.PilotingSettings import MaxTilt DRONE_IP = "10.202.0.1" if __name__ == "__main__": drone = olympe.Drone(DRONE_IP) drone.connect() maxTiltAction = drone(MaxTilt(10)).wait() if maxTiltAction.success(): print("MaxTilt(10) success") elif maxTiltAction.timedout(): print("MaxTilt(10) timedout") else: # If ".wait()" is called on the ``maxTiltAction`` this shouldn't happen print("MaxTilt(10) is still in progress") maxTiltAction = drone(MaxTilt(0)).wait() if maxTiltAction.success(): print("MaxTilt(0) success") elif maxTiltAction.timedout(): print("MaxTilt(0) timedout") else: # If ".wait()" is called on the ``maxTiltAction`` this shouldn't happen print("MaxTilt(0) is still in progress") drone.disconnect()
true
e1dc319118cfe2716f6bad76177e283e0b555058
Python
AniluaR07/AniluaR07.github.io
/AniluaR.py
UTF-8
1,046
4.1875
4
[]
no_license
import random # A list of words that potential_words = ["Masterpiece", "Monster", "Computer", "Improvements", "juice"] word = random.choice(potential_words) caracters = len(word) # Use to test your code: # print(word) # Converts the word to lowercase word = word.lower() # Make it a list of letters for someone to guess current_word = ["_"] # TIP: the number of letters should match the word for a in range(caracters - 1): current_word.append("_") # Some useful variables guesses = [] maxfails = 5 fails = 0 while fails < maxfails: guess = input("Guess a letter: ") # check if the guess is valid: Is it one letter? Have they already guessed it? check = False while check == False: guess = input("guess the word") # check if the guess is correct: Is it in the word? If so, reveal the letters! if guess == word: check = True print(current_word) fails = fails+1 print("You have " + str(maxfails - fails) + " tries left!") else: check = False print("try again") check = True print("you won!")
true
0ea61b2a13df4fcfeebe5ea52e9f67bcad04dfda
Python
arunachalamev/PythonProgramming
/Algorithms/LeetCode/L0198rob.py
UTF-8
336
3.1875
3
[]
no_license
def rob(nums): if len(nums) ==0: return 0 if len(nums) ==1: return nums[0] if len(nums) == 2: return max(nums[0],nums[1]) prevPrev, prev = 0, 0 for index,value in enumerate(nums): current = max(prev, prevPrev+value) prevPrev= prev prev= current return current print(rob([2,7,9,3,1]))
true
c974cbbbc0f098b4d188d8cee606646df515128a
Python
abdullateef28/c_l_project_shoyinka_lateef
/list 2.py
UTF-8
1,227
2.78125
3
[]
no_license
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:05:16) [MSC v.1915 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> ============= RESTART: C:/Users/Asus-PC/Documents/phyton/list.py ============= >>> >>> ============= RESTART: C:/Users/Asus-PC/Documents/phyton/list.py ============= Traceback (most recent call last): File "C:/Users/Asus-PC/Documents/phyton/list.py", line 2, in <module> ptint (names) NameError: name 'ptint' is not defined >>> ============= RESTART: C:/Users/Asus-PC/Documents/phyton/list.py ============= ['lateef', 'azeez', 'toyeeb'] >>> names=["lateef", "azeez", "toyeeb"] >>> names ['lateef', 'azeez', 'toyeeb'] >>> names[0] 'lateef' >>> names[-2] 'azeez' >>> names.append("ismail") >>> names ['lateef', 'azeez', 'toyeeb', 'ismail'] >>> age=(12, 23, 6, 5) >>> names.extend(age) >>> names ['lateef', 'azeez', 'toyeeb', 'ismail', 12, 23, 6, 5] >>> names.remove("ismail") >>> names ['lateef', 'azeez', 'toyeeb', 12, 23, 6, 5] >>> print(names) ['lateef', 'azeez', 'toyeeb', 12, 23, 6, 5] >>> print(names,age) ['lateef', 'azeez', 'toyeeb', 12, 23, 6, 5] (12, 23, 6, 5) >>> len(names) 7 >>> max(age) 23 >>>
true
97640777b50e34707eff39b0e24e4ac6b740627b
Python
Interstellar300/Sudoku-solver
/tool.py
UTF-8
1,783
3.015625
3
[]
no_license
import Model.model as md import Utils.find_digit as fd import Utils.solve as s import Preprocess.preprocess as pp from torchvision import transforms import argparse import cv2 import numpy as np import torch def find_numbers(cells_raw): cells = [] for cell in cells_raw: cell = fd.get_digit(cell) # resize = cv2.resize(cell, (32,32), interpolation = cv2.INTER_AREA) resize = cv2.resize(cell, (48,48), interpolation = cv2.INTER_AREA) cells.append(resize) return cells def digitalize(model,cells): print("digitalizing the given image.....") sudoku_grid = [] row = [] transform = transforms.Compose([transforms.ToTensor()]) k = 0 for cell in cells: cell = transform(cell) # predictions = model(cell.view(1,1,32,32)) predictions = model(cell.view(1,1,48,48)) value = int(predictions.argmax()) row.append(value) k += 1 if(k % 9 == 0): sudoku_grid.append(row) row = [] return sudoku_grid if __name__=="__main__": parser = argparse.ArgumentParser() parser.add_argument("-i", "--image_path", help="path to the image of the sudoku problem",required=True) args = vars(parser.parse_args()) path = args["image_path"] cells_raw = pp.preprocess(path) cells = find_numbers(cells_raw) model = md.load_model() sudoku_grid = digitalize(model,cells) print("displaying the sudoku grid.....") for row in sudoku_grid: for cell in row: print(cell,end=" ") print() print("solving the puzzle") solved_grid = s.solve(sudoku_grid) print("displaying the solution.....") for row in solved_grid: for cell in row: print(cell,end=" ") print()
true
3cdad3222ce7374a6bbb2f39aa7d03e10837951c
Python
angeloasl/Projeto-D.O.G
/mestrecerto.py
UTF-8
1,789
2.6875
3
[]
no_license
#include <Ultrasonic.h> #include "SoftwareSerial.h" // Inclui a biblioteca SoftwareSerial Ultrasonic ultrassomPortaCasa(7, 6); // define o nome do sensor(ultrassom) Ultrasonic ultrassomPortaGaragem(5, 4); SoftwareSerial blackBoardSlave(2,3); // (RX, TX) bool dog = false; const int ledVerde = 11; const int botao_sistema = 13; const int botao_garagem = 13; const int ledVermelho = 9; const int ledAmarelo = 10; bool sinal_botao_garagem; bool sinal_botao_sistema; bool led_State = HIGH; void setup() { Serial.begin(9600); pinMode(ledAmarelo, OUTPUT); pinMode(botao_sistema, INPUT); pinMode(ledVerde, OUTPUT); pinMode(ledVermelho, OUTPUT); sinal_botao_sistema = true; blackBoardSlave.begin(9600); } void loop() { float distancia_PortaCasa = ultrassomPortaCasa.Ranging(CM); float distancia_PortaGaragem = ultrassomPortaGaragem.Ranging(CM); if (sinal_botao_sistema == false) { digitalWrite(ledAmarelo, HIGH); digitalWrite(ledVermelho, LOW); digitalWrite(ledVerde, LOW); dog = false; } if (digitalRead(botao_sistema) == HIGH) { while (digitalRead(botao_sistema) == HIGH); sinal_botao_sistema = !sinal_botao_sistema; } if (sinal_botao_sistema == true) { digitalWrite(ledAmarelo, LOW); if ((distancia_PortaCasa >= 11) && (distancia_PortaCasa <= 15)) { dog = false; } if ((distancia_PortaGaragem >= 11) && (distancia_PortaGaragem <= 15)) { dog = true; } if (dog==false) { digitalWrite(ledVerde, HIGH); digitalWrite(ledVermelho, LOW); } if (dog==true) { digitalWrite(ledVermelho,HIGH); digitalWrite(ledVerde, LOW); } if (dog == false){ blackBoardSlave.print(1); } if (dog == true){ blackBoardSlave.print(0); } } }
true
a4b61ed81d92aa831bf8b48fb3fda959cfd9c3d3
Python
abnoviello23/GeminidSystemsPython
/Script1_PyCharm.py
UTF-8
438
2.765625
3
[]
no_license
import csv import json peopleCSV = open('people.csv') reader3 = csv.reader(peopleCSV, delimiter=',') final_csv2 = list(reader3) region_list = [] found = -1 state_to_region = open('state_to_region.json') state_data = json.load(state_to_region) for x in range(len(final_csv2)): for i in state_data: found = final_csv2[x][3].find(i) if found != -1: region_list.append(state_data[i]) final_csv2[x][4] = state_data[i] break
true
500a480a0966367232e44a9c9795065b09a32b55
Python
luchuynh/FaceIdentify
/FaceIdentify.py
UTF-8
6,387
2.65625
3
[]
no_license
import cv2 from Tkinter import * import numpy as np import os import tkMessageBox bin_n = 16 # chuyen anh xam # ten ten =["",] # phat hien khuon mat def detect_face(img): gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) face_cascade = cv2.CascadeClassifier('D:\\OpenCV\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_default.xml') faces = face_cascade.detectMultiScale(gray, scaleFactor = 1.2 ,minNeighbors= 5,minSize=(20,20)); if(len(faces)==0): return None,None x,y,w,h = faces[0] return gray[y:y+w,x:x+h],faces[0] # xu ly anh def hog(img): gx = cv2.Sobel(img,cv2.CV_32F, 1, 0) gy = cv2.Sobel(img,cv2.CV_32F, 0, 1) mag, ang = cv2.cartToPolar(gx, gy) bins = np.int32(bin_n*ang/(2*np.pi)) bin_cells = bins[:10,:10], bins[10:,:10], bins[:10,10:], bins[10:,10:] mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10:], mag[10:,10:] hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)] hist = np.hstack(hists) return hist #tao du lieu training va labels def create_data_traning(data_forder): dir = os.listdir(data_forder); # create two array to save data anh lables faces=[] labels=[] for dir_name in dir: if not dir_name.startswith('s'): continue label = int(dir_name.replace('s',"")) subject_dir_path = data_forder + "/" + dir_name subject_images_names = os.listdir(subject_dir_path) for image_name in subject_images_names: if image_name.startswith("."): continue; image_path = subject_dir_path+"/"+image_name image= cv2.imread(image_path) face,rect = detect_face(image) if face is not None: fp = hog(face) faces.append(fp) labels.append(label) return faces,labels # ve def draw_rectangle(img, rect): (x,y,w,h) = rect cv2.rectangle(img,(x,y),(x+w,y+h),(0,225,0),2) def draw_text(img,text,x,y): cv2.putText(img,text,(x,y),cv2.FONT_HERSHEY_PLAIN,1.5,(0,255,0),2) # tao du lieu training svm = cv2.ml.SVM_create() def train(): faces ,labels = create_data_traning("data") dataTrain = np.float32(faces).reshape(-1,64) Labels = np.array(labels)[:,np.newaxis] # mo hinh svm svm.setKernel(cv2.ml.SVM_LINEAR) svm.setType(cv2.ml.SVM_C_SVC) svm.setC(2.67) svm.setGamma(5.383) svm.train(dataTrain, cv2.ml.ROW_SAMPLE, Labels) # svm.save('svm_data.dat') tkMessageBox.showinfo("Thông Báo", "Máy đã học thành công") #print type(labels) def predict(img): face, rect = detect_face(img) if face is None: return else: hogdata2 = hog(face) imgtest = np.float32(hogdata2).reshape(-1,bin_n*4) result = svm.predict(imgtest)[1] label_text = ten[int(result[0])] draw_rectangle(img,rect) draw_text(img,label_text,rect[0],rect[1]-5) return img def nhandien(): cap =cv2.VideoCapture(0) while True: ret,frame = cap.read() pic = predict(frame) if pic is None: cv2.imshow('pic',frame) else: cv2.imshow('pic',pic) if cv2.waitKey(1) & 0xFF ==ord('q'): break cap.release() cv2.destroyAllWindows() # ham tao du lieu def hoc(): face_cascade = cv2.CascadeClassifier('D:\\OpenCV\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_default.xml') count = 0 name=stringTen.get() ten.append(name); i = len(ten)-1; path ='E:\\Ung dung nhan dien khuon mat\\data\\s%d'%i os.mkdir(path,755) cap = cv2.VideoCapture(0) while True: ret,img = cap.read() gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray,1.3,5,minSize=(20,20)) for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) roi_gray = gray[y:y+h, x:x+w] roi_color = img[y:y+h, x:x+w] if(count < 100): cv2.imwrite('../Ung dung nhan dien khuon mat/data/s%d/anh%d.jpg'%(i,count),gray) count += 1 else: cv2.putText(img,'tao du lieu xong roi ^^',(x,y),cv2.FONT_HERSHEY_PLAIN,1.5,(0,255,0),2,cv2.LINE_AA) cv2.imshow('img',img) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() # ham xoa thu muc def xoafile(): path ='E:\\Ung dung nhan dien khuon mat\\data' fileNeed=os.listdir(path) for item in fileNeed: lsimg=os.listdir("../Ung dung nhan dien khuon mat/data/%s"%item) for x in lsimg: os.remove("../Ung dung nhan dien khuon mat/data/%s/%s"%(item,x)) os.removedirs("../Ung dung nhan dien khuon mat/data/%s"%item) os.mkdir(path,755) tkMessageBox.showinfo("Thông Báo", "xóa dữ liệu thành công") # create GUi def resetAction(): stringTen.set("") root = Tk() stringTen = StringVar() root.title("Nhận diên khuôn mặt") root.resizable(width=True,height=True) root.minsize(width=290,height=200) Label(root,text="ỨNG DỤNG NHẬN DIÊN KHUÔN MẶT",fg="red",height=2,justify=CENTER).grid(row=0,columnspan=3) Label(root,text="Tên của bạn :",fg="green",height=2).grid(row=1,column=0) t=Entry(root,textvariable=stringTen,).grid(row=1,column=1) t.pack(ipady=3) root.geometry("400x400") t = Text(r, height=20, width=40) frameButton = Frame() Button(frameButton,text="Tạo",fg="white",bg="violet",command = hoc).pack(side=LEFT) Label(frameButton,text=" ").pack(side=LEFT) Button(frameButton,text="Tiếp",fg="white",bg="violet",command=resetAction).pack(side=LEFT) frameButton.grid(row=1,column=2) Button(root,text="Cho Máy Học",fg="white",bg="Yellow",width=40,height=2,justify=CENTER,command=train).grid(row=3,columnspan=3) Button(root,text="Nhận Diện",fg="white",bg="lightblue",width=40,height=2,justify=CENTER,command=nhandien).grid(row=4,columnspan=3) Button(root,text="Clear Data",fg="white",bg="red",width=40,height=2,justify=CENTER,command=xoafile).grid(row=5,columnspan=3) root.mainloop()
true
685a74f7e8fb44455969c0cf3f1afcf01af5d877
Python
ffpy/Raspbian-Tools
/cpu_status.py
UTF-8
522
2.96875
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import re import time def get_cpu_temp(): '''获取CPU温度,单位:摄氏度''' return os.popen('vcgencmd measure_temp').read().strip()[len('temp='):-len("'C")] def get_cpu_used(): '''获取CPU使用率''' s = os.popen("top -n 2 -b").read().strip() return re.search(r"Cpu\(s\)[\w\W]*Cpu\(s\):\s*([\d\.]*) us", s).group(1) while True: print('使用率:%s%%\t 温度:%s°C' % (get_cpu_used(), get_cpu_temp())) # time.sleep(1)
true
4694e13493175947b62fd7beeeb5ec007686e132
Python
ivaneyvieira/pythonJango
/json_grava.py
UTF-8
124
2.75
3
[]
no_license
import json arquivo = open('arquivo.json', 'w') json.dump(32.3, arquivo) json.dump([1, 4, 5, 6], arquivo) arquivo.close()
true
bd47b72ace3ef8bdbc7a84ce82da527e34e1c750
Python
rasql/tk-tutorial
/docs/intro/intro.py
UTF-8
828
3.15625
3
[]
no_license
import tkinter as tk import tkinter.ttk as ttk class Label(ttk.Label): """Create a Label object.""" def __init__(self, text='Label', **kwargs): super().__init__(App.stack[-1], text=text, **kwargs) self.grid() class Button(ttk.Button): """Create a Button object.""" def __init__(self, text='Button', **kwargs): super().__init__(App.stack[-1], text=text, **kwargs) self.grid() class App: """Define the application class.""" stack = [] def __init__(self): self.root = tk.Tk() self.root.title('App') App.stack.append(self.root) Label('New Label') Label() Button('New Button') Button() def run(self): """Run the main loop.""" self.root.mainloop() if __name__ == '__main__': App().run()
true
aadf29724c85cf48545a2b16b0a30418f400cff5
Python
alon-benari/NewLariat
/LariatProject/LariatApp/forms.py
UTF-8
5,614
2.640625
3
[]
no_license
from django import forms from .models import Patient class PatientForm(forms.ModelForm): """ A form to capture data from a patient """ YES = 1 NO = 0 MALE = 0 FEMALE = 1 ONE = 0;TWO = 1;THREE = 2;FOUR = 3;FIVE=4 YES_NO= ((YES,'yes'),(NO,'no')) GENDER = ((MALE,'male'),(FEMALE,'female')) # mobility_options = ((ONE,'Can get around without any help'), (TWO,'Needs help from a cane/walker/scooter'), (THREE,'Needs help from other to get around the house or neighborhood'), (FOUR,'Needs help getting in or out of a chair'), (FIVE,'Totally dependent on other to get around')) # eating_options = ((ONE,'Can plan and prepare his/her own meals'), (TWO,'Needs help planning his/her meals'), (THREE,'Needs preparing his/her meals'), (FOUR,'Needs help eating his.her meals'), (FIVE,'Totally dependent on others to eat his/her meals')) # toilet_options = ((ONE,'Can use the toilet without help'), (TWO,'Needs help getting to or from toilet'), (THREE,'Needs help to use toilet paper'), (FOUR,'Cannot use standard toilet , but with help can use badpan/urinal'), (FIVE,'Totally dependent on others to manage toileting')) # hygiene_options = ((ONE,'Can shower or bath without prompting or help'), (TWO,'Can shower or bath without help when prompted'), (THREE,'Needs help preparing the tub or shower'), (FOUR,'Needs some help with some elements of washing'), (FIVE,'Totally dependent on others to shower or bathe')) # ####### first_name = forms.CharField(label = 'First Name',max_length = 50) middle_initial = forms.CharField(label = 'Middle initial',max_length = 1) last_name = forms.CharField(label = 'Last Name',max_length = 50) SSN = forms.CharField(label = 'SSN',max_length=9) age = forms.IntegerField() # female = forms.ChoiceField( choices = GENDER, required=True, widget = forms.RadioSelect(), label= 'Gender') # snf = forms.ChoiceField( choices = YES_NO, required=True, widget = forms.RadioSelect(), label= 'Does the patient live in an assited living/nursing home environment?') nephrologist = forms.ChoiceField( choices = YES_NO, required=True, widget = forms.RadioSelect(), label = 'Has the patient ever seen a nephrologist or has a history of kidney disease?') # chf = forms.ChoiceField( choices = YES_NO, required=True, widget = forms.RadioSelect(), label = 'Does the patient has chronic (long-standing) congestive heart failure?') # sob = forms.ChoiceField( choices = YES_NO, required=True, widget = forms.RadioSelect(), label = 'Does the patient CURRENTLY have shortness of breath at rest or mininal activity?') # cancer = forms.ChoiceField( choices = YES_NO, required=True, widget = forms.RadioSelect(), label = 'Was the patient treated in the past 5 years for cancer?') # weight_loss = forms.ChoiceField( choices = YES_NO, required=True, widget = forms.RadioSelect(), label = 'In the past 3 months, has the patient lost 10 pounds or more unintentionally?') # appetite = forms.ChoiceField( choices = YES_NO, required=True, widget = forms.RadioSelect(), label = 'Is the patient appetite currently poor?') memory = forms.ChoiceField( choices = YES_NO, required = True, widget = forms.RadioSelect(), label = 'During the last 3 months, has it become more difficult for the patient to remember things/organize thoughts') mobility = forms.ChoiceField(choices = mobility_options, required = True, widget = forms.RadioSelect(), label = 'Mobility:Activity of daily living: please select the most appropriate') # eating = forms.ChoiceField(choices = eating_options, required = True, widget = forms.RadioSelect(), label = 'Eating: please select the most appropriate') # # toileting = forms.ChoiceField(choices = toilet_options, required = True, widget = forms.RadioSelect(), label = 'Personal toileting: please select the most appropriate') # # hygiene = forms.ChoiceField(choices = hygiene_options, required = True, widget = forms.RadioSelect(), label = 'Personal hygiene: please select the most appropriate') # class Meta: model= Patient fields = ('female','first_name','middle_initial','last_name','age', 'SSN','snf','nephrologist','chf','sob','cancer', 'weight_loss','appetite','memory','mobility','eating','toileting','hygiene')
true
dd6dd0657475d3472b26a3471b0f9607616ac6b0
Python
muhrin/apricotpy
/apricotpy/messages.py
UTF-8
6,907
3.15625
3
[ "MIT" ]
permissive
from collections import namedtuple import threading import re _WilcardEntry = namedtuple("_WildcardEntry", ['re', 'listeners']) class Mailman(object): """ A class to send messages to listeners Messages send by this class: * mailman.listener_added.[subject] * mailman.listener_removed.[subject] where subject is the subject the listener is listening for """ @staticmethod def contains_wildcard(event): """ Does the event string contain a wildcard. :param event: The event string :type event: str or unicode :return: True if it does, False otherwise """ return event.find('*') != -1 or event.find('#') != -1 def __init__(self, loop): """ :param loop: The event loop :type loop: :class:`apricotpy.AbstractEventLoop` """ self.__loop = loop self._specific_listeners = {} self._wildcard_listeners = {} self._listeners_lock = threading.Lock() def add_listener(self, listener, subject='*'): """ Start listening to a particular event or a group of events. :param listener: The listener callback function to call when the event happens :param subject: A subject string :type subject: str or unicode """ if subject is None: raise ValueError("Invalid event '{}'".format(subject)) with self._listeners_lock: self._check_listener(listener) if self.contains_wildcard(subject): self._add_wildcard_listener(listener, subject) else: self._add_specific_listener(listener, subject) def remove_listener(self, listener, subject=None): """ Stop listening for events. If event is not specified it is assumed that the listener wants to stop listening to all events. :param listener: The listener that is currently listening :param subject: (optional) subject to stop listening for :type subject: str or unicode """ with self._listeners_lock: if subject is None: # This means remove ALL messages for this listener for evt in self._specific_listeners.keys(): self._remove_specific_listener(listener, evt) for evt in self._wildcard_listeners.keys(): self._remove_wildcard_listener(listener, evt) else: if self.contains_wildcard(subject): try: self._remove_wildcard_listener(listener, subject) except KeyError: pass else: try: self._remove_specific_listener(listener, subject) except KeyError: pass def clear_all_listeners(self): with self._listeners_lock: self._specific_listeners.clear() self._wildcard_listeners.clear() def num_listening(self): """ Get the number of events that are being listening for. This corresponds exactly to the number of .start_listening() calls made this this emitter. :return: The number of events listened for :rtype: int """ with self._listeners_lock: total = 0 for listeners in self._specific_listeners.itervalues(): total += len(listeners) for entry in self._wildcard_listeners.itervalues(): total += len(entry.listeners) return total def send(self, subject, body=None): """ Send a message :param subject: The message subject :param body: The body of the message """ # These loops need to use copies because, e.g., the recipient may # add or remove listeners during the delivery # Deal with the wildcard listeners for evt, entry in self._wildcard_listeners.items(): if self._wildcard_match(evt, subject): for l in list(entry.listeners): self._deliver_msg(l, subject, body) # And now with the specific listeners try: for l in self._specific_listeners[subject].copy(): self._deliver_msg(l, subject, body) except KeyError: pass def specific_listeners(self): return self._specific_listeners def wildcard_listeners(self): return self._wildcard_listeners def _deliver_msg(self, listener, event, body): self.__loop.call_soon(listener, self.__loop, event, body) @staticmethod def _check_listener(listener): if not callable(listener): raise ValueError("Listener must be callable") # Can do more sophisticated checks here, but it's a pain (to check both # classes that are callable having the right signature and plain functions) def _add_wildcard_listener(self, listener, subject): if subject in self._wildcard_listeners: self._wildcard_listeners[subject].listeners.add(listener) else: # Build the regular expression regex = subject.replace('.', '\.').replace('*', '.*').replace('#', '.+') self._wildcard_listeners[subject] = _WilcardEntry(re.compile(regex), {listener}) self.send('mailman.listener_added.{}'.format(subject)) def _remove_wildcard_listener(self, listener, subject): """ Remove a wildcard listener. Precondition: listener in self._wildcard_listeners[event] :param listener: The listener to remove :param subject: The subject to stop listening for """ self._wildcard_listeners[subject].listeners.discard(listener) if len(self._wildcard_listeners[subject].listeners) == 0: del self._wildcard_listeners[subject] self.send('mailman.listener_removed.{}'.format(subject)) def _add_specific_listener(self, listener, subject): self._specific_listeners.setdefault(subject, set()).add(listener) self.send('mailman.listener_added.{}'.format(subject)) def _remove_specific_listener(self, listener, subject): """ Remove a specific listener. Precondition: listener in self._specific_listeners[event] :param listener: The listener to remove :param subject: The subject to stop listening for """ self._specific_listeners[subject].discard(listener) if len(self._specific_listeners[subject]) == 0: del self._specific_listeners[subject] self.send('mailman.listener_removed.{}'.format(subject)) def _wildcard_match(self, event, to_match): return self._wildcard_listeners[event].re.match(to_match) is not None
true
6e88f65740323784be16d36b066e9e65322549a5
Python
doubledave/botxxy
/src/skeleton.py
UTF-8
3,424
3.03125
3
[]
no_license
# Import the necessary libraries. import socket import ssl import time from mylib import myprint, unescape # Some basic variables used to configure the bot server = "boxxybabee.catiechat.net" # EU server #server = "anewhopeee.catiechat.net" # US server port = 6667 # default port ssl_port = 6697 # ssl port chans = ["#test"] #default channels botnick = "feature-test" # bot nick botuser = "tuser" bothost = "thost" botserver = "tserver" botname = "tname" botpassword = "" #============BASIC FUNCTIONS TO MAKE THIS A BIT EASIER=============== def ping(reply): # This is our first function! It will respond to server Pings. ircsock.send("PONG :%s\n" % (reply)) # In some IRCds it is mandatory to reply to PING the same message we recieve #myprint("PONG :%s" % (reply)) def sendChanMsg(chan, msg): # This sends a message to the channel 'chan' ircsock.send("PRIVMSG %s :%s\n" % (chan, msg.encode("utf8"))) def sendNickMsg(nick, msg): # This sends a notice to the nickname 'nick' ircsock.send("NOTICE %s :%s\n" % (nick, msg.encode("utf8"))) def getNick(msg): # Returns the nickname of whoever requested a command from a RAW irc privmsg. Example in commentary below. # ":b0nk!LoC@fake.dimension PRIVMSG #test :lolmessage" return msg.split('!')[0].replace(':','') def getUser(msg): # Returns the user and host of whoever requested a command from a RAW irc privmsg. Example in commentary below. # ":b0nk!LoC@fake.dimension PRIVMSG #test :lolmessage" return msg.split(" PRIVMSG ")[0].translate(None, ':') def getChannel(msg): # Returns the channel from whereever a command was requested from a RAW irc PRIVMSG. Example in commentary below. # ":b0nk!LoC@fake.dimension PRIVMSG #test :lolmessage" return msg.split(" PRIVMSG ")[-1].split(' :')[0] def joinChan(chan): # This function is used to join channels. ircsock.send("JOIN %s\n" % (chan)) def joinChans(chans): # This is used to join all the channels in the array 'chans' for i in chans: ircsock.send("JOIN %s\n" % (i)) def hello(msg): # This function responds to a user that inputs "Hello botxxy" nick = getNick(msg) chan = getChannel(msg) myprint("%s said hi in %s" % (nick, chan)) sendChanMsg(chan, "Hello %s!" % (nick)) #========================END OF BASIC FUNCTIONS===================== # Connection ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ircsock = ssl.wrap_socket(ircsock) # SSL wrapper for the socket ircsock.connect((server, ssl_port)) # Here we connect to the server using the port defined above time.sleep(2) ircsock.send("USER %s %s %s %s\n" % (botuser, bothost, botserver, botname)) # Bot authentication ircsock.send("NICK %s\n" % (botnick) ) # Here we actually assign the nick to the bot time.sleep(2) joinChans(chans) while 1: # This is our infinite loop where we'll wait for commands to show up, the 'break' function will exit the loop and end the program thus killing the bot ircmsg = ircsock.recv(1024) # Receive data from the server ircmsg = ircmsg.strip('\n\r') # Removing any unnecessary linebreaks myprint (ircmsg) # Here we print what's coming from the server if "PING :" in ircmsg: # If the server pings us then we've got to respond! reply = ircmsg.split("PING :")[1] # In some IRCds it is mandatory to reply to PING the same message we recieve ping(reply) if ":hello " + botnick in ircmsg.lower(): # If we can find "Hello botnick" it will call the function hello() hello(ircmsg)
true
54f5d8a4326c494ed92034adb96e44a41c2009b3
Python
lucianofalmeida/Desafios_Python
/desafio057.py
UTF-8
125
3.265625
3
[]
no_license
tupla = ("carro","moto") tupla[0]= 'bike' print(tupla) #o erro acontece pq as tuplas não suportam atribuição de itens
true
6556b491357f364af329c98a88710bb8f1c5bdb4
Python
ePlusPS/nexus9000
/nexusscripts/off-box/cleanup/nexus_delbootflash.py
UTF-8
1,969
2.578125
3
[]
no_license
"""Script Cataloging Information :Product Info:Nexus::9000::9516::NX-OS Release 6.2 :Category:Cleanup :Box Type:Off-Box :Title:Nexus Configuration Cleanup :Short Description:To delete the switch bootflash configurations :Long Description:Delete the switch bootflash configurations :Input:command to delete the configurations :Output:Nexus switch is cleaned up from bootflash scripts """ import os import requests import json import ConfigParser #read the nexus configuration file config=ConfigParser.ConfigParser() config.read('nexus_cleanup.cfg') ipaddress = config.get('HostDetails', 'ipaddress') username = config.get('HostDetails', 'username') password = config.get('HostDetails', 'password') #check the configuration details if (ipaddress == ''): print "Please update the configuration file with Switch IPAddress" exit(1) if ((username and password) == ''): print "Please update the configuration file with Switch User Credentials" exit(1) elif (username == ''): print "Please update the configuration file with Switch User Creentials " exit(1) elif (password == ''): print "Please update the configuration file with Switch User Credentials " exit(1) """ Delete Bootflash script """ class Nexus_DelBootFlash: myheaders = {'content-type':'application/json-rpc'} url = "http://"+ipaddress+"/ins" def nexus_delbootflash(self): #execute the commands payload=[{"jsonrpc": "2.0","method": "cli","params": {"cmd": "conf t","version": 1},"id": 1}, {"jsonrpc": "2.0","method": "cli","params": {"cmd": "terminal dont-ask","version": 1},"id": 2}, {"jsonrpc": "2.0","method": "cli","params": {"cmd": "delete bootflash:scripts","version": 1},"id": 3}] response = requests.post(Nexus_DelBootFlash.url,data=json.dumps(payload), headers=Nexus_DelBootFlash.myheaders,auth=(username,password)).json() print response if __name__ == '__main__': ob = Nexus_DelBootFlash() ob.nexus_delbootflash()
true
db7f624d92cc5231802b3693a45fc4c1e2ad9f54
Python
sherld/LeetCodeForPython
/Solutions/GenerateParentheses.py
UTF-8
688
3.34375
3
[]
no_license
class Solution: def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ if n == 0: return [] ret = [] self.buildParenthesis(ret, '', 0, n) return ret def buildParenthesis(self, ret, s, existedNum, remainNum): if existedNum == 0 and remainNum == 0: ret.append(s) return if remainNum > 0: self.buildParenthesis(ret, s + '(', existedNum + 1, remainNum - 1) if existedNum > 0: self.buildParenthesis(ret, s + ')', existedNum - 1, remainNum) if __name__ == '__main__': print(Solution().generateParenthesis(3))
true
493eb4573927979a9a46fdfc477a18d7a21677d6
Python
huangciyin/ashley-madison-dox
/amdoxx/queries.py
UTF-8
3,357
2.5625
3
[ "MIT" ]
permissive
import MySQLdb as mysql import util from members import AmMember class AmQuery(): def __init__(self): self.conn = mysql.connect('localhost', user='am_username', passwd='am_password', db='am') def search_email(self, email): """Find a member based on their email, or None if email does not exist""" email = util.sql_escape(email) result = util.fetch_first_or_none(self.conn.cursor(), "select id, email, first_name, last_name " + "from am_am_member inner join aminno_member_email " + "on am_am_member.id = aminno_member_email.pnum " + "where aminno_member_email.email = '" + email + "';") return AmMember(self.conn, *result) if result is not None else None def search_first_last(self, fname, lname): """Find a member based on their first and last name, or None if not exist""" fname, lname = tuple(map(lambda s: util.sql_escape(s), [fname, lname])) result = util.fetch_first_or_none(self.conn.cursor(), "select id, email, first_name, last_name " + "from am_am_member inner join aminno_member_email " + "on am_am_member.id = aminno_member_email.pnum " + "where am_am_member.first_name = '" + fname + "'" + "and am_am_member.last_name = '" + lname + "';") return AmMember(self.conn, *result) if result is not None else None def closest_to(self): """Find closest users to point within certain radius""" # TODO: implement these as function parameters lat, lon = 40.419358, -86.877356 limit = 10 max_radius_in_miles = 100 result = util.fetchall(self.conn.cursor(), "SELECT id, first_name, last_name, email, " + "X(location) AS lat, Y(location) AS lng, " + # 3959 sets distance to miles "(3959 * " + "acos(" + "cos( radians(%f) )" % lat + "* cos( radians( X(location) ) ) " + "* cos( radians( Y(location) ) - radians(%f) )" % lon + "+ sin( radians(%f) ) " % lat + "* sin( radians( X(location) ) ) ) ) AS distance " + "FROM am_spatial_lookup " + "INNER JOIN am_am_member " + "ON am_am_member.id = am_spatial_lookup.pnum " + "INNER JOIN aminno_member_email " + "ON am_am_member.id = aminno_member_email.pnum " + "WHERE last_name IS NOT NULL " + "AND last_name != '<paid_delete>' " + "HAVING distance <= %f " % max_radius_in_miles + "ORDER BY distance ASC " + "LIMIT %d;" % limit) return tuple(result)
true
daabffb832d1e89c41d858c919495d586062e791
Python
mingzhu-wu/self-labeling-coref-annotation
/self-labeling/gender.py
UTF-8
1,525
3.40625
3
[]
no_license
from nltk.corpus import names from nltk.classify import apply_features import nltk import random class GenderRecoginition: """ use nltk classfication to identify gender. """ def gender_features(self, word): return { 'first-letter': word[0], # First letter 'first2-letters': word[0:2], # First 2 letters 'first3-letters': word[0:3], # First 3 letters 'last-letter': word[-1], 'last2-letters': word[-2:], 'last3-letters': word[-3:], } def gender_identify(self, word, isPrint): # featuresets = [(gender_features(n), gender) for (n, gender) in labeled_names] # train_set, test_set = featuresets[500:], featuresets[:500] labeled_names = ([(name, 'male') for name in names.words('male.txt')] + [(name, 'female') for name in names.words('female.txt')]) random.shuffle(labeled_names) train_set = apply_features(self.gender_features, labeled_names[500:]) test_set = apply_features(self.gender_features, labeled_names[:500]) classifier = nltk.NaiveBayesClassifier.train(train_set) if isPrint: print("gender recognise accuracy is " + str(nltk.classify.accuracy(classifier, test_set))) return classifier.classify(self.gender_features(word)) if __name__ == '__main__': genderRec = GenderRecoginition() print(genderRec.gender_identify("Lucy Green", True))
true
3ddaad23b87d9f03837867408cb59788916847f9
Python
lonesloane/Python-Snippets
/Design_Patterns/Creational/Factory/ShapeFactory.py
UTF-8
554
3.46875
3
[]
no_license
class IShape: def draw(self): pass class Circle(IShape): def draw(self): print('Circle drawn') class Square(IShape): def draw(self): print('Square drawn') class ShapeFactory: @staticmethod def get_shape(shape_type): if shape_type == 'circle': return Circle() if shape_type == 'square': return Square() assert 0, 'Could not recognize shape ' + shape_type f = ShapeFactory() f.get_shape('square').draw() f.get_shape('circle').draw() f.get_shape('triangle').draw()
true
8d9eb70225b7ffd85708c3ed9fcd7c8caebe7d0f
Python
eyallev25/docker_api_exercise
/tests/support/docker_utils.py
UTF-8
2,863
2.84375
3
[]
no_license
import docker import time import concurrent.futures images_list = [ 'bfirsh/reticulate-splines', 'nginx' ] client = docker.from_env() # Instantiate docker client timeout = 30 # Seconds def print_container_stats(): """Main method, allocate a new thread for each image from image_list and print stats when done. Arguments: """ with concurrent.futures.ThreadPoolExecutor() as executor: results = executor.map(pull_image_and_run_container, images_list) for result in results: print(f"For image name: '{result.image_name}' the max mem usage is: {result.max_mem}, and max cpu usage is:" f" {result.max_cpu}") def pull_image_and_run_container(image_name): """Pull image from dockerhub, run docker container and find max metrics. Arguments: image_name (str) : The image name. Return: container_response (object) : The container metrics. """ container_response = ContainerResponse(image_name) image = get_images_from_dockerhub(image_name) container = client.containers.run(image, detach=True) timeout_start = time.time() # TODO While container is still running. while time.time() < timeout_start + timeout: mem_usage, total_cpu_usage = _get_container_stats(container) container_response.max_mem_usage(mem_usage) container_response.max_cpu_usage(total_cpu_usage) # stop container. container.stop() return container_response def get_images_from_dockerhub(image_name): """Pull image from dockerhub. Arguments: image_name (str) : The image name. Return: image (object) : The image. """ image = client.images.pull(image_name) return image def _get_container_stats(container): """Pull image from dockerhub. Arguments: container (object) : The container object. Return: mem_usage (int) : container's mem usage metric. total_cpu_usage (int) : container's total cpu usage metric. """ status = container.stats(decode=None, stream=False) mem_usage = status['memory_stats']['usage'] total_cpu_usage = status['cpu_stats']['cpu_usage']['total_usage'] return mem_usage, total_cpu_usage class ContainerResponse: def __init__(self, image_name): self.image_name = image_name self.max_mem = 0 self.max_cpu = 0 self.container_id = "" def max_mem_usage(self, mem_usage): if mem_usage > self.max_mem: self.max_mem = mem_usage def max_cpu_usage(self, cpu_usage): if cpu_usage > self.max_cpu: self.max_cpu = cpu_usage if __name__ == '__main__': print_container_stats()
true
ba86f7fabc060bfc6dd61da552239783d8999533
Python
albertogeniola/MerossIot
/meross_iot/model/plugin/light.py
UTF-8
2,184
2.8125
3
[ "MIT" ]
permissive
from typing import Union, Optional, Tuple from meross_iot.model.typing import RgbTuple from meross_iot.utilities.conversion import int_to_rgb, rgb_to_int class LightInfo(object): def __init__(self, rgb: Union[int, Tuple[int, int, int]] = None, luminance: int = None, temperature: int = None, capacity: int = None, onoff: int = None): self._rgb = self._convert_rgb(rgb) self._luminance = luminance self._temperature = temperature self._capacity = capacity self._onoff = onoff @property def rgb_tuple(self) -> Optional[Tuple[int, int, int]]: return self._rgb @property def rgb_int(self) -> Optional[int]: if self._rgb is not None: return rgb_to_int(self._rgb) return None @property def luminance(self) -> Optional[int]: return self._luminance @property def temperature(self) -> Optional[int]: return self._temperature @property def is_on(self) -> Optional[bool]: if self._onoff is not None: return self._onoff == 1 return None def update(self, rgb: Union[int, RgbTuple] = None, luminance: int = None, temperature: int = None, capacity: int = None, onoff: int = None, *args, **kwargs): if rgb is not None: self._rgb = self._convert_rgb(rgb) if luminance is not None: self._luminance = luminance if temperature is not None: self._temperature = temperature if capacity is not None: self._capacity = capacity if onoff is not None: self._onoff = onoff @staticmethod def _convert_rgb(rgb: Union[int, tuple]): if rgb is None: return None if isinstance(rgb, int): return int_to_rgb(rgb) elif isinstance(rgb, tuple): return rgb else: raise ValueError("rgb value must be either an integer or a (red, green. blue) integers (0-255) tuple.")
true
9abef191e3e2942ae1373693d3a0299755d0f9e4
Python
SimleCat/assignment
/python/20150313/A5.py
UTF-8
2,118
3.203125
3
[]
no_license
from simpleai.search import SearchProblem, genetic # from simpleai.search.viewers import ConsoleViewer import random class KnapsackProblem(SearchProblem): def __init__(self, numObjects, maxWeight, weights, values, initial_state=None): super(KnapsackProblem, self).__init__(initial_state) self.numObjects = numObjects self.maxWeight = maxWeight self.weights = weights self.values = values; def generate_random_state(self): r = range(self.numObjects) choice = [1] * self.numObjects while not self._valid(choice): k = random.randint(1, self.numObjects) x = random.sample(r, k) for i in x: choice[i] = 0 return choice def crossover(self, s, t): cnt = 1 k = random.randint(1, numObjects-1) y = s[:k] + t[k:] while not self._valid(y): if cnt > numObjects: return s cnt += 1 k = random.randint(1, numObjects-1) y = s[:k] + t[k:] return y def mutate(self, s): valid = False n = -1 cnt = 0 s_pre = s while not valid: s = s_pre if cnt > numObjects: break n = random.randint(0, numObjects-1) m = random.randint(0, numObjects-1) if s[n]+s[m] == 1: if not s[n]: s[n] = 1 s[m] = 0 else: s[n] = 0 s[m] = 1 valid = self._valid(s) cnt += 1 return s def value(self, s): v = 0 for index, item in enumerate(s): if item == 1: v += self.values[index] return v def _weight(self, s): weight = 0 for index, item in enumerate(s): if item == 1: weight += self.weights[index] return weight def _valid(self, s): if self._weight(s) > maxWeight: return False return True if __name__ == "__main__": numObjects = 20 weights = [4, 6, 5, 5, 3, 2, 4, 8, 1, 5, 3, 7, 2, 5, 6, 3, 8, 4, 7, 2] values = [5, 6, 2, 8, 6, 5, 8, 2, 7, 6, 1, 3, 4, 4, 1, 5, 6, 2, 5, 3] maxWeight = 35 problem = KnapsackProblem(numObjects, maxWeight, weights, values) result = genetic(problem, iterations_limit=100, population_size=16, mutation_chance=0.10) print result.path() print 'Weight = ' + str(problem._weight(result.path()[0][1])) print 'Value = ' + str(problem.value(result.path()[0][1]))
true
c59196ee45699ad690ef5b1c6e1d9e2186a02c43
Python
yusufbenliii/Image-to-Text
/draw.py
UTF-8
3,570
2.8125
3
[]
no_license
from tkinter import * from PIL import Image, ImageGrab import pytesseract as tess import clipboard import pyautogui class ScreenShootDisplay: def __init__(self): self.root = Tk() self.root.title("Ss") path = "cut.ico" try: self.root.iconbitmap(r'cut.ico') except Exception as e: print(e) self.root.attributes('-alpha', 0.2) self.root.attributes('-fullscreen', True) w , h = self.root.winfo_screenwidth(),self.root.winfo_screenheight() self.root.geometry(f"{w}x{h}") self.canvas = Canvas( self.root, width=w, height=h, highlightbackground="black", bg= 'black' ) self.canvas.pack() self.is_packed = False self.is_released = True self.is_clicked = False self.root.bind("<Button-1>", self.click) self.root.bind("<ButtonRelease-1>", self.release) self.root.bind("<Motion>", self.motion) self.root.bind("<Key>", self.key_events) self.root.bind("<Escape>", self.exit) tess.pytesseract.tesseract_cmd = r"C:\\Program Files\\Tesseract-OCR\\tesseract.exe" self.root.mainloop() def exit(self, event): self.root.quit() def clear(self): self.canvas.delete("all") self.canvas.pack() self.root.attributes('-alpha', 0) def key_events(self, event): if event.char == "s": self.is_packed = True if event.char == "m": self.root.iconify() def motion(self, event): if self.is_clicked and not self.is_released and self.is_packed: self.draw_rect(self.start_x, self.start_y, event.x, event.y) def release(self, event): self.canvas.delete("all") if self.is_packed: self.root.iconify() self.screenshot(self.start_x, self.start_y, event.x, event.y) self.is_packed = False self.is_released = True self.is_clicked = False def click(self, event): self.is_released = False self.is_clicked = True self.start_x = event.x self.start_y = event.y def draw_rect(self, x1, y1, x2, y2): self.canvas.delete("all") self.canvas.create_rectangle((x1, y1, x2, y2),fill="ghostwhite") # gray99 self.canvas.pack() def screenshot(self, x1, y1, x2, y2): try: box = self.create_box(x1, y1, x2, y2) img = ImageGrab.grab(bbox=box, all_screens=True) basewidth = 1920 wpercent = (basewidth/float(img.size[0])) hsize = int((float(img.size[1])*float(wpercent))) img = img.resize((basewidth, hsize), Image.ANTIALIAS) img.save("images/image.PNG") text = tess.image_to_string(img) self.write_to_file(text) except Exception as e: print(e, "error occured while reading image") pass def create_box(self, x1, y1, x2, y2): x_lst = [x1, x2] y_lst = [y1, y2] x_lst.sort() y_lst.sort() box = (x_lst[0], y_lst[0], x_lst[1], y_lst[1]) return box def write_to_file(self, text): text = text[:-2] text = text.translate({8221: '"'}) text = text.translate({ord('“'): '"'}) text = text.translate({ord('‘'): "'"}) text = text.translate({ord('’'): "'"}) clipboard.copy(text) with open("output.txt", "w") as f: f.write(text) f.close() if __name__ == '__main__': app = ScreenShootDisplay()
true
abb681dcf41e156fcd8c84fa87c5ae6cc3798154
Python
bgmacris/100daysOfCode
/Day95/act5.py
UTF-8
544
4.15625
4
[]
no_license
""" Escribir una función que reciba un DataFrame con el formato del ejercicio anterior, una lista de meses, y devuelva el balance (ventas - gastos) total en los meses indicados. """ import pandas as pd def gastos(datos, meses): datos['Balance'] = datos.Ventas - datos.Gastos return datos[datos.Mes.isin(meses)].Balance.sum() datos = pd.DataFrame({ 'Mes': ['Enero', 'Febrero', 'Marzo', 'Abril'], 'Ventas': [30500, 35600, 28300, 33900], 'Gastos': [22000, 23400, 18100, 20700] }) print(gastos(datos, ['Enero', 'Febrero']))
true
86076f64c26fa4a56ebd8875dc764cd4365088c4
Python
nunomota/spatial-inequality
/spatial_inequality/optimization/run_metrics.py
UTF-8
12,632
2.953125
3
[ "MIT" ]
permissive
""" Structured information container, to track specified metrics over a single run of our algorithm. """ import json import copy from time import time class RunMetrics: """ This class is used to track metrics over a single run of the redistricting algorithm (done over a single state). Most of its methods are intended to be used as callbacks at specific points of its iterations. Attributes: __per_student_funding_whole_state (float): Per-student funding across the state. __spatial_inequality_values (list of float): List of inequality values, registered throughout the algorithm's run. __percentage_of_schools_redistricted (list of float): List of percentages of schools redistricted at each iteration of the algorithm, compared to their initial assignment. __number_of_districts (list of int): List of absolute number of existing district at each iteration. __move_history (list of tuple): List of all redistricting moves performed throughout the algorithm's run, containing a school's standardized NCES ID, a source district's standardized NCES ID, and a destination district's standardized NCES ID. __district_assignment_by_school_id (dict of str: dict): Mapping between a checkpoint label (i.e., 'before' or 'after') and the corresponding school/district assignment. __per_student_funding_by_district_id (dict of str: dict): Mapping between a checkpoint label (i.e., 'before' or 'after') and the corresponding per-student funding. """ # One time measurements __per_student_funding_whole_state = None # Lists of overtime measurements __spatial_inequality_values = None __percentage_of_schools_redistricted = None __number_of_districts = None __move_history = None # Before/after comparison measurements __district_assignment_by_school_id = None __per_student_funding_by_district_id = None # One time metrics __start_timestamp = None __end_timestamp = None def __init__(self): # Overtime measurement initialization self.__spatial_inequality_values = [] self.__percentage_of_schools_redistricted = [] self.__number_of_districts = [] self.__move_history = [] # Before/after measurement initialization self.__district_assignment_by_school_id = {} self.__per_student_funding_by_district_id = {} def on_init(self, schools, districts, lookup): """ Initializes necessary class' attributes and stores initial metrics' values (prior to the algorithm's iterations). This method should be called immediately after school/district assignment is finalized. Args: schools (list of optimization.entity_nodes.School): List of all initialized School instances. districts (list of optimization.entity_nodes.District): List of all initialized District instances. lookup (optimization.lookup.Lookup): Lookup instance. """ # Calculate average funding per student total_funding_in_state = sum(map(lambda x: x.get_total_funding(), districts)) total_students_in_state = sum(map(lambda x: x.get_total_students(), districts)) # Update variables self.__per_student_funding_whole_state = total_funding_in_state / total_students_in_state self.__checkpoint_before_and_after_measurements(schools, districts, lookup, "before") self.__start_timestamp = time() def on_end(self, schools, districts, lookup): """ Initializes necessary class' attributes and stores final metrics' values (after the algorithm concludes its run). This method should be called at the end of the algorithm's last iteration. Args: schools (list of optimization.entity_nodes.School): List of all initialized School instances. districts (list of optimization.entity_nodes.District): List of all initialized District instances. lookup (optimization.lookup.Lookup): Lookup instance. """ self.__checkpoint_before_and_after_measurements(schools, districts, lookup, "after") self.on_update(schools, districts, lookup) self.__end_timestamp = time() def on_update(self, schools, districts, lookup): """ Updates necessary class' attributes and calculates runtime metrics' values (during the algorithm's run). This method should be called at the end of each of the algorithm's iterations. Args: schools (list of optimization.entity_nodes.School): List of all initialized School instances. districts (list of optimization.entity_nodes.District): List of all initialized District instances. lookup (optimization.lookup.Lookup): Lookup instance. """ # Calculate inequality cur_inequality = self.__calculate_inequality(districts, lookup) self.__spatial_inequality_values.append(cur_inequality) # Calculate percentage of redistricted schools cur_percentage = self.__calculate_percentage_of_schools_redistricted(schools, lookup) self.__percentage_of_schools_redistricted.append(cur_percentage) # Calculate number of districts self.__number_of_districts.append(len(districts)) def on_move(self, iteration_idx, moves): """ Registers all redistricting moves performed during one of the algorithm's iterations. This method should be called during any/all of the algorithm's iterations, immediately after schools are effectively redistricted. If schools are not redistricted, this method needs not be called. Args: iteration_idx (int): Current iteration's index (needs not be a continuous variable). moves (list of tuple): List of all moves performed during the current iteration of the algorithm (i.e., tuples comprised of a redistricted school standardized NCES ID, its source district standardized NCES ID and its destination district standardized NCES ID). """ for move in moves: # Get configuration school_id = move[0] from_district_id = move[1] to_district_id = move[2] # Add move to moves' history self.__move_history.append(( iteration_idx, school_id, from_district_id, to_district_id )) def as_dict(self): """ Creates a dictionary containing all metrics tracked. Returns: dict: Resulting dictionary with tracked metrics. """ return { # Overtime measurements "spatial_inequality": copy.copy(self.__spatial_inequality_values), "percentage_of_schools_redistricted": copy.copy(self.__percentage_of_schools_redistricted), "number_of_districts": copy.copy(self.__number_of_districts), "move_history": copy.copy(self.__move_history), # Before/after measurements "district_assignment_by_school_id": copy.copy(self.__district_assignment_by_school_id), "per_student_funding_by_district_id": copy.copy(self.__per_student_funding_by_district_id), # One time measurements "time_elapsed": self.__end_timestamp - self.__start_timestamp, "per_student_funding_whole_state": self.__per_student_funding_whole_state } def to_file(self, filepath): """ Writes all tracked metrics to a JSON-formatted file. Args: filepath (str): Full path for output file, including filename and extension. """ with open(filepath, "w") as file: json.dump(self.as_dict(), file) def __len__(self): return len(self.__spatial_inequality_values) def __checkpoint_before_and_after_measurements(self, schools, districts, lookup, label): """ Auxiliary method to handle class' attributes update/initialization upon the algorithm's start or end. Args: schools (list of optimization.entity_nodes.School): List of all initialized School instances. districts (list of optimization.entity_nodes.District): List of all initialized District instances. lookup (optimization.lookup.Lookup): Lookup instance. label (str): Should be 'before' or 'after'. Raises: AssertionError: Whenever there is an invalid school/district assignment, missing information on number of students or overall funding, or when an invalid label is provided. """ assert(self.__district_assignment_by_school_id is not None) assert(self.__per_student_funding_by_district_id is not None) assert(label == "before" or label == "after") # Initialize school assignment get_district_id = lambda school: lookup.get_district_by_school_id(school.get_id()).get_id() self.__district_assignment_by_school_id[label] = dict(map( lambda school: (school.get_id(), get_district_id(school)), schools )) # Initialize district funding get_per_student_funding = lambda district: district.get_total_funding() / district.get_total_students() self.__per_student_funding_by_district_id[label] = dict(map( lambda district: (district.get_id(), get_per_student_funding(district)), districts )) def __calculate_inequality(self, districts, lookup): """ Auxiliary method to calculate spatial inequality for current school/district assignment. Args: districts (list of optimization.entity_nodes.District): List of all initialized District instances. lookup (optimization.lookup.Lookup): Lookup instance. Returns: float: Spatial inequality index. """ get_per_student_funding = lambda district: district.get_total_funding() / district.get_total_students() abs_funding_diff = lambda x,y: abs(get_per_student_funding(x) - get_per_student_funding(y)) overall_inequality = 0 normalization_factor = 0 for district in districts: neighboring_districts = lookup.get_neighboor_districts_by_district_id(district.get_id()) full_neighborhood = [*neighboring_districts, district] ineq_contribution = sum(map( lambda x: abs_funding_diff(district, x), full_neighborhood )) overall_inequality += ineq_contribution / len(full_neighborhood) normalization_factor += get_per_student_funding(district) return overall_inequality / normalization_factor def __calculate_percentage_of_schools_redistricted(self, schools, lookup): """ Auxiliary method to calculate the percentage of schools that are currently redistricted (compared to their initial assignment). Args: districts (list of optimization.entity_nodes.School): List of all initialized School instances. lookup (optimization.lookup.Lookup): Lookup instance. Returns: float: Percentage of currently redistricted schools. """ # Get initial assignment initial_district_assignment = self.__district_assignment_by_school_id["before"] # Extract current assignment get_district_id = lambda school: lookup.get_district_by_school_id(school.get_id()).get_id() cur_district_assignment = dict(map( lambda school: (school.get_id(), get_district_id(school)), schools )) # Filter schools that were redistricted is_redistricted = lambda school: initial_district_assignment[school.get_id()] != cur_district_assignment[school.get_id()] schools_redistricted = list(filter( is_redistricted, schools )) # Return final percentage return 100 * len(schools_redistricted) / len(schools)
true
165199635871198db842d0e6be1425aad7f85153
Python
Haannbboo/JAQK
/build/lib/jaqk/operations/Open.py
UTF-8
4,062
2.921875
3
[ "MIT" ]
permissive
import os as _os import pandas as _pd import gc as _gc from ..operations.Path import path as _path from ..operations.Path import datapath def open_file(stock, name, setup=False): """ opener for opening sheets for client stock - company name (e.g AAPL for apple inc.) name - name of the sheet (e.g 'income' / 'balace'), use sheets_names() to see all names returns a csv sheet of the sheet of the company """ if not isinstance(stock, str): raise TypeError("Parameter 'stock' should be a string, not a " + type(stock).__name__) if setup is True: # when setup, name is "AAPL_income.csv", not "income" # path = _os.path.join(datapath(setup=False), stock, name) path = datapath(True, stock, name) df = _pd.read_csv(path) _gc.collect() return df # not setup, normal open_file names = ['major_holders', 'top_institutional_holders', 'top_mutual_fund_holders', 'Trading_Information', 'Financial_Highlights', 'Valuation_Measures', 'Executives', 'Description', 'Earnings_Estimate', 'Revenue_Estimate', 'Earnings_History', 'EPS_Trend', 'EPS_Revisions', 'Growth_Estimates', 'stats', 'statements', 'reports', 'Executives', 'Description', 'analysis', 'Summary', 'balance', 'cash_flow', 'income'] if name not in names: try: name = _path(name) # when client mistakenly input factor instead of sheet name except ValueError: raise ValueError( 'Parameter "name" should be the name of the financial sheets, not a factor name...Use path method to ' 'find the location of a factor') path = datapath(True, stock, stock) try: df = _pd.read_csv(path + '_' + name + '.csv') _gc.collect() except FileNotFoundError: _gc.collect() if _os.path.exists(datapath(True, stock)): raise ValueError("There is no sheet - {} - for company {}. Use main_get to retrieve the sheet".format (name, stock)) else: raise ValueError("There is no record of '" + stock + "' in database") return df def open_general(file, setup=False): """Read CSV in folder "general" in database. Also used in setup.py Args: file: str - file name, need '.csv'. setup: bool - setup flag, indicate usage by setup or not. Returns: df - dataframe of stock list if FileNotFound, print out suggestions """ try: if setup is False: p = datapath(True, 'general', file) df = _pd.read_csv(p + '.csv') elif setup is True: p = datapath(True, 'general', file) df = _pd.read_csv(p + '.py') else: df = None # not tested here return df except FileNotFoundError as e: print("There is no record of {} in your database. Go to your chosen setup path to check, if not there go to " "Github and download the missing sheet".format(file)) return None def open_stock_list(exchange='ALL'): """Read the stock list in database, a wrap up of open_general. Open stock list files in database using open_general() function. Args: exchange: str - default True (all stocks), or either NYSE or NASDAQ. Returns: a csv format file with ticket names (rows) vs [Open, Close, High, Close, Adj. Close, Vol] (columns) Raises: ValueError: error assessing exchange param. """ if exchange not in ['NYSE', 'NASDAQ'] and exchange != 'ALL': raise ValueError("Parameter 'exchange' should either NYSE or NASDAQ") if exchange == 'ALL': # all tickets c1 = open_general('NASDAQ') c2 = open_general('NYSE') df = _pd.concat([c1, c2], ignore_index=True).drop('Unnamed: 9', axis=1) # drop duplicated column else: _csv = open_general(exchange) df = _csv.drop('Unnamed: 9', axis=1) return df
true
f4ac523f052e6934988ae8051a34deba267300cc
Python
madokast/pythonLearn
/201901/timeLib.py
UTF-8
290
2.8125
3
[]
no_license
import time print(time.time()) #1547642050.57 print(time.ctime()) #Wed Jan 16 20:31:01 2019 print(time.gmtime()) #time.struct_time(tm_year=2019, tm_mon=1, tm_mday=16, # tm_hour=12, tm_min=34, tm_sec=10, tm_wday=2, tm_yday=16, tm_isdst=0) print(time.strftime("%Y",time.gmtime())) #2019
true
10c4863b8f764e41b76e5d8eed43f65d1e921f30
Python
DZwell/hacker_rank
/trees/is_present.py
UTF-8
756
3.6875
4
[]
no_license
""" class BSTreeNode: def __init__(self, node_value): self.value = node_value self.left = self.right = None """ from collections import deque def isPresent(root, val): if root: if root.value == val: return 1 q = deque([root]) while q: if root.left: if root.left.value == val: return 1 q.appendleft(root.left) if root.right: if root.right.value == val: return 1 q.appendleft(root.right) root = q.pop() return 0 return 0 # write your code here # return 1 or 0 depending on whether the element is present in the tree or not
true
4a49d47f30afa442a7d9828aa35c8c5602128671
Python
seattlechem/codewars
/geeks-for-geeks/closest-leaf-in-bt-wt-dist/closest_leaf_in_bt_wt_dist.py
UTF-8
1,549
3.5
4
[ "MIT" ]
permissive
"""When given value k, it returns the closest leaf and its distance.""" import collections class Node: """Node class definition.""" def __init__(self, val): """Definition for constructor.""" self.val = val self.left = None self.right = None def find_closest(root, k): """Input root and given k, output closest leaf and its distance in int.""" neighbors = collections.defaultdict(list) leaves = set() def traverse(node, neighbors, leaves): if not node: return if not node.left and not node.right: leaves.add(node.val) if node.left: neighbors[node.val].append(node.left.val) neighbors[node.left.val].append(node.val) traverse(node.left, neighbors, leaves) if node.right: neighbors[node.val].append(node.right.val) neighbors[node.right.val].append(node.val) traverse(node.right, neighbors, leaves) traverse(root, neighbors, leaves) qu, lookup = [k], set([k]) dst = 0 result = {'val': [], 'dist': []} while qu: qu_next = [] for uu in qu: if uu in leaves: result['val'].append(uu) result['dist'].append(dst) for v in neighbors[uu]: if v in lookup: continue lookup.add(v) qu_next.append(v) if len(result['val']) > 0: return result qu = qu_next dst += 1 return 0
true
2e22a56bc95c879b38fb4383086def8c593a4714
Python
AeekTrue/Neural_network
/src/generate_lesson.py
UTF-8
583
2.703125
3
[]
no_license
import numpy as np import time num_examples = 1000 num_inputs = 2 prefix = 'circle' # round(time.time()) training_file_name = f'training_data_{prefix}.csv' test_file_name = f'test_data_{prefix}.csv' def sort_func(x, y): return (x - 0.5)**2 + (y - 0.5)**2 < 0.1 training = np.random.random((num_examples, num_inputs + 1)) training[:, -1] = sort_func(*training[:, :-1].T) np.savetxt(training_file_name, training, delimiter=',') test = np.random.random((num_examples, num_inputs + 1)) test[:, -1] = sort_func(*test[:, :-1].T) np.savetxt(test_file_name, test, delimiter=',')
true
012e64765e40188a711d3fea0b38014dee03f43e
Python
webclinic017/Intelligent-BackTesing-System
/backtesting/portfolio.py
UTF-8
8,885
3.0625
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Mon Apr 10 16:51:08 2017 @author: ricky_xu """ from __future__ import print_function try: import Queue as queue except ImportError: import queue import pandas as pd from event import OrderEvent from performance import create_sharpe_ratio, create_drawdowns class Portfolio(object): """ Portfolio can handle the positions and market value of all instruments at a resolution of a Bar object. """ def __init__(self, bars, events, start_date, initial_capital=100000): """ :param bars: DataHandler; DataHandler object with current data. :param events: Queue; event queue. :param start_date: datetime; timestamp of start date. :param initial_capital: float; initial capital. :param symbol_list: list; a list of symbol strings :param all_positions: list of dict; historical list of a dict(k: datetime and symbol strings; v:datetime and positions of all symbols) :param current_position: dict; current position for last market bar updated. :param all_holdings: dict; historical list of all symbol holdings. :param current_holdings: dict; the most up to date dict of all symbol holdings values. :param equity_curve: DataFrame; record performance of the strategy """ self.bars = bars self.events = events self.symbol_list = self.bars.symbol_list self.start_date = start_date self.initial_capital = initial_capital self.all_positions = self.construct_all_positions() self.current_positions = dict((k, v) for k, v in [(s, 0) for s in self.symbol_list]) self.all_holdings = self.construct_all_holdings() self.current_holdings = self.construct_current_holdings() self.equity_curve = None def construct_all_positions(self): """ Construct a list of dict containing datetime and each position of each symbol. :return: list; a list of dict containing datetime and each position of each symbol. """ d = dict((k, v) for k, v in [(s, 0) for s in self.symbol_list]) d['datetime'] = self.start_date return [d] def construct_all_holdings(self): """ Construct a list of dict containing datetime and each holdins(cash, commisson, total) of each symbol. :return: list; a list of dict containing datetime and each holdins(cash, commisson, total) of each symbol. """ d = dict((k, v) for k, v in [(s, 0.0) for s in self.symbol_list]) d['datetime'] = self.start_date d['cash'] = self.initial_capital d['commisson'] = 0.0 d['total'] = self.initial_capital return [d] def construct_current_holdings(self): """ Construct a dict containing the holdings(cash, commission, total) of all symbols and its datetime is current datetime :return:a dict containing the holdings(cash, commission, total) of all symbols """ d = dict((k, v) for k, v in [(s, 0.0) for s in self.symbol_list]) d['cash'] = self.initial_capital d['commission'] = 0.0 d['total'] = self.initial_capital return d # append this set of current positions to the all_positions list def update_timeindex(self, event): """ append this set of current positions to the all_positions list :param event: Event; it can be used in backtest and backtest can trigger it when its type is MARKET. """ latest_datetime = self.bars.get_latest_bar_datetime(self.symbol_list[0]) dp = dict((k, v) for k, v in [(s, 0) for s in self.symbol_list]) dp['datetime'] = latest_datetime for s in self.symbol_list: dp[s] = self.current_positions[s] self.all_positions.append(dp) dh = dict((k, v) for k, v in [(s, 0) for s in self.symbol_list]) dh['datetime'] = latest_datetime dh['cash'] = self.current_holdings['cash'] dh['commission'] = self.current_holdings['commission'] dh['total'] = self.current_holdings['total'] for s in self.symbol_list: market_value = self.current_positions[s] * self.bars.get_latest_bar_value(s, 'adj_close') dh[s] = market_value dh['total'] += market_value self.all_holdings.append(dh) # FillEvent buy or sell==> update current_positions def update_positions_from_fill(self, fill): """ update the current positions depend the direction of FillEvent. :param fill: FillEvent; it can be used in backtest. """ fill_dir = 0 if fill.direction == 'BUY': fill_dir = 1 if fill.direction == 'SELL': fill_dir = -1 self.current_positions[fill.symbol] += fill_dir * fill.quantity def update_holdings_from_fill(self, fill): """ update current holdings depend on FillEvent. :param fill: FillEvent; it can be used in backtest. """ fill_dir = 0 if fill.direction == 'BUY': fill_dir = 1 if fill.direction == 'SELL': fill_dir = -1 fill_cost = self.bars.get_latest_bar_value(fill.symbol, "adj_close") cost = fill_dir * fill_cost * fill.quantity self.current_holdings[fill.symbol] += cost self.current_holdings['commission'] += fill.commission self.current_holdings['cash'] -= (cost + fill.commission) self.current_holdings['total'] -= (cost + fill.commission) def update_fill(self, event): """ encapsulate update_holdings_from_fill() and update_positions_from_fill(). :param event: FillEvent; """ if event.type == 'FILL': self.update_holdings_from_fill(event) self.update_positions_from_fill(event) def generate_navie_order(self, signal): """ Create OrderEvent using SignalEvent. :param signal: SignalEvent; it's created in strategy.calculate_signals() :return: OrderEvent; use the attributes of SignalEvent to generate OrderEvent. """ order = None symbol = signal.symbol direction = signal.signal_type strength = signal.strength mkt_quantity = 100 cur_quantity = self.current_positions[symbol] order_type = 'MKT' if direction == 'LONG' and cur_quantity == 0: order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY') if direction == 'SHORT' and cur_quantity == 0: order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL') if direction == 'EXIT' and cur_quantity > 0: order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL') if direction == 'EXIT' and cur_quantity < 0: order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY') return order # 根据SIFGNAL添加order到event queue def update_signal(self, event): """ It can be used in backtest. put OrderEvent into EventQueue. :param event: Event; do put operation depend on SignalEvent. """ if event.type == 'SIGNAL': order_event = self.generate_navie_order(event) self.events.put(order_event) def create_equity_curve_dataframe(self): """ It is the part of output_performance of backtest. It generate DataFrame(index: datetime, columns: returns equity_curve ) """ curve = pd.DataFrame(self.all_holdings) curve.set_index('datetime', inplace=True) curve['returns'] = curve['total'].pct_change() curve['equity_curve'] = (1.0 + curve['returns']).cumprod() self.equity_curve = curve def output_summary_stats(self): """ Calulate states(total_return, sharpe_ratio, max_drawdown, max_duration). :return: list; summary data. """ total_return = self.equity_curve['equity_curve'][-1] returns = self.equity_curve['returns'] pnl = self.equity_curve['equity_curve'] sharpe_ratio = create_sharpe_ratio(returns, periods=252 * 60 * 6.5) drawdown, max_dd, max_duration = create_drawdowns(pnl) self.equity_curve['drawdown'] = drawdown stats = [("Total Return", "%0.2f%%" % ((total_return - 1.0) * 100.0)), ("Sharpe Ratio", "%0.2f%%" % sharpe_ratio), ("Max Drawdown", "%0.2f%%" % (max_dd * 100.0)), ("Drawdown Duration", "%d" % max_duration)] self.equity_curve.to_csv('equity.csv') return stats
true
23a71aaac50a9fcf330b294a54b613d3952e5f4c
Python
pepilipep/stock-price-predictions
/src/feature_dataset_enrichment.py
UTF-8
2,763
2.734375
3
[]
no_license
import pandas as pd import numpy as np from sklearn.preprocessing import MinMaxScaler import sklearn import talib import talib.abstract as tabs payload=pd.read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies') first_table = payload[0] tickets = first_table['Symbol'].values.tolist() tickets.remove('BRK.B') tickets.remove('BF.B') all_stocks = [] for ticket in tickets: stocks = pd.read_csv('./datasets/yahoo/' + ticket + '.csv') stocks.rename(columns=str.lower, inplace=True) all_stocks.append(stocks) def feature_extraction(df): # ROC roc = tabs.ROC(df, timeperiod=1) roc = np.nan_to_num(roc) df['roc'] = roc # SMA 10 sma = tabs.SMA(df, timeperiod=10) sma = np.nan_to_num(sma) df['sma'] = sma # MACD, MACD SIGNAL and MACD HIST macd, macdsignal, macdhist = talib.MACD(df['close']) macd = np.nan_to_num(macd) macdsignal = np.nan_to_num(macdsignal) macdhist = np.nan_to_num(macdhist) df['macd'] = macd df['macd_signal'] = macdsignal df['macd_hist'] = macdhist # CCI 24 cci = tabs.CCI(df, timeperiod=24) cci = np.nan_to_num(cci) df['cci'] = cci # MTM 10 mtm = tabs.MOM(df, timeperiod=10) mtm = np.nan_to_num(mtm) df['mtm'] = mtm # RSI 5 rsi = tabs.RSI(df, timeperiod=5) rsi = np.nan_to_num(rsi) df['rsi'] = rsi # WNR 9 wnr = tabs.WMA(df, timeperiod=9) wnr = np.nan_to_num(wnr) df['wnr'] = wnr # SLOWK & SLOWD slowk, slowd = talib.STOCH(df['high'], df['low'], df['close']) slowk = np.nan_to_num(slowk) slowd = np.nan_to_num(slowd) df['slowk'] = slowk df['slowd'] = slowd # ADOSC adosc = tabs.ADOSC(df) adosc = np.nan_to_num(adosc) df['adosc'] = adosc # AARON aroondown, aroonup = talib.AROON(df['high'], df['low']) aroondown = np.nan_to_num(aroondown) aroonup = np.nan_to_num(aroonup) df['aroon_down'] = aroondown df['aroon_up'] = aroonup # BBANDS upper, middle, lower = talib.BBANDS(df['close'], matype=0) upper = np.nan_to_num(upper) df['upper'] = upper middle = np.nan_to_num(middle) df['middle'] = middle lower = np.nan_to_num(lower) df['bbands'] = lower def feature_normalization(df): features = ['volume', 'sma', 'rsi', 'wnr', 'slowk', 'slowd', 'adosc'] scaler = MinMaxScaler() for f in features: damn = np.array(df[f]).reshape((-1, 1)) df[f + '_mm'] = scaler.fit_transform(damn).reshape((-1)) for ticket, stock in zip(tickets, all_stocks): s = stock.copy() feature_extraction(s) feature_normalization(s) s.to_csv('./datasets/enriched/' + ticket + '.csv', index=False)
true
22b5cf58edfe9ca570c3840c8ac8995b70f3ddbe
Python
qiaoyu-jzh/hello-world
/python/test5.py
UTF-8
171
3.25
3
[]
no_license
#闭包练习 def count(): fs=[] for i in range(1,4): def f(): return i*i fs.append(f) return fs f1,f2,f3=count() #s=f1() #print(s)
true
6e8ab3ffa4a6fd27c8fddcf4079d78a002ae9e1c
Python
SaudiWebDev2020/Sumiyah_Fallatah
/Weekly_Challenges/python/week3/testing_python.py
UTF-8
500
4
4
[]
no_license
my_list=[] print(type(my_list)) my_list.append(6) my_list.append(2) my_list.append(5) my_list.append(4) print(my_list) # def fun(): # pass print ("Hello Python") ob2 = { "name": "Zaphod", "numHeads": 2 } ob3 = {} for x in ob2: ob3[ob2[x]] = x print(ob3) ######### name = "Zen" print("My name is " + name +4) print("***") name = "Zen" print("My name is", name, 4) first_name = "Zen" last_name = "Coder" age = 27 print(f"My name is {first_name} {last_name} and I am {age} years old.")
true
ddceb8a29f6e3e6b7b29b6779ed5bb5a8d26f1b6
Python
ChristopherSparling/coding-practice
/dsaawp/circular-linked-list.py
UTF-8
1,514
4.03125
4
[]
no_license
class CircularQueue: class _Node: __slots__ = '_element','_next' def __init__(self,element,next_node): self._element = element self._next = next_node def __init__(self): self._tail = None self._size = 0 def __len__(self): return self._size def is_empty(self): return self._size == 0 def push(self, element): self._head = self._Node(element, self._head) self._size += 1 def first(self): if self.is_empty(): raise Exception('Stack is empty') head = self._tail._next return head._element def dequeue(self): if self.is_empty(): raise Exception('Stack is empty') prev_head = self._tail._next if self._size == 1: self._tail = None else: self._tail._next = prev_head._next self._size -= 1 return prev_head._element def enqueue(self,element): new_node = self._Node(element,None) if self.is_empty(): new_node._next = new_node else: new_node._next = self._tail._next self._tail._next = new_node self._tail = new_node self._size += 1 def rotate(self): if self._size > 0: self._tail = self._tail._next new_stack = CircularQueue() for i in range(5): new_stack.enqueue(i) print(new_stack.first()) for i in range(5): print(new_stack.dequeue())
true
74b47511f3d202ae6cd3ab12c6ef4b1f6c26dbb7
Python
Vital77766688/smartphones_parse
/smartphones_parse/pipelines.py
UTF-8
635
2.578125
3
[ "MIT" ]
permissive
import os import json from datetime import datetime from scrapy.exporters import JsonItemExporter from itemadapter import ItemAdapter class JsonWriterPipeline: def open_spider(self, spider): dt = datetime.now().strftime('%Y%m%d%H%M%S') filename = os.path.join(f'output/{spider.name}_{dt}.json') self.file = open(filename, 'wb') self.exporter = JsonItemExporter(self.file, encoding='utf-8') self.exporter.start_exporting() def close_spider(self, spider): self.exporter.finish_exporting() self.file.close() def process_item(self, item, spider): self.exporter.export_item(ItemAdapter(item).asdict()) return item
true
d29550d0bf4696e9ccfdd14fe046ed116814d798
Python
cucumbyu/rai
/Latihan.py
UTF-8
1,171
2.6875
3
[]
no_license
import argparse import getpass import imaplib import poplib import smtplib IMAP_SERVER = 'outlook.office365.com' IMAP_PORT = 993 POP_SERVER = 'outlook.office365.com' POP_PORT = 995 def imap_mail(username): mailbox = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT) password = getpass.getpass(prompt='Enter your email password: ') mailbox.login(username, password) mailbox.select('Inbox') typ, data = mailbox.search(None, 'ALL') for num in data[0].split(): typ, data = mailbox.fetch(num, '(RFC822)') print ('Message %s\n%s\n' % (num, data[0][1])) break mailbox.close() mailbox.logout() def pop_mail(username): mailbox = poplib.POP3_SSL(POP_SERVER, POP_PORT) mailbox.user(username) password = getpass.getpass(prompt='Enter your email password: ') mailbox.pass_(password) num_messages = len(mailbox.list()[1]) print ('Total emails: {}'.format(num_messages)) mailbox.quit() def mail(): protocol = input("choose pop_mail or imap_mail : ") if (protocol == "imap_mail"): imap_mail('170010159@stikom-bali.ac.id') else: pop_mail('170010159@stikom-bali.ac.id') if __name__ == '__main__': mail()
true
500598e1384ef9fc2db361ee70c31f7eb50212bc
Python
irynabidylo/test_automation
/test_Italki.py
UTF-8
1,309
2.796875
3
[]
no_license
from selenium import webdriver import unittest class ItalkiTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = webdriver.Chrome(executable_path="C:\Program Files\Drivers_browsers\chromedriver.exe") cls.driver.maximize_window() cls.driver.implicitly_wait(5) @classmethod def tearDownClass(cls): cls.driver.quit() print("Test completed") def test_homepage_title_verification(self): self.driver.get("https://www.italki.com") self.assertEqual("italki: Learn a language online", self.driver.title, "Titles don't match") #"Titles don't match" - message which will be shown if test fails def test_login(self): self.driver.get("https://www.italki.com/signin?hl=ru") self.driver.find_element_by_id("signinForm_email").send_keys("test_email@gmail.com") self.driver.find_element_by_id("signinForm_password").send_keys("123456789aB") self.driver.find_element_by_class_name("ant-btn ant-btn-secondary ant-btn-block").click() self.assertEqual("Панель управления | italki", self.driver.title, "Titles don't match") #"Titles don't match" - message which will be shown if test fails if __name__ == '__main__': unittest.main()
true
7ec2112ac0243c45c4b7b3669ddd432587d12dc8
Python
SteveHelenCoDevelopment/LeetCodeChallenges
/test_palindrome.py
UTF-8
736
3.328125
3
[]
no_license
# Test file for calling imported library functions import unittest from longestPalindrome import Solution class TestPalindromeSuite(unittest.TestCase): def test_longer(self): y = Solution() test_cases = ["aaaa","aba","abasskjhghjkz","abasskjhgghjkz"] responses = ["aaaa","aba","kjhghjk","kjhgghjk"] for i in range(len(test_cases)): self.assertEqual(y.longestPalindrome(test_cases[i]), responses[i]) def test_extreme(self): y = Solution() test_cases = ["","a"," "] responses = ["","a"," "] for i in range(len(test_cases)): self.assertEqual(y.longestPalindrome(test_cases[i]), responses[i]) if __name__ == '__main__': unittest.main()
true
80614086b76515d374a450377e20650bbec1a950
Python
Sandeep8447/interview_puzzles
/src/test/python/com/skalicky/python/interviewpuzzles/test_find_max_length_of_substring_without_repeating_chars.py
UTF-8
1,397
3.375
3
[]
no_license
from unittest import TestCase from src.main.python.com.skalicky.python.interviewpuzzles.find_max_length_of_substring_without_repeating_chars import \ Solution class TestSolution(TestCase): def test_find_max_length_of_substring_without_repeating_chars__when_input_is_none__then_output_is_0(self): self.assertEqual(0, Solution.find_max_length_of_substring_without_repeating_chars(None)) def test_find_max_length_of_substring_without_repeating_chars__when_input_is_empty__then_output_is_0(self): self.assertEqual(0, Solution.find_max_length_of_substring_without_repeating_chars('')) def test_find_max_length_of_substring_without_repeating_chars__when_input_contains_all_characters_only_once__then_output_is_length_of_input( self): self.assertEqual(3, Solution.find_max_length_of_substring_without_repeating_chars('abc')) def test_find_max_length_of_substring_without_repeating_chars__when_input_contains_1_character_2x__then_output_is_shorter_than_length_of_input( self): self.assertEqual(2, Solution.find_max_length_of_substring_without_repeating_chars('aba')) def test_find_max_length_of_substring_without_repeating_chars__when_input_is_abrkaabcdefghijjxxx__then_output_is_10( self): self.assertEqual(10, Solution.find_max_length_of_substring_without_repeating_chars('abrkaabcdefghijjxxx'))
true
1b2b240ba07606eb7e691115ff873244ce208fe1
Python
zimkies/puzzles
/datastructures/tree.py
UTF-8
3,404
3.203125
3
[]
no_license
from collections import deque class Tree(): depth = None """My own instance of a tree""" def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right self.depth = self.get_depth() def printout(self): treedepth = self.get_depth() list = deque([(self,treedepth)]) depth = treedepth + 1 while (len(list) >0): t = list.popleft() d = t[1] t = t[0] # break if bottom row is reached if (d <= 0): break # append children to list if ((t is None) or (t.left is None)): list.append((None, d-1)) else: list.append((t.left, d -1)) if ((t is None) or (t.right is None)): list.append((None, d-1)) else: list.append((t.right, d -1)) if (t is None): val = '*' else: val = t.val if (d<depth): depth = d print "\n" lineprint(val, d) else: print "-", lineprint(val, d) def get_depth(self): if self.depth is not None: return self.depth else: if (self.left is None): l = 0 else: l = self.left.get_depth() if (self.right is None): r = 0 else: r = self.right.get_depth() self.depth = max(l, r) + 1 return self.depth def set_left(self, tree): self.left = tree self.get_depth() def set_right(self, tree): self.right = tree self.get_depth() def lineprint(val, depth): h = 2**depth - 1 for i in range(h): print "-", print val, for i in range(h): print "-", def mytree(): a = Tree(1) b = Tree(2) c = Tree(3) d = Tree(4) e = Tree(5) f = Tree(6, a) g = Tree(7, c, d) h = Tree(8, f,g) i = Tree(9, h, f) j = Tree(0, h) return h,i, j def bsort(ints): list = [] for i,int in enumerate(ints): list[i] = [int] class Heap(Tree): def __init__(self, vals): self.heap = Emptytree() for v in vals: self.insert(v) self.depth = self.get_depth() def insert(self, x, heap=None): def get_max(self): val = self.tree.val l = self.tree.left r = self.tree.right if (isinstance(l, Emptytree)): self.tree = r elif (isinstance(r, Emptytree)): self.tree = l #elif (index(l.val) > index(r.val)): def heap_insert(val, heap): # if heap is empty, return a tree if isinstance(heap, Emptytree): return Tree(val) l = self.tree.left r = self.tree.right if (isinstance(l, Emptytree)): self.tree = r elif (isinstance(r, Emptytree)): self.tree = l def merge_sort(lst): l = len(lst) a = lst[:l/2] b = lst[l/2:] if (len(a) == 0): return b elif len(b) == 0: return a return merge(merge_sort(a), merge_sort(b)) def merge(a,b): al = len(a) bl = len(b) s = [] ai,bi = 0,0 while ((ai < al) and (bi < bl)): if a[ai] > b[bi]: s.append(b[bi]) bi +=1 else: s.append(a[ai]) ai +=1 s.extend(a[ai:]) s.extend(b[bi:]) return s
true
d00bc832656762cc42070440a0f7bf494bd45b3d
Python
kirtymeena/DSA
/9.Stack/1.stack.py
UTF-8
3,596
3.765625
4
[]
no_license
# -*- coding: utf-8 -*- """ Created on Wed Dec 16 09:51:15 2020 @author: kirty """ # implementation using array class Stack: def __init__(self): self.stack = [] self.output = [] self.precedence = {"+":1,"-":1,"/":2,"*":2,"^":3} def IsEmpty(self): if self.stack ==[]: return True def push(self,data): self.stack.append(data) def pop(self): if not self.IsEmpty(): return self.stack.pop() return "$" def IsFull(self): if len(self.stack)-1==self.capacity: print("Full") return True def peek(self): if self.IsEmpty(): return "Empty" return self.stack[-1] def IsBalanced(self,exp): lis = [] for i in exp: lis.append(i) # print(lis) for j in range(len(lis)): if lis[j] in ["[","{","("]: self.push(lis[j]) else: if lis[j]==")": if self.peek()=="(": self.pop() elif lis[j]=="]": if self.peek()=="[": self.pop() elif lis[j]=="}": if self.peek()=="{": self.pop() if len(self.stack)==0: return "Balanced" return "Not Balanced" def IsOperand(self,op): return op.isalpha() def precedence(self,opr): d = {"+":1,"-":1,"*":2,"/":2,"^":3} if opr in d: return d[opr] def IsGreater(self,i): try: a = self.precedence[i] b =self.precedence[self.peek()] return True if a<=b else False except KeyError: return False def infix_to_postfix(self,exp): # "A+(B*C-(D/E^F)*G)*H" for j in exp: if self.IsOperand(j): self.output.append(j) elif j=="(": self.push(j) elif j==")": while self.peek()!="(" and not self.IsEmpty(): if self.peek!="(": self.output.append(self.pop()) if not self.IsEmpty() and self.peek()!="(": return -1 else: self.pop() else: while not self.IsEmpty() and self.IsGreater(j): self.output.append(self.pop()) self.push(j) while len(self.stack)!=0: self.output.append(self.pop()) return "".join(self.output) s = Stack() exp="(a+b)*(c+d)" # print(s.IsBalanced(exp)) # print(s.infix_to_postfix(exp)) # s.push(10) # s.push(20) # s.push(30) # s.push(40) # s.push(50) # print(s.peek())
true
615d1a556a465a4706c91f3483459ab7abeb64b8
Python
michaelssavage/eMot
/src/modelTrain/sgdClassifier.py
UTF-8
2,138
2.625
3
[]
no_license
import sys import warnings from pathlib import Path import pandas as pd from modelFuncs import saveFiles from sklearn.feature_extraction.text import CountVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score, f1_score from sklearn.model_selection import train_test_split from tqdm import tqdm from utils.textMod import preprocessAndTokenise, spellCheck tqdm.pandas() # filter warning about using custom tokenizer warnings.filterwarnings("ignore") # sets path to src sys.path.append(str(Path(__file__).parent.parent.absolute())) def main(): print("Loading Data Sets") df_anger = pd.read_csv("../datasets/anger.csv") df_fear = pd.read_csv("../datasets/fear.csv") df_joy = pd.read_csv("../datasets/joy.csv") df_surprise = pd.read_csv("../datasets/surprise.csv") df_happiness = pd.read_csv("../datasets/happiness.csv") df_sadness = pd.read_csv("../datasets/sadness.csv") data_set = [ df_anger, df_fear, df_joy, df_surprise, df_happiness, df_sadness] data = pd.concat(data_set) print("\nChecking Spelling:") data["Text"] = data["Text"].progress_apply(spellCheck) X = data["Text"] y = data["Emotion"] X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42 ) cv = CountVectorizer(tokenizer=preprocessAndTokenise, ngram_range=(1, 2)) X_train_count = cv.fit_transform(X_train) x_test_count = cv.transform(X_test) sgd = SGDClassifier( alpha=0.001, loss="modified_huber", penalty="l2", tol=None, n_jobs=-1 ) sgd.fit(X_train_count, y_train) ysvm_pred = sgd.predict(x_test_count) print("Accuracy: {:.2f}%".format(accuracy_score(y_test, ysvm_pred) * 100)) print( "F1 Score: {:.2f}".format( f1_score( y_test, ysvm_pred, average="micro") * 100)) model_filename = "sgd.pkl" cv_filename = "sgd_cv.pkl" saveFiles(sgd, model_filename) saveFiles(cv, cv_filename) if __name__ == "__main__": main()
true
4105fe34fb2d831296244c917a771a872346e590
Python
ai-kmu/etc
/algorithm/2020/1009_simplify_path/daehee.py
UTF-8
764
3.171875
3
[]
no_license
class Solution: def simplifyPath(self, path: str) -> str: paths = path.split('/') real_paths=[] for path in paths: # 경로들 걸러내기 if path=='' or path=='.': # 현재위치 그대로 continue elif path=='..': # 상위 디렉토리 if len(real_paths)>=1: del real_paths[-1] else: # 하위 디렉토리 real_paths.append(path) real_path = '/' for i, path in enumerate(real_paths): # 값 재조합 if i>0: real_path += '/' real_path += path return real_path
true
034d1b7674ddabeb60fd3f02ba2a2cb95f9d6139
Python
vishrutkmr7/DailyPracticeProblemsDIP
/2019/11 November/dp11042019.py
UTF-8
909
4
4
[ "MIT" ]
permissive
# This problem was recently asked by Facebook: # Given a directed graph, reverse the directed graph so all directed edges are reversed. # Input: # A -> B, B -> C, A -> C # Output: # B -> A, C -> B, C -> A from collections import defaultdict class Node: def __init__(self, value): self.adjacent = [] self.value = value def reverse_graph(graph): # Fill this in. revG = {} for val, node in graph.items(): adj = [j.value for j in node.adjacent] for it in graph: if it not in revG.keys(): revG[it] = Node(it) if it in adj: revG[it].adjacent.append(val) return revG a = Node("a") b = Node("b") c = Node("c") a.adjacent += [b, c] b.adjacent += [c] graph = {a.value: a, b.value: b, c.value: c} for _, val in reverse_graph(graph).items(): print(_, val.adjacent) # a [] # b ['a'] # c ['a', 'b']
true
744c58b8369cd52732f79c5f0f6d8a4b827bd1a3
Python
drewhoener/CS220
/Project 4/src/suffix.py
UTF-8
690
3
3
[]
no_license
from immdict import ImmDict import markov_main def empty_suffix(): return ImmDict() def add_word(suffix, word): if word in suffix.keys(): return suffix.put(word, suffix.get(word) + 1) return suffix.put(word, 1) def choose_word(chain, prefix, random): list_total = [dic for dic in chain.get(prefix).keys() for _ in range(chain.get(prefix).get(dic))] # print(list_total) return list_total[random(len(list_total)) - 1] keyOne = ("this", "is") keyTwo = ("you", "suck") immOne = ImmDict({"the": 2, "a": 3}) immTwo = ImmDict({"at": 2, "this": 3}) dicti = ImmDict({keyOne: immOne, keyTwo: immTwo}) print(choose_word(dicti, keyOne, markov_main.randomizer))
true
22ffbc5d0f8b39f5087adc8987cd9f4d147eff2e
Python
hansh0112/Sample-Projects-
/twitter_search/twitter_api.py
UTF-8
1,579
2.84375
3
[]
no_license
import optparse import sys import twitter_functions def main(args): parser = optparse.OptionParser("""Usage: %prog [-s <search term> | -t | -u <username>]""") parser.add_option("-s", "--search", type="string", action="store", dest="search_term", default=None, help="Display tweets containing a particular string.") parser.add_option("-t", "--trending-topics", action="store_true", dest="trending_topics", default=False, help="Display the trending topics.") parser.add_option("-u", "--user-tweets", type="string", action="store", dest="user_tweets", default=False, help="Display a user's tweets.") parser.add_option("-w", "--trending-tweets", action="store_true", dest="trending_tweets", default=False, help="Display tweets from all of the trending topics.") (opts, args) = parser.parse_args(args) if opts.search_term: twitter_functions.search(opts.search_term) elif opts.trending_topics: twitter_functions.trendingTopics() elif opts.user_tweets: twitter_functions.userTweets(opts.user_tweets) elif opts.trending_tweets: twitter_functions.trendingTweets() if __name__ == "__main__": main(sys.argv[1:])
true
142ae52b8e9d2fb3e1bd21c59be7c99ed872aff6
Python
dozercodes/Breakout
/tester.py
UTF-8
2,234
2.578125
3
[]
no_license
#!/usr/bin/python2.6 import main, gui, board, block, ball, paddle import unittest class MyTest(unittest.TestCase): def testMain(self): complete = main.main() self.assertTrue(complete) def testGUIStartGame(self): complete = gui.GUI.startGame(self) self.assertTrue(complete) def testGUIDrawBoard(self): complete = gui.GUI.drawBoard(self) self.assertTrue(complete) def testGUIDrawPaddle(self): complete = gui.GUI.drawPaddle(self) self.assertTrue(complete) def testGUIDrawBlocks(self): complete = gui.GUI.drawBlocks(self) self.assertTrue(complete) def testGUIDrawBall(self): complete = gui.GUI.drawBall(self) self.assertTrue(complete) def testBoardSetWidth(self): complete = board.Board.setWidth(self) self.assertTrue(complete) def testBoardSetHeight(self): complete = board.Board.setHeight(self) self.assertTrue(complete) def testBlockSetWidth(self): complete = block.Block.setWidth(self) self.assertTrue(complete) def testBlockSetHeight(self): complete = block.Block.setHeight(self) self.assertTrue(complete) def testBlockSetColor(self): complete = block.Block.setColor(self) self.assertTrue(complete) def testBlockOnHit(self): complete = block.Block.onHit(self) self.assertTrue(complete) def testBallSetDiameter(self): complete = ball.Ball.setDiameter(self) self.assertTrue(complete) def testBallSetSpeed(self): complete = ball.Ball.setSpeed(self) self.assertTrue(complete) def testBallMove(self): complete = ball.Ball.move(self) self.assertTrue(complete) def testPaddleSetWidth(self): complete = paddle.Paddle.setWidth(self) self.assertTrue(complete) def testPaddleSetHeight(self): complete = paddle.Paddle.setHeight(self) self.assertTrue(complete) def testPaddleMove(self): complete = paddle.Paddle.move(self) self.assertTrue(complete) if __name__ == '__main__': unittest.main()
true
2553a06e332b1b8b2cb84b7367c81523d548a8c7
Python
HOZH/leetCode
/leetCodePython2020/153.find-minimum-in-rotated-sorted-array.py
UTF-8
487
2.921875
3
[]
no_license
# # @lc app=leetcode id=153 lang=python3 # # [153] Find Minimum in Rotated Sorted Array # # @lc code=start class Solution: def findMin(self, nums: List[int]) -> int: def helper(arr, l, r): if l+1 >= r: return min(arr[l], arr[r]) if arr[l] < arr[r]: return arr[l] m = l+(r-l)//2 return min(helper(arr, l, m-1), helper(arr, m, r)) return helper(nums, 0, len(nums)-1) # @lc code=end
true
4dabeca3d3893017c32d8e98a3ba8be193d43613
Python
dora23/KEMET-Python
/tests/header_section_tests/support_nav_section_tests.py
UTF-8
1,950
2.578125
3
[]
no_license
import time import pytest from pages.header_section import support_nav_section from tests import config class TestSupportMenu: @pytest.fixture() def support(self, driver): return support_nav_section.SupportSection(driver) # Print all Support categories and test their links def test_applications_nav_menu(self, support): support.navigate_to_kemet_page() time.sleep(2) support.accept_cookies() support.hover_over_support() time.sleep(2) print('\nSupport:') displayed_contact_us_elems_title = support.get_displayed_support_contact_us_titles() support_apps_elems = [] for title in displayed_contact_us_elems_title: title_among_possible = False if title.text in config.possible_support_column_1: title_among_possible = True assert title_among_possible, "Titles don't match" support_apps_elems.append((title.get_attribute("href"), title.text)) print(title.text) for support_1_elem in support_apps_elems: support._visit2(support_1_elem[0]) time.sleep(2) assert support.get_current_url() == support_1_elem[0] support.hover_over_support() displayed_supply_management_elems_title = support.get_displayed_technology_supply_management_elems_titles() for title in displayed_supply_management_elems_title: title_among_possible = False if title.text in config.possible_support_column_2: title_among_possible = True assert title_among_possible, "Titles don't match" support_apps_elems.append((title.get_attribute("href"), title.text)) print(title.text) for support_2_elem in support_apps_elems: support._visit2(support_2_elem[0]) time.sleep(2) assert support.get_current_url() == support_2_elem[0]
true
90b3845d106677844ccc5a412ed4e04a8e1609a9
Python
jsverch/practice
/hourglass.py
UTF-8
358
3.09375
3
[]
no_license
arr = [(1, 1, 1, 0, 0, 0), (0, 1, 0, 0, 0, 0), (1, 1, 1, 0, 0, 0), (0, 0, 2, 4, 4, 0), (0, 0, 0, 2, 0, 0), (0, 0, 1, 2, 4, 0)] hgs = list() for x in range(0, 4): for y in range(0, 4): ch = arr[x][y] + arr[x][y+1] + arr[x][y+2] + arr[x+1][y+1] + arr[x+2][y]\ + arr[x+2][y+1] + arr[x+2][y+2] hgs.append(ch) print max(hgs)
true
793e1191a9f34a87e242a2f7dc8ff5c9a2e559c8
Python
Omega97/quantum_logic_gates
/quantum_gates.py
UTF-8
1,199
2.5625
3
[]
no_license
from algebra import * from numpy import pi def identity(n_bits): """identity given number of q-bits""" return Operator(np.identity(2**n_bits)) I = identity(1) H = Operator([[1, 1], [1, -1]]).n() X = Operator([[0, 1], [1, 0]]) Y = Operator([[0, -1j], [1j, 0]]) Z = Operator([[1, 0], [0, -1]]) NOT = X CX = CNOT = C_(NOT) R = phase_shift S = phase_shift(pi / 2) T = phase_shift(pi / 8) Toffoli = CCNOT = C_(C_(NOT)) SWAP = Operator([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]) Fredkin = CSWAP = C_(SWAP) # complex number: (1+i)/2 q_ = complex(1, 1)/2 NOT_sqrt = I * q_ + X * q_.conjugate() SWAP_sqrt = stack(Id(1), NOT_sqrt, Id(1)) def ising(mat): """unofficial Ising matrices""" def ising_(angle): a = np.cos(angle) * tensor_prod(I, I) b = -1j * np.sin(angle) * tensor_prod(mat, mat) return Operator(a + b) return ising_ Ising_XX = ising(X) Ising_YY = ising(Y) def Ising_ZZ(angle): a = np.cos(angle/2) * tensor_prod(I, I) b = 1j * np.sin(angle/2) * tensor_prod(Z, Z) return Operator(a + b) del q_
true
16cc7f8c77ffc3fa7fb0484cbe2ca38bad2c8fa1
Python
MartinHarvey/NetDucky
/server_app/app/routes.py
UTF-8
924
2.71875
3
[]
no_license
import os from flask import request from app import server_app #Basic route. Used to test if server is running and responding to requests @server_app.route('/') @server_app.route('/index') def index(): return "Hello, World!" # <duckey_name> corresponds to the name each ducky client has. This allows you # to issue different instructions to # different duckys. @server_app.route('/download/<duckey_name>', methods = ['GET']) def file_Page(duckey_name): path = os.getcwd() +"/files/" + duckey_name with open(path, "r") as file: data = file.read() file.close() return(data, 200) #Upload a new set of instructions for <ducky_name>. @server_app.route('/upload/instructions/<ducky_name>/', methods = ['POST']) def upload_Instruction(ducky_name): file = request.files['secret'] file.save(os.path.join(server_app.config['UPLOAD_FOLDER'], ducky_name)) return ("Success", 200)
true
2058faf87a09cea366a03e2076d406c6c9fa3311
Python
ketchup-doraemon/Morphology_Team4
/src/two_net_model.py
UTF-8
3,767
2.65625
3
[]
no_license
# -*- coding: utf-8 -*- __author__ = 'Daisuke Yoda' __Date__ = 'December 2018' import numpy as np from gensim.models.keyedvectors import KeyedVectors import matplotlib.pyplot as plt from chainer import Chain, Variable, optimizers import chainer.functions as F import chainer.links as L class Second_Network(Chain): def __init__(self,vocab_size, in_size, out_size): super(Second_Network, self).__init__( xh=L.EmbedID(vocab_size, in_size), hh=L.LSTM(in_size, out_size), ) def forward(self, x): x = Variable(x) x = self.xh(x) if self.i == 0: self.x = x y = self.hh(x) return y def __call__(self,word): self.reset() self.i = 0 if word == []: return self.forward(np.array([0],dtype=np.int32)) for char in word: out = self.forward(char) self.i += 1 return out def reset(self): self.hh.reset_state() class Third_Network(Chain): def __init__(self, in_size, hidden_size, out_size): super(Third_Network, self).__init__( hh1 = L.Linear(in_size, hidden_size), bn1 = L.BatchNormalization(hidden_size), hh2 =L.Linear(in_size, hidden_size), bn2 = L.BatchNormalization(hidden_size), hy = L.Linear(hidden_size*2, out_size), bn3 = L.BatchNormalization(out_size), ) def __call__(self, x1,x2,t): t = Variable(t) h1 = self.hh1(x1) h2 = self.hh2(x2) #h1 = self.bn1(h1) #h2 = self.bn2(h2) h1 = F.dropout(h1,0.3) h2 = F.dropout(h2, 0.3) h1 = F.relu(h1) h2 = F.relu(h2) h = F.concat([h1, h2]) out = self.hy(h) #out = self.bn3(out) #out = F.dropout(out,0.3) out = F.tanh(out) out = F.normalize(out) return F.mean_squared_error(out,t) def predict(self, x1,x2): h1 = self.hh1(x1) h2 = self.hh2(x2) h1 = F.relu(h1) h2 = F.relu(h2) h = F.concat([h1, h2]) out = self.hy(h) out = F.tanh(out) out = F.normalize(out) return out if __name__ == '__main__': dic = KeyedVectors.load_word2vec_format("trainer/glove.6B.100d.bin") original_word = 'created' glove_vec = dic.get_vector(original_word).reshape(1, 100) second_net = Second_Network(27,100, 50) second_net.cleargrads() second_net.reset() optimizer2 = optimizers.Adam() optimizer2.setup(second_net) second_net2 = Second_Network(27, 30, 50) second_net2.cleargrads() second_net2.reset() optimizer3 = optimizers.Adam() optimizer3.setup(second_net2) third_net = Third_Network(50, 50, 100) third_net.cleargrads() optimizer4 = optimizers.Adam() optimizer4.setup(third_net) loss_record = [] word1 = 'work' word2 = 'ed' vec1 = [np.array([ord(char) - 96], dtype=np.int32) for char in word1] vec2 = [np.array([ord(char) - 96], dtype=np.int32) for char in word2] for i in range(100): y1 = second_net(vec1) y2 = second_net2(vec2) loss = third_net(y1,y2,glove_vec) loss_record.append(float(loss.data)) loss.backward(retain_grad=True) optimizer4.update() optimizer3.update() optimizer2.update() y1 = second_net(vec1) y2 = second_net2(vec2) pred = third_net.predict(y1,y2) dic.most_similar(pred.data) plt.plot(loss_record) plt.show() print(dic.most_similar(pred.data))
true
23178b6086cb71f59bcba56acffbc026116fbf00
Python
ghcjssla/reinforceNLP
/01-cartpole/model.py
UTF-8
763
2.8125
3
[]
no_license
import torch import torch.nn as nn import torch.nn.functional as F """ Cartpole Network """ class CartpoleNet(nn.Module): def __init__(self, n_state, n_action, softmax=True): super(CartpoleNet, self).__init__() self.softmax = softmax self.layer1 = nn.Linear(n_state, 256) self.layer2 = nn.Linear(256, 256) self.output = nn.Linear(256, n_action) def forward(self, state): output = F.relu(self.layer1(state)) output = F.relu(self.layer2(output)) output = self.output(output) return F.softmax(output, dim=1) if self.softmax else output """ Cartpole Configuration """ class CartpoleConfig(dict): __getattr__ = dict.__getitem__ __setattr__ = dict.__setitem__
true
683c9aa9e558ed96397a640731e3702124f48d8f
Python
hakgyu2298/Python_test
/20210622_실습2C-3.py
UTF-8
197
4.5625
5
[]
no_license
# 리스트의 모든 원소를 enumerate()함수로 스캔하기(1부터 카운트) x = ['John', 'George', 'Paul', 'Ringo'] for i, name in enumerate(x,1): print(f'{i}번째 = {name}')
true
36a8d58933181c4bdb5ab8fe2bd0c1a27de89d86
Python
mrwizard82d1/py_mem_pwds
/mem_pwds/cmd/memorable_pwds.py
UTF-8
1,251
2.765625
3
[]
no_license
#!/usr/bin/env python # """An interactive, text-based application to generate strong, easily memorized passwords.""" import cmd import os import string import sys try: # if it is installed from mem_pwds.MemorablePwds import MemorablePwds except ImportError: # if it is in development sys.path.append(os.path.join(os.path.split(os.path.abspath(__file__))[0], '..', '..')) from mem_pwds.MemorablePwds import MemorablePwds class MemorablePwdsApp(cmd.Cmd): def __init__(self): cmd.Cmd.__init__(self) self.prompt = 'Memorable Passwords: ' self._generator = MemorablePwds() def help_next(self): print 'Generates the next password.' def do_next(self, theCount): print self._generator.next() def help_EOF(self): print 'Quits the program.' def do_EOF(self, line): return True def help_exit(self): print 'Quits the program.' def do_exit(self, line): if __name__ == '__main__': sys.exit() else: raise Exception('exit') def doApp(): theApp = MemorablePwdsApp() theApp.cmdloop() if __name__ == '__main__': doApp()
true
8cbc0d778e803293770404e118d9c8efa5134653
Python
workcookiestw/Python-GetGovOpenData
/opendata.py
UTF-8
596
2.546875
3
[]
no_license
import time import urllib3 import datetime import requests import urllib.request import re #REF: https://docs.python.org/2/library/xml.etree.elementtree.html response = urllib.request.urlopen("http://opendata.epa.gov.tw/webapi/api/rest/datastore/355000000I-000001/?format=xml&limit=1&offset=0") '''soup = beautifulsoup4(response) print(soup) if response.read().decode('utf_8') is '麥寮': print(response.read().decode('utf_8'))''' print(response.read().decode('utf_8')) if re.match("雲林縣",response.read().decode('utf_8')): print(response.read().decode('utf_8'))
true
b15adde56fafc03ff9debcfc2e3df41bc3b1bd0e
Python
fodierna/Natural-Language-Technologies
/CONCEPT_SIMILARITY/utilities.py
UTF-8
3,441
3.046875
3
[]
no_license
import csv from math import log import numpy as np from numpy import cov, std from scipy.stats import rankdata import nltk from nltk.corpus import wordnet as wn import sys # read a file containing two words and a similitary score associated to def read(path): #nltk.download('wordnet') with open(path) as csv_file: w1 = [] w2 = [] target = [] line_count = 0 csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: if line_count == 0: #print(f'Column names are {", ".join(row)}') line_count += 1 else: w1.append(row[0]) w2.append(row[1]) target.append(float(row[2])/10) #print("Word 1: {} \t Word 2: {} \t Target: {}".format(row[0], row[1], row[2])) line_count += 1 #print(f'Processed {line_count} lines.') return w1, w2, target # wu palmer similarity def wu_palmer_similarity(w1, w2): max_sim = 0 # look for each word in synset associated to w1 for s1 in wn.synsets(w1): # look for each word in synset associated to ww for s2 in wn.synsets(w2): #first common parent of s1 and s2 for lcs in s1.lowest_common_hypernyms(s2): # wu-palmer sim: 2*depth(LCS) / depth(s1)+depth(s2) sim = 2*lcs.max_depth()/(s1.max_depth()+s2.max_depth()) # to find the maximum similarity if(sim > max_sim): max_sim = sim return max_sim # shortest path similarity def sp_similarity(w1, w2, depth_max = 30): min_len = sys.maxsize # look for each word in synset associated to w1 for s1 in wn.synsets(w1): # look for each word in synset associated to w2 for s2 in wn.synsets(w2): # find the shortest path distance between s1 and s2 len = s1.shortest_path_distance(s2) if(len is None): len = 2 * depth_max # to find the shortest path if(len < min_len): min_len = len # normalized similarity return (2*depth_max - min_len) / (2*depth_max) # leakcock & chodorow similarity def lc_similarity(w1, w2, depth_max = 30): max_sim = 0 # look for each word in synset associated to w1 for s1 in wn.synsets(w1): # look for each word in synset associated to w2 for s2 in wn.synsets(w2): # find the shortest path distance between s1 and s2 len = s1.shortest_path_distance(s2) if(len is not None): if(len>0): sim = -(log(len/(2*depth_max+1))) else: sim = -(log(len+1/(2*depth_max+1))) else: sim = 0 if(sim > max_sim): max_sim = sim return max_sim/log(2*depth_max+1) #correlation indexes def spearman_rank_correlation_coefficient(target, predicted): target = np.array(target).astype(np.float) predicted = np.array(predicted).astype(np.float) return cov(rankdata(target), rankdata(predicted))[0][1] / (std(rankdata(target)) * std(rankdata(predicted))) def pearson_correlation(target, predicted): target = np.array(target).astype(np.float) predicted = np.array(predicted).astype(np.float) return cov(target, predicted)[0][1] / (std(target)*std(predicted))
true
a38e93b306c95168c59da6e6bfdc51438bf1f3e6
Python
livan123/DataMining
/03统计算法/common_used.py
UTF-8
861
2.859375
3
[]
no_license
# -*- coding: utf-8 -*- # 1)因子分析(FA) # 2)主成分分析(PCA) # 3)独立成分分析(IDA) # 4)线性判别分析(LDA) # 5)离群点分析 # 6)时间序列法 # ACF:样本自相关函数,样本序列存在周期性; # ADF:单位根检验,表明序列平稳性; # AR:自回归模型; # MA:滑动平均模型; # ARMA:平稳序列的自回归滑动平均; # ARIMA:非平稳序列的自回归滑动平均(需要进行差分处理) # 主要有四类: # 1)趋势: # 2)季节变动:就是计算周期内各时期季节性影响的相对数; # 3)循环变动: # 4)不规则波动: # 7)假设检验 # 8)相关分析 # 9)方差分析 # 10)区间估计 # 11)协同过滤 # 12)k邻近法
true
f59d926f199abdd6f4e5939462a65578e67afad4
Python
IMSY-DKFZ/simpa
/simpa/core/simulation_modules/acoustic_forward_module/__init__.py
UTF-8
3,375
2.5625
3
[ "MIT" ]
permissive
# SPDX-FileCopyrightText: 2021 Division of Intelligent Medical Systems, DKFZ # SPDX-FileCopyrightText: 2021 Janek Groehl # SPDX-License-Identifier: MIT from abc import abstractmethod import numpy as np from simpa.core import SimulationModule from simpa.utils import Tags, Settings from simpa.io_handling.io_hdf5 import save_hdf5 from simpa.utils.dict_path_manager import generate_dict_path from simpa.core.device_digital_twins import PhotoacousticDevice, DetectionGeometryBase from simpa.utils.quality_assurance.data_sanity_testing import assert_array_well_defined class AcousticForwardModelBaseAdapter(SimulationModule): """ This method is the entry method for running an acoustic forward model. It is invoked in the *simpa.core.simulation.simulate* method, but can also be called individually for the purposes of performing acoustic forward modeling only or in a different context. The concrete will be chosen based on the:: Tags.ACOUSTIC_MODEL tag in the settings dictionary. :param settings: The settings dictionary containing key-value pairs that determine the simulation. Here, it must contain the Tags.ACOUSTIC_MODEL tag and any tags that might be required by the specific acoustic model. :raises AssertionError: an assertion error is raised if the Tags.ACOUSTIC_MODEL tag is not given or points to an unknown acoustic forward model. """ def __init__(self, global_settings: Settings): super(AcousticForwardModelBaseAdapter, self).__init__(global_settings=global_settings) self.component_settings = global_settings.get_acoustic_settings() @abstractmethod def forward_model(self, detection_geometry) -> np.ndarray: """ This method performs the acoustic forward modeling given the initial pressure distribution and the acoustic tissue properties contained in the settings file. A deriving class needs to implement this method according to its model. :return: time series pressure data """ pass def run(self, digital_device_twin): """ Call this method to invoke the simulation process. :param digital_device_twin: :return: a numpy array containing the time series pressure data per detection element """ self.logger.info("Simulating the acoustic forward process...") _device = None if isinstance(digital_device_twin, DetectionGeometryBase): _device = digital_device_twin elif isinstance(digital_device_twin, PhotoacousticDevice): _device = digital_device_twin.get_detection_geometry() else: raise TypeError( f"The optical forward modelling does not support devices of type {type(digital_device_twin)}") time_series_data = self.forward_model(_device) if not (Tags.IGNORE_QA_ASSERTIONS in self.global_settings and Tags.IGNORE_QA_ASSERTIONS): assert_array_well_defined(time_series_data, array_name="time_series_data") acoustic_output_path = generate_dict_path( Tags.DATA_FIELD_TIME_SERIES_DATA, wavelength=self.global_settings[Tags.WAVELENGTH]) save_hdf5(time_series_data, self.global_settings[Tags.SIMPA_OUTPUT_PATH], acoustic_output_path) self.logger.info("Simulating the acoustic forward process...[Done]")
true
51ed90864f2656805bc17eaddcafec9a1c36d7f1
Python
aap488/meal_planner
/meal_data.py
UTF-8
219
2.65625
3
[]
no_license
class MealData: """ Class designed to store the information used in a Meal class. """ def __init__(self, meal_list, meal_name): self.meal_list = meal_list self.meal_name = meal_name
true
83aa67f8ca2a2a66ba8429aed38626d18057ef21
Python
Jonathan-aguilar/DAS_Sistemas
/Ene-Jun-2021/perez-gutierrez-julio-cesar/Examen Extraordinario/Ejercicio-7/users.py
UTF-8
1,525
3.15625
3
[ "MIT" ]
permissive
"A Singleton Dictionary of Users" from decimal import Decimal from wallets import Wallets from reports import Reports class Users(): "A Singleton Dictionary of Users" #_users: dict[str, dict[str, str]] = {} # Python 3.9 _users = {} # Python 3.8 or earlier def __new__(cls): return cls @classmethod #def register_user(cls, new_user: dict[str, str]) -> str: # Python 3.9 def register_user(cls, new_user) -> str: # Python 3.8 or earlier "register a user" if not new_user["user_name"] in cls._users: # generate really complicated unique user_id. # Using the existing user_name as the id for simplicity user_id = new_user["user_name"] cls._users[user_id] = new_user Reports.log_event(f"new user `{user_id}` created") # create a wallet for the new user Wallets().create_wallet(user_id) # give the user a sign up bonus Reports.log_event( f"Give new user `{user_id}` sign up bonus of 10") Wallets().adjust_balance(user_id, Decimal(10)) return user_id return "" @classmethod def edit_user(cls, user_id: str, user: dict): "do nothing" print(user_id) print(user) return False @classmethod def change_pwd(cls, user_id: str, password: str): "do nothing" print(user_id) print(password) return False
true
0449740770b74d78537a37e1c26953370fe42024
Python
waqar-ahmed-malik/python
/tutorials/pythonModules/csvModule/code.py
UTF-8
502
2.75
3
[]
no_license
import csv with open("Read.csv", "r", encoding="utf8") as csv_read: csv_reader = csv.DictReader(csv_read) fieldnames = list() for line in csv_reader: for key, value in line.items(): if key not in fieldnames: fieldnames.append(key) csv_read.seek(0) with open("Write.csv", "w", newline='') as csv_write: csv_writer = csv.DictWriter(csv_write, fieldnames=fieldnames, ) for line in csv_reader: csv_writer.writerow(line)
true
c482816b0fc38bd50ed12fa5e312c8f26c2d4ec2
Python
chiendb97/naive_bayes
/main.py
UTF-8
1,126
2.625
3
[]
no_license
from utils.data_loader import DataLoader from utils.model import NaVieBayes from sklearn.metrics import accuracy_score, f1_score import pickle loader = DataLoader() len_vocab = len(loader.vocab) features, target = loader.get_data() n = len(target) indexs = [i//2 if i % 2 == 0 else i//2 + n//2 for i in range(n)] features = [features[i] for i in indexs] target = [target[i] for i in indexs] k_fold = 5 batch_size = len(target)//k_fold for i in range(k_fold): model = NaVieBayes(num_class=2, len_vocab=len_vocab, alpha=1) features_train = features[0: batch_size*i] + features[batch_size*(i+1):] target_train = target[0: batch_size*i] + target[batch_size*(i+1):] features_test = features[batch_size*i: batch_size*(i+1)] target_test = target[batch_size*i: batch_size*(i+1)] model.fit(features_train, target_train) y_pred = model.predict(features_test) print('model {}: acc: {}, f1_score: {}'.format(i, accuracy_score(target_test, y_pred), f1_score(target_test, y_pred, average=None))) with open('models/nb_model_' + str(i) + '.pkl', 'wb+') as f: pickle.dump(model, f) print('Done')
true
06020790a21b2cbaf6d3822768e2c1f32013c418
Python
Aasthaengg/IBMdataset
/Python_codes/p02595/s715817534.py
UTF-8
221
3.109375
3
[]
no_license
import math N, M = map(int, input().split()) counter = 0 for _ in range(N): a, b = map(int, input().split()) distance = math.sqrt(abs(a)**2 + abs(b)**2) if distance <= M: counter += 1 print(counter)
true
878ea2bb15b453403d577d459b613c0b082bde3a
Python
yukiao/to-do-list
/Home.py
UTF-8
1,888
2.609375
3
[]
no_license
from PyQt5 import QtWidgets from PyQt5.QtWidgets import * import Login as login import User import Account as account class Home(QWidget): def __init__(self): super(Home,self).__init__() self.setContentsMargins(20,20,20,20) self.initUi() def initUi(self): self.usernameLabel = QLabel('Username') self.usernameField = QLineEdit() self.passwordLabel = QLabel('Password') self.passwordField = QLineEdit() self.passwordField.setEchoMode(QtWidgets.QLineEdit.Password) self.button = QPushButton("Login") self.button.clicked.connect(self.onClicked) self.grid = QGridLayout() self.create = QPushButton("Create Account") self.create.clicked.connect(self.createAccount) self.grid.addWidget(self.usernameLabel,0,0) self.grid.addWidget(self.usernameField,0,1) self.grid.addWidget(self.passwordLabel,1,0) self.grid.addWidget(self.passwordField,1,1) self.grid.addWidget(self.button,2,2) self.grid.addWidget(self.create,3,2) self.grid.setHorizontalSpacing(20) self.setLayout(self.grid) def onClicked(self): self.username = self.usernameField.text() self.password = self.passwordField.text() if login.Login().authentication(self.username,self.password): self.newWindow = User.User(self.username) self.newWindow.setWindowTitle("ToDoList") self.newWindow.show() self.close() else: msg = QMessageBox() msg.setWindowTitle("Error") msg.setText('Wrong username/password') msg.setIcon(QMessageBox.Critical) x = msg.exec_() def createAccount(self): self.createNewAccount = account.Account() self.createNewAccount.show() self.close()
true
8cfc7f5623958c41a4a22db619ed2e6bfe30c54e
Python
eddyxq/Intro-to-Computer-Science
/Full A3/A3.py
UTF-8
14,603
3.84375
4
[]
no_license
# Author: Eddy Qiang # Student ID: 30058191 # CPSC 231-T01 """ Patch History: Date Version Notes May 16, 2017 Ver. 1.0.0 initial creation May 27, 2017 Ver. 1.0.1 added three new rooms June 02, 2017 Ver. 1.0.2 reorganized code into functions June 07, 2017 Ver. 1.0.3 add more functions, refined code """ """ A text-based "choose your own" adventure game. There are six rooms in the game world, within each room the player will see a number of choices and the program will react to the player's decision. The goal of this game is to try to unlock a inner door and then find paradise. The door will only be unlocked if the player turns the key silver lock in the pantry to the "right" position and the key gold lock in the kitchen to the "left" position. Upon opening the door, the player has to look around and interact with various things to find paradise. The only way to reach paradise is to fertilize the pot of soil by feeding cheese to the mouse after picking up cheese, and picking up a ball of string and dropping it down the hole. Once the player reaches paradise the game ends and a congratulatory message is displayed. """ # display entrance options def print_entrance_menu(): print("You are now at the entrance room.\n") print("1. Try to open the door") print("2. Go through the left entry way") print("3. Go through the right entry way") # moves player to entrance room def move_to_entrance(): room = "entrance" return room # inner door logic def open_inner_door(silver_lock, gold_lock): print("You try to open the door and...") if (silver_lock == "right") and (gold_lock == "left"): room = "living_room" print("The door unlocks. Congratulations!") print_game_intro2() return room else: room = "entrance" print("The door won't budge!\n") return room # display kitchen lock position def print_kitchen_intro(gold_lock): print("You are now at the kitchen, and you see a gold lock.") print("The gold lock is currently in the", gold_lock, "position.\n") # display kitchen options def print_kitchen_menu(): print("1. Turn the gold lock to the left position") print("2. Turn the gold lock to the right position") print("3. Turn the gold lock to the center position") print("4. Don't change the position! Return to entrance way") # moves player to kitchen def move_to_kitchen(): room = "kitchen" return room # sets gold lock positions def gold_lock_position(decision): if decision == 1: print("The gold lock is now set to the left position\n") gold_lock = "left" return gold_lock elif decision == 2: print("The gold lock is now set to the right position\n") gold_lock = "right" return gold_lock elif decision == 3: print("The gold lock is now set to the center position\n") gold_lock = "center" return gold_lock # display pantry lock position def print_pantry_intro(silver_lock): print("You are now at the pantry, and you see a silver lock.") print("The silver lock is currently in the", silver_lock, "position.\n") # display pantry options def print_pantry_menu(): print("1. Turn the silver lock to the left position") print("2. Turn the silver lock to the right position") print("3. Turn the silver lock to the center position") print("4. Don't change the position! Return to entrance way") # moves player to pantry def move_to_pantry(): room = "pantry" return room # sets silver lock positions def silver_lock_position(decision): if decision == 1: print("The silver lock is now set to the left position\n") silver_lock = "left" return silver_lock elif decision == 2: print("The silver lock is now set to the right position\n") silver_lock = "right" return silver_lock elif decision == 3: print("The silver lock is now set to the center position\n") silver_lock = "center" return silver_lock # display living room options def print_living_room_menu(ball_of_string_available): print("You are now at the living room.") if ball_of_string_available == True: print("You see a ball of string on the floor") print("1. View the pot of soil") print("2. Walk up stairs") print("3. Go through the dark entrance way") if ball_of_string_available == True: print("4. Pick up a ball of string") # moves player to living room def move_to_living_room(): room = "living_room" return room # pot of soil logic and win condition def check_win_condition(pot_of_soil_dry): print("You view the pot of soil...") if pot_of_soil_dry == True: room = "living_room" print("The pot of soil looks dry\n") return room else: print("A vine grows out of the pot and takes you to paradise.") print("Congratulations!") game_won = True # display attic options def print_attic_menu(have_cheese): print("You are now in the attic.\n") print("You see cheese on the ground as well as a hole in the ground.") print("1. Pick up cheese") if have_cheese == True: print("2. Drop cheese down the hole") print("3. Walk down the stairs") # moves player to attic def move_to_attic(): room = "attic" return room # picking up cheese def pick_up_cheese(): print("You picked up some cheese\n") have_cheese = True return have_cheese # dropping cheese def drop_cheese(have_cheese): print("You attempt to drop cheese down the hole and you find that") if have_cheese == True: print("The cheese is too big\n") else: print("You do not have any cheese on you") # display bedroom desciption def print_bedroom_intro(string_dropped): print("You are now at the bedroom.") if string_dropped == True: print("The cat has left the room due to the large distraction motion of the string,\nand you see a mouse") else: print("You noticed there is a mouse in the mouse hole and you see a cat watching the mouse hole\n") # moves player to bedroom def move_to_bedroom(): room = "bedroom" return room # display bedroom options def print_bedroom_menu(have_ball_of_string, string_dropped, have_cheese): print("1. Go back through the dark entrance way") if (have_ball_of_string == True) and (string_dropped == False): print("2. Play with the cat using the string") if (have_ball_of_string == False) and (string_dropped == True) and (have_cheese == True): print("3. Feed cheese to the mouse") # play with cat def interact_with_cat(): print("The cat briefly looks at you and then goes back to watching the mouse hole\n") # feed mouse def feed_mouse(): print("You fed the mouse some cheese, the mouse leaves the room and returns after a moment\n") pot_of_soil_dry = False return pot_of_soil_dry # prompt user for input def ask_for_input(): decision = int(input("What would you like to do? Enter choice number: \n")) return decision # display input error def display_error(): print("Invalid entry, please enter again.\n") # displays part one game introduction def print_game_intro(): print(""" You have just stepped into the entrance room through the outer door. The door you came through magically vanishes behind you. In front of you there is a inner door, one room to your left, and one room to your right.\n""") # displays part two game introduction def print_game_intro2(): print(""" You have just stepped through the inner door taking you from the entrance room through to the living room. The door you came through magically vanishes behind you. In the living room you see a pot of soil, stairs going up, and a dark entrance way.\n""") # entrance room option selection def entrance(silver_lock, gold_lock): OPEN_DOOR = 1 MOVE_TO_KITCHEN = 2 MOVE_TO_PANTRY = 3 # input validation loop try: validity = False while validity == False: print_entrance_menu() decision = ask_for_input() if decision in range(1, 4): validity = True else: display_error() # decision logic if decision == OPEN_DOOR: room = open_inner_door(silver_lock, gold_lock) return room elif decision == MOVE_TO_KITCHEN: room = move_to_kitchen() return room elif decision == MOVE_TO_PANTRY: room = move_to_pantry() return room else: display_error() except ValueError: display_error() # pantry room option selection def pantry(): # input validation loop try: validity = False while validity == False: print_pantry_menu() decision = ask_for_input() if decision in range(1, 5): validity = True return decision else: display_error() except ValueError: display_error() # kitchen room option selection def kitchen(): # input validation loop try: validity = False while validity == False: print_kitchen_menu() decision = ask_for_input() if decision in range(1, 5): validity = True return decision else: display_error() except ValueError: display_error() # living room option selection def living_room(): # input validation loop try: validity = False while validity == False: decision = ask_for_input() if decision in range(1, 6): validity = True return decision else: display_error() except ValueError: display_error() # attic option selection def attic(have_ball_of_string, have_cheese): # input validation loop try: validity = False while validity == False: print_attic_menu(have_cheese) if have_ball_of_string == True: print("4. Drop the string down the hole") decision = ask_for_input() if decision in range(1, 5): validity = True return decision else: display_error() except ValueError: display_error() # bedroom option selection def bedroom(have_ball_of_string, string_dropped, have_cheese): # input validation loop try: validity = False while validity == False: print_bedroom_menu(have_ball_of_string, string_dropped, have_cheese) decision = ask_for_input() if decision in range(1, 4): validity = True return decision else: display_error() except ValueError: display_error() # starting function def main(): print_game_intro() # initialize game settings and variable room = "entrance" gold_lock = "left" silver_lock = "right" inner_door_locked = True ball_of_string_available = True pot_of_soil_dry = True have_ball_of_string = False have_cheese = False string_dropped = False path_to_paradise = False game_won = False MOVE_TO_ENTRANCE = 4 VIEW_SOIL = 1 MOVE_TO_ATTIC = 2 MOVE_TO_BEDROOM = 3 PICK_UP_STRING =4 DROP_STRING = 4 PICK_UP_CHEESE = 1 DROP_CHEESE = 2 MOVE_TO_LIVING_ROOM = 3 MOVE_BACK = 1 INTERACT_WITH_CAT = 2 FEED_MOUSE = 3 # main game loop while game_won == False: # entrance room if room == "entrance": room = entrance(silver_lock, gold_lock) # pantry elif room == "pantry": print_pantry_intro(silver_lock) decision = pantry() if decision in range(1,4): silver_lock = silver_lock_position(decision) elif decision == MOVE_TO_ENTRANCE: room = move_to_entrance() else: display_error() # kitchen elif room == "kitchen": print_kitchen_intro(gold_lock) decision = kitchen() if decision in range(1,4): gold_lock = gold_lock_position(decision) elif decision == MOVE_TO_ENTRANCE: room = move_to_entrance() else: display_error() # living elif room == "living_room": print_living_room_menu(ball_of_string_available) decision = living_room() if decision == VIEW_SOIL: room = check_win_condition(pot_of_soil_dry) elif decision == MOVE_TO_ATTIC: room = move_to_attic() elif decision == MOVE_TO_BEDROOM: room = move_to_bedroom() elif decision == PICK_UP_STRING: if ball_of_string_available == True: print("You picked up the ball of string\n") ball_of_string_available = False have_ball_of_string = True else: display_error() else: display_error() # attic elif room == "attic": decision = attic(have_ball_of_string, have_cheese) if decision == PICK_UP_CHEESE: have_cheese = pick_up_cheese() elif (decision == DROP_CHEESE) and (have_cheese == True): drop_cheese(have_cheese) elif decision == MOVE_TO_LIVING_ROOM: room = move_to_living_room() elif (decision == DROP_STRING) and (have_ball_of_string == True): print("You dropped the string down the hole\n") have_ball_of_string = False string_dropped = True else: display_error() # bedroom elif room == "bedroom": print_bedroom_intro(string_dropped) decision = bedroom(have_ball_of_string, string_dropped, have_cheese) if decision == MOVE_BACK: room = move_to_living_room() elif (decision == INTERACT_WITH_CAT) and (have_ball_of_string == True): interact_with_cat() elif (decision == FEED_MOUSE) and (have_cheese == True) and (string_dropped == True): pot_of_soil_dry = feed_mouse() else: display_error() main()
true
24b9111c3b0a39a50079e3897c934f5fb622773a
Python
whitphx/stlite
/packages/sharing-editor/public/samples/011_component_gallery/pages/widget.checkbox.py
UTF-8
88
2.703125
3
[ "Apache-2.0" ]
permissive
import streamlit as st agree = st.checkbox("I agree") if agree: st.write("Great!")
true
266055bf5aac610145d1659d34215c386e9e9671
Python
ClarkeJ2000/CA117-Programming-2
/square_122.py
UTF-8
979
3.546875
4
[]
no_license
#!/usr/bin/env python3 import sys import math def trim(a): trimmed = [] for x in a: if '\n' in x: trimmed.append(x[:-1]) else: trimmed.append(x) return trimmed def distance(a, b, c, d): distance = math.sqrt((c - a) ** 2 + (d - b) ** 2) return distance def main(): lines = sys.stdin.readlines() line = trim(lines) new_list = [] i = 0 while i < len(lines): lines[i] = lines[i].split() new_list.append(lines[i]) i = i + 1 x1 = int(new_list[0][0]) y1 = int(new_list[0][1]) x2 = int(new_list[1][0]) y2 = int(new_list[1][1]) x3 = int(new_list[2][0]) y3 = int(new_list[2][1]) d1 = distance(x1, y1, x2, y2) d2 = distance(x2, y2, x3, y3) d3 = distance(x3, y3, x1, y1) if d1 > d2: print(x1 + x2 - x3, y1 + y2 - y3) elif d2 > d3: print(x2 + x3 - x1, y2 + y3 - y1) elif d3 > d1: print(x3 + x1 - x2, y3 + y1 - y2) if __name__ == '__main__': main()
true
2d69fdab55c93d516472aafbb07e9f5d40e5cbaf
Python
fourswordsio/SpaceX-Chainlink-Adapter
/elonmusk.py
UTF-8
761
2.609375
3
[]
no_license
import requests class SpaceX: def __init__(self): self._api_endpoint = "https://api.spacexdata.com/v3/launches/next" def get_launch_info(self): response = requests.get(self._api_endpoint).json() try: flight_data = { "launch_time": response["launch_date_utc"], "mission_id": str(response["mission_id"][0]), "mission_name": response["mission_name"], "flight_number": response["flight_number"], "rocket_name": response["rocket"]["rocket_name"], "launch_center": response["launch_site"]["site_name_long"] } return flight_data except Exception as error: return error
true
e91215ac23c3c23fbfb78d658f246b503a89bfdb
Python
sisyphean-labs/json-toolkit
/json-to-csv
UTF-8
381
2.75
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 import argparse import csv import json import sys def main(): parser = argparse.ArgumentParser(description="Converts json on stdin to csv on stdout") args = parser.parse_args() rows = json.load(sys.stdin) csv_writer = csv.writer(sys.stdout, dialect='unix') csv_writer.writerows(rows) exit(0) if __name__ == "__main__": main()
true
560e5e8018ab906ac393dec557ad68d8f4c71681
Python
guiaramos/algorithms-data-structures
/python/challenges/anagrams.py
UTF-8
1,025
3.953125
4
[]
no_license
# checkAnagrams check if two strings are anagrams O(n) def checkAnagrams(firstString, secondString): # check if the length is same if len(firstString) != len(secondString): return False # create a lookup dict for record the frequency of letters freqFirstString = {} # loop thru the first string and increase the count for each letter for letter in firstString: if letter in freqFirstString: freqFirstString[letter] += 1 else: freqFirstString[letter] = 1 # loop thru the second string for letter in secondString: if letter in freqFirstString: # check if the letter is present on freq dict if freqFirstString[letter] == 0: # if freq is 0 than return false return False else: # decrease the count of the frequency freqFirstString[letter] -= 1 else: return False return True checkAnagrams('anagram', 'nagaram')
true
8714fd8a085abf03c19870adf199a031329cfd69
Python
vranand1/empirical_workshop_2021
/1_reproducibility_KLC_intro/time.py
UTF-8
405
4.15625
4
[]
no_license
####################################### # Printing the time every 10 seconds ## ####################################### # libraries used import time # first statement print("This file tells you the time after every 10 seconds.") # print the time after every 10 seconds for i in range(10000): print("The time is now: " + time.strftime("%X") + ". Time flies when you are on KLC.") time.sleep(10)
true
2d64264f055ea325fd0375a27a1a194f1f675c55
Python
sayakchak/SnackDown2019
/Qualifier.py
UTF-8
478
2.796875
3
[]
no_license
sum = 0 T = int(input()) if T>1000 or T<1: exit(0) for i in range(T): N, K = [int(x) for x in input().split()] sum += N if K<1 or N<1 or K>N or K>100000 or N>100000 or sum>1000000: exit(0) S = [int(x) for x in input().split()] if min(S)<1 or max(S)>1000000000: exit(0) S.sort() S.reverse() score = S[K-1] c = 0 for j in range(N-1, -1, -1): if S[j] == score: break c += 1 print(N-c)
true
2dfdc52d4ae7a361fe74813367dba6f755acf019
Python
lruhlen/project_euler
/python/problem3.py
UTF-8
1,480
4.125
4
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue Nov 1 23:15:38 2016 @author: lruhlen Problem 3: The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ # Code import numpy as np def get_next_prime(): list_of_primes = [2] while True: current_max_prime = max(list_of_primes) yield current_max_prime candidate = current_max_prime + 1 while 0 in [candidate%n for n in list_of_primes]: candidate +=1 list_of_primes.append(candidate) def get_prime_factor_ceiling(n): return int(np.sqrt(n)) def factor_once(n): ceiling = get_prime_factor_ceiling(n) prime_faucet = get_next_prime() this_factor = next(prime_faucet) loop_counter = 0 while (this_factor <= ceiling): loop_counter += 1 if n % this_factor == 0: return this_factor else: this_factor = next(prime_faucet) return n def factor_full(n): denom = factor_once(n) if denom > 1: return max(denom, factor_full(n/denom)) else: return max(denom, n/denom) # Tests assert get_prime_factor_ceiling(26) == 5, "get_prime_factor_ceiling \ returned incorrect answer" assert factor_full(2) == 2, "factor_full(2) returned incorrect answer" assert factor_full(4) == 2, "factor_full(4) returned incorrect answer" assert factor_full(13195)== 29, "factor(13195) failed to return 29" print factor_full(600851475143)
true
56463773a9b46746f2610de9f1fb1a9a04b36935
Python
JasonGlazer/EP-Launch3
/eplaunch/tests/utilities/test_version.py
UTF-8
1,728
2.828125
3
[]
no_license
import unittest import os from eplaunch.utilities.version import Version class TestVersion(unittest.TestCase): def test_numeric_version_from_string(self): v = Version() self.assertEqual(v.numeric_version_from_string("8.1.0"), 80100) self.assertEqual(v.numeric_version_from_string("8.8.8"), 80808) self.assertEqual(v.numeric_version_from_string("8.7"), 80700) self.assertEqual(v.numeric_version_from_string("8.6-dfjsuy"), 80600) self.assertEqual(v.numeric_version_from_string("8.4.2-dfjsuy"), 80402) self.assertEqual(v.numeric_version_from_string("7.12.13"), 71213) def test_line_with_no_comment(self): v = Version() self.assertEqual(v.line_with_no_comment(" object, ! this is a comment"), "object,") self.assertEqual(v.line_with_no_comment("! this is a comment"), "") self.assertEqual(v.line_with_no_comment(" object, "), "object,") def test_check_energyplus_version(self): v = Version() # the version object is on one line file_path = os.path.join(os.path.dirname(__file__), "Minimal.idf") is_version_found, version_string, version_number = v.check_energyplus_version(file_path) self.assertTrue(is_version_found) self.assertEqual(version_string, "8.9") self.assertEqual(version_number, 80900) # the version object is spreads across two lines file_path = os.path.join(os.path.dirname(__file__), "Minimal2.idf") is_version_found, version_string, version_number = v.check_energyplus_version(file_path) self.assertTrue(is_version_found) self.assertEqual(version_string, "8.9.1") self.assertEqual(version_number, 80901)
true
cdd2018273518cf35e20caf2322154f73f0cd146
Python
ywyz/IntroducingToProgrammingUsingPython
/Exercise03/3-6.py
UTF-8
244
3.203125
3
[ "Apache-2.0" ]
permissive
''' @Date: 2019-08-19 17:46:38 @Author: ywyz @LastModifiedBy: ywyz @Github: https://github.com/ywyz @LastEditors: ywyz @LastEditTime: 2019-08-19 17:46:39 ''' number = eval(input("Enter an ASCII code: ")) print("The character is ", chr(number))
true
501cb7117f643eda44f060522ae3758b05d95ef7
Python
akey96/Programacion-Taller-
/project/model/vo/movement.py
UTF-8
793
3.171875
3
[]
no_license
#!/usr/bin/python3 # -*- coding: utf-8 -*- class Movement(): def __init__(self): self.__time = None self.__movement = None self.__pincer = None # setters of atrribs def __settime(self, timeM): self.__time = timeM def __setmovement(self, movement): self.__movement = movement def __setpincer(self, pincer): self.__pincer = pincer # getters of at def __gettime(self): return self.__time def __getmovement(self): return self.__movement def __getpincer(self): return self.__pincer # properties of attrib time = property(fget=__gettime, fset=__settime) movement = property(fget=__getmovement, fset=__setmovement) pincer = property(fget=__getpincer, fset=__setpincer)
true
9023dbf12f559f133e88976efe07b5429eeac080
Python
KevvinHoo/MGC
/grace_dl/torch/compressor/mgc.py
UTF-8
2,836
2.53125
3
[]
no_license
import torch from grace_dl.torch import Compressor class MGC(Compressor): # def __init__(self, compress_ratio): super().__init__(tensors_size_are_same=False) self.compress_ratio = compress_ratio def compress(self, tensor, name): shape = tensor.size() tensor = tensor.flatten() numel = tensor.numel() sample_shape = [max(1, int(numel * 0.01))] sample_index = torch.empty(sample_shape).uniform_(0, numel).type(torch.long) # Sample sample_tensor = tensor[sample_index] thr = torch.mean(sample_tensor.abs()) mask = tensor.abs() >= thr selected = mask.sum() for _ in range(10): if selected > 1.3 * numel * self.compress_ratio: thr = 1.3 * thr elif selected < 0.7 * numel * self.compress_ratio: thr = 0.7 * thr else: break mask = tensor.abs() >= thr selected = mask.sum() indices, = torch.where(mask) values = tensor[indices] ################################################################################################################ # upperbound = torch.max(values.abs()) # Apply the MAX VALUE in the abs of the tensor instead of the norm of tensor # lowwerbound = torch.min(values.abs()) upperbound = torch.max(values.abs()) lowwerbound = torch.min(values.abs()) upperbound = upperbound.flatten() lowwerbound = lowwerbound.flatten() abs_gradient = values.abs() level_float = 127 / (upperbound - lowwerbound) * (abs_gradient - lowwerbound) previous_level = level_float.floor() prob = torch.empty_like(values).uniform_() is_next_level = (prob < (level_float - previous_level)).type(torch.float32) new_level = (previous_level + is_next_level) sign = values.sign() tensor_compressed = (new_level * sign).type(torch.int16) tensor_compressed = tensor_compressed.type(torch.int8) ctx = shape, numel, upperbound, lowwerbound return [tensor_compressed, indices], ctx def decompress(self, tensor_compressed, ctx): shape, numel, upperbound, lowwerbound = ctx values, indices = tensor_compressed # tensor_compressed, upperbound, lowwerbound = values decode_output = values.type(torch.float32) value = (upperbound - lowwerbound) / 127 * decode_output + lowwerbound ################################################################################################################ tensor_decompressed = torch.zeros(numel, dtype=value.dtype, layout=value.layout, device=value.device) tensor_decompressed.scatter_(0, indices, value) return tensor_decompressed.view(shape)
true
cc8328f13a6515433d7efdbe833fcea2ec14fb1e
Python
AdamZhouSE/pythonHomework
/Code/CodeRecords/2578/60792/258944.py
UTF-8
257
3.171875
3
[]
no_license
import math def Sum(list1,n): sum=0 for i in range(0,len(list1)): sum=sum+math.ceil(list1[i]/n) return sum list1=list(map(int,input().split(","))) n=int(input()) i=1 sum=Sum(list1,1) while sum>n: i=i+1 sum=Sum(list1,i) print(i)
true
7dcfe80e56632bcdde709f06389aa83e6a8907e1
Python
prajwollamichhane11/ML-Algorithm-Tutorial-Implementations
/Dual Variable Linear Regression/DualVar_linregression.py
UTF-8
1,693
3.578125
4
[]
no_license
from numpy import * def compute_error_for_line_given_points(b,m,points): totalError = 0 for i in range(0, len(points)): x = points[i,0] y = points[i,1] totalError += (y-(m*x + b)) **2 return totalError/float(len(points)) def gradient_descent_runner(points, starting_b, starting_m, learning_rate, num_iterations): b = starting_b m = starting_m #gradient Descent Algorithm for i in range(num_iterations): b, m = step_gradient(b,m, array(points), learning_rate) return ([b,m]) def step_gradient(b_current,m_current, points, learningRate): b_gradient = 0 m_gradient = 0 N = float(len(points)) for i in range(0, len(points)): x = points[i,0] y = points[i,1] #direction with respect to b and m #computing partial derivative of our error function b_gradient += -(2/N) * (y - ((m_current * x) + b_current)) m_gradient += -(2/N) * x * (y - ((m_current * x) + b_current)) #updating the b and m values using the partial derivatives new_b = b_current - (learningRate * b_gradient) new_m = m_current - (learningRate * m_gradient) return [new_b, new_m] def run(): #1 points = genfromtxt('data.csv',delimiter=',') #2 #define hyperparameters learning_rate = 0.0001 #y=mx+b initial_b = 0 initial_m = 0 num_iterations = 1000 #3 training our model print("starting gradient descent at b = {0},m={1}, error ={2}".format(initial_b,initial_m,compute_error_for_line_given_points(initial_b,initial_m,points))) [b,m] = gradient_descent_runner(points,initial_b,initial_m,learning_rate,num_iterations) print("ending gradient descent at b = {1},m={2}, error ={3}".format(num_iterations,b,m,compute_error_for_line_given_points(b,m,points))) run()
true
79e55f05b82c07ef53bb5ceb747c431e9198149d
Python
LuckyLub/python-onsite
/week_04/web_scraping/01_your_page.py
UTF-8
772
2.984375
3
[]
no_license
''' Using python's request library, retrieve the HTML of the website you created that now lives online at <your-gh-username>.github.io/<your-repo-name> BONUS: extend your python program so that it reads your original HTML file and returns True if the HTML from the response is the same as the the contents of the original HTML file. <<<<<<< HEAD ''' import requests import os url = "https://lubcountcooper.github.io/my_sites/" file = "/home/robert-jan/Documents/CodingNomads/Extras/my_sites/topics_overview.html" with os.fdopen(os.open(file, os.O_RDONLY), "r") as fin: original = fin.read() content = requests.get(url).text if original == content: print(True) else: print(False) ''' >>>>>>> 52cba3b05b42df043df4904b236c3e044812bb5f'''
true
7b935300ea75a8f1cd354b606362f871b43c48bb
Python
OrianaLombardi/Python-
/fundamentos/listas-ej.py
UTF-8
182
3.421875
3
[]
no_license
#for numero in range(10): # if numero%3==0: # print(numero) listaNumeros=[0,1,2,3,4,5,6,7,8,9,10] for numero in listaNumeros: if numero%3 ==0: print(numero)
true
f7388ec2ac672a7433fde4e5b7f9121c36bfc08b
Python
jzcoder/dfwpythoneers_asyncio
/exercises/48_executor_process_pool.py
UTF-8
960
2.734375
3
[]
no_license
""" Use a ProcessPoolExecutor instead of default thread pool. Note: The overhead compared to thread pool executor. But, it was really easy to switch to the process pool. """ import asyncio, demo, time, os from concurrent.futures import ProcessPoolExecutor NUM_TASKS = 20 def blocking_call(timeout, ndx): demo.LOG(f"Executing blocking call; ndx={ndx}; pid={os.getpid()}") time.sleep(timeout) return ndx async def wait_task(pool, timeout, ndx): demo.LOG_TASK_START('wait_task', ndx) ndx = await asyncio.get_event_loop().run_in_executor(pool, blocking_call, timeout, ndx) demo.LOG_TASK_END() return ndx if __name__ == '__main__': loop = asyncio.get_event_loop() pool = ProcessPoolExecutor(20) cors = [wait_task(pool, 5, i+1) for i in range(0, NUM_TASKS)] fut = asyncio.gather(*cors) start_time = loop.time() result = loop.run_until_complete(fut) loop.close() demo.LOG(f'result={result}')
true
ace38ade56fccf36cbedd9839d10608e66d5fc2c
Python
sergey-msu/notebook
/ml/how-to/scipy.py
UTF-8
1,557
3.046875
3
[]
no_license
import scipy.stats as sts # Optimization from scipy import optimize def f(x): return (x[0] - 3.2)**2 + (x[1] - 1)**4 + 3 x_min = optimize.minimize(f) x_min.x # [3.2 1] # Solve SLE from scipy import linalg A = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]]) b = np.array([2, 4, -1]) x = linalg.solve(A, b) # [2. -2. 9.] # Interpolation from scipy import interpolate x = np.arange(0, 10) y = np.exp(-x/3.0) f = interpolate.interpld(x, y, kind='quadratic') x_new = np.arange(0, 10, 0.1) y_new = f(x_new) # Generate normal distribution mu = 2.0 sigma = 0.5 norm_rv = sts.norm(loc=mu, scale=sigma) x = norm_rv.rvs(size=4) # [2.42471807, 2.89001427, 1.5406754 , 2.218372] # Generate uniform distribution a = 1 b = 4 uniform_rv = sts.uniform(a, b-a) x = uniform_rv.rvs(size=4) # [2.90068986, 1.30900927, 2.61667386, 1.82853085] # Generate Bernoulli distribution p = 0.7 bernoulli_rv = sts.bernoulli(p) x = bernoulli_rv.rvs(size=4) # [1, 1, 1, 0] # Generate binomial distribution n = 20 p = 0.7 binom_rv = sts.binom(n, p) x = binom_rv.rvs(size=4) # [13, 15, 13, 14] # Generate Poisson distribution lam = 5 poisson_rv = sts.poisson(lam) x = poisson_rv.rvs(size=4) # [6, 10, 4, 4] # Custom discrete random variable elements = np.array([1, 5, 12]) probabilities = [0.05, 0.7, 0.25] np.random.choice(elements, 4, p=probabilities) # [5, 12, 5, 5] # z - quantiles of normal distribution sts.norm.ppf(1-0.05/2) # for 95% interval
true
a586a8bd6d1f4468dd069b1bd382e161a9020946
Python
karmueo/traclus_impl
/integ_tests/deer_tests/traclus_runner.py
UTF-8
881
2.515625
3
[]
no_license
''' Created on Jan 20, 2016 @author: Alex ''' from traclus_impl.coordination import run_traclus from deer_file_reader import read_test_file import os import cProfile """ This is useful for profiling performance on the datasets in this directory""" def run_deer_stuff(): file = os.path.join(os.path.dirname(__file__), "elk_1993.tra") points = read_test_file(file) traj_res = run_traclus(point_iterable_list=points, epsilon=32, min_neighbors=7, \ min_num_trajectories_in_cluster=2, min_vertical_lines=7, min_prev_dist=0.0) print "heres the output: " + str(traj_res) print "about to print out the lines" for traj in traj_res: print "A new average trajectory:" for point in traj: print str(point) print "done" if __name__ == '__main__': cProfile.run('run_deer_stuff()')
true
9a13f66221d8e8c4c11b2752eba926ada73e8566
Python
denkho/CourseraPython
/week1/ex_18.py
UTF-8
249
3.28125
3
[]
no_license
# За день машина проезжает N километров. # Сколько дней нужно, чтобы проехать маршрут длиной M километров? n, m = int(input()), int(input()) print((n + m - 1) // n)
true
e304dbda40fa9460d23800d868f2d7c082e480a7
Python
waldisjr/JuniorIT
/_2019_2020/Classworks/_18_18_01_2020/_1.py
UTF-8
333
3.421875
3
[]
no_license
import string ab = ['abc','cv','Fd','fg','eYty','eryT',] def f(a): abc = string.ascii_lowercase minn = len(ab[0]) for i in a: if len(i) <= minn: minn = len(i) varients = [] for i in a: if len(i) == minn: i = i.lower() varients.append(i) c = f(ab) print(c)
true
b65c79fad62ac98ae8cc21368b17d700b3bfb649
Python
wemporcode/SDPerfTool
/lmdd.py
UTF-8
2,754
2.515625
3
[]
no_license
#!/usr/bin/python __author__ = 'bigzhang' import datetime from pyadb import ADB from lmdd_processor import LmddProcessor from lmdd_speed import LmddSpeed from optparse import OptionParser target_list=['data', 'sdcard', 'sdcard1'] if __name__ == '__main__': usage = "usage: %prog [-d target]{-t times}" parser = OptionParser() parser.add_option('-t', '--times', dest = "times", help = "Test Times", default = 10, type = "int") parser.add_option('-d', '--dest', dest = "target", help = "The target test path, data or sdcard or sdcard1", type = "string") (options, args) = parser.parse_args() # get adb path for config file. adb_conf = open('adb.conf', 'r') adbpath = adb_conf.readlines() adb_conf.close() if adbpath == []: print "Please config ADB PATH!" exit(0) adb = ADB() adb.set_adb_path(adbpath[0]) # verity ADB path if adb.check_path() is False: print "ERROR: ADB PATH NOT Correct." exit(-2) # get detected devices dev = 0 while dev is 0: print "Detecting devices..." , error,devices = adb.get_devices() if len(devices) == 0: print "[+] No devices detected!" print "Waiting for devices..." adb.wait_for_device() continue elif error is 2: print "You haven't enought permissions!" exit(-3) print "OK" dev = 1 # adb need run as root adb.set_adb_root() adb.wait_for_device() # built log and xlsx file name with datetime current_time = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") speed_file = 'lmdd_perf_' + current_time + '.log' xlsx_file = 'lmdd_perf_' + current_time + '.xlsx' # built SPEED Tester. test_times = options.times test_target = options.target if test_target not in target_list: print 'PLEASE INPUT TARGET PATH!' print '--- Target: data or sdcard or sdcard1 ---' print '--- Target: data or sdcard or sdcard1 ---' print '--- Target: data or sdcard or sdcard1 ---' exit(0) else: print 'Test Target:%s' %test_target tester = LmddSpeed(test_times, None, adb, test_target) list_size = tester.get_list_size() input_file = open(speed_file, 'wb+') tester.lmdd_header(input_file) tester.prepare_env() tester.lmdd_write(input_file) tester.lmdd_read(input_file) tester.finish() # Analyse speed log and built xlsx report processor = LmddProcessor(xlsx_file, test_times, list_size) input_file = open(speed_file, 'r') lines = input_file.readlines() processor.parse(lines)
true