index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
35,131
|
derick-droid/pythonbasics
|
refs/heads/main
|
/list.py
|
# using while loops in list
# verifying users
prev_user = ["derrick", "okinda", "kibaso"]
new_users = []
current_user = []
while prev_user:
new_users = prev_user.pop()
print(f"verifying: {new_users}")
current_user.append(new_users)
print("the following users have been confirmed:")
for user in current_user:
print(user)
print()
# Removing All Instances of Specific Values from a List
pets = ["cats", "pigs", "dogs", "horse", "cats", "cats", "cats"]
while "cats" in pets:
pets.remove("cats")
print(pets)
|
{"/module.py": ["/largest_number.py"]}
|
35,132
|
derick-droid/pythonbasics
|
refs/heads/main
|
/movie.py
|
# 7-5. Movie Tickets: A movie theater charges different ticket prices depending on
# a person’s age. If a person is under the age of 3, the ticket is free; if they are
# between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is
# $15. Write a loop in which you ask users their age, and then tell them the cost
# of their movie ticket.
while True:
age = int(input("enter age: "))
if age < 3:
print("your ticket is free")
elif age <= 12:
print("your ticket is $10")
else:
print("your ticket is $15")
|
{"/module.py": ["/largest_number.py"]}
|
35,133
|
derick-droid/pythonbasics
|
refs/heads/main
|
/diif_21.py
|
# Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21.
#
# diff21(19) → 2
# diff21(10) → 11
# diff21(21) → 0
def diff_21(n):
if n <= 21:
return abs(n - 21)
else:
return (abs(n - 21)) * 2
|
{"/module.py": ["/largest_number.py"]}
|
35,134
|
derick-droid/pythonbasics
|
refs/heads/main
|
/ifstatement.py
|
is_hot = False
is_cold = False
if is_hot:
print("it is a hot day")
print("drink a plenty of water")
elif is_cold:
print("it is a cold day ")
print("wear warm clothes")
else:
print("it is a lovely day")
print("enjoy your day")
# IF STATEMENTS EXERCISE
mark_price = 1000000
good_credit = False
if good_credit:
down_payment = mark_price * 0.1
print(f"price: ${down_payment}")
else:
down_payment = mark_price * 0.2
print(f"price: ${down_payment}")
print("thank you for purchasing with us")
|
{"/module.py": ["/largest_number.py"]}
|
35,135
|
derick-droid/pythonbasics
|
refs/heads/main
|
/tuplecrash.py
|
# 4-13. Buffet: A buffet-style restaurant offers only five basic foods. Think of five
# simple foods, and store them in a tuple.
# • Use a for loop to print each food the restaurant offers.
# • Try to modify one of the items, and make sure that Python rejects the
# change.
# • The restaurant changes its menu, replacing two of the items with different
# foods. Add a block of code that rewrites the tuple, and then use a for
# loop to print each of the items on the revised menu.
buffet_style = ("chips", "chickens", "pork", "beef")
for items in buffet_style:
print(items)
print()
buffet_style1 = ("chips", "chickens","pizza", "mutton")
for food in buffet_style1:
print(food)
|
{"/module.py": ["/largest_number.py"]}
|
35,136
|
derick-droid/pythonbasics
|
refs/heads/main
|
/comparison.py
|
# >,>, >=,<=,==, !=
temperature = 30
if temperature >= 35:
print("it is hot day ")
else:
print("it is a lovely day")
#COMPARISON OPERATOR EXERSICE
name = input("name: ")
if len(name) < 3: # LEN FUNCTION COUNT NUMBER OF CHARACTERS ENTERED BY THE USER
print("characters must be at least 3")
elif len(name) > 10:
print("character must be at most 10")
else:
print("lovely name")
|
{"/module.py": ["/largest_number.py"]}
|
35,137
|
derick-droid/pythonbasics
|
refs/heads/main
|
/rectangle.py
|
for row in range(4):
for col in range(8):
if (col == 0 or col == 7 ) or (row == 0 or row == 3):
print("*", end=" ")
else:
print(end=" ")
print()
|
{"/module.py": ["/largest_number.py"]}
|
35,138
|
derick-droid/pythonbasics
|
refs/heads/main
|
/functions.py
|
def pop ():
""" description of greeting"""
print("hello")
print("come")
pop()
print("jaya")
print()
# passing information to a function
def great_user(name):
print(f"hello {name} ")
great_user("john")
|
{"/module.py": ["/largest_number.py"]}
|
35,139
|
derick-droid/pythonbasics
|
refs/heads/main
|
/fronttimes.py
|
# Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front;
#
# front_times('Chocolate', 2) → 'ChoCho'
# front_times('Chocolate', 3) → 'ChoChoCho'
# front_times('Abc', 3) → 'AbcAbcAbc'
def front_times(str, n):
for i in range(n):
if len(str) == 3:
print(str * n, end="")
elif len(str) < 3:
print(str * n, end="")
elif len(str) > 3:
print(str[:4] * n, end="")
pop = front_times("abc", 3 )
|
{"/module.py": ["/largest_number.py"]}
|
35,140
|
derick-droid/pythonbasics
|
refs/heads/main
|
/main.py
|
# exceptions helps to limit codes from crushing
try:
age = int(input("age: "))
income = 20000
rate = income // age
print(age)
print(rate)
except ValueError:
print("invalid value")
except ZeroDivisionError:
print("invalid age value")
|
{"/module.py": ["/largest_number.py"]}
|
35,141
|
derick-droid/pythonbasics
|
refs/heads/main
|
/default.py
|
def describe_pet(animal_name, animal_type = "dog"):
print(f"\n I have {animal_type}")
print(f"my {animal_type} name is {animal_name}")
describe_pet("willie")
|
{"/module.py": ["/largest_number.py"]}
|
35,142
|
derick-droid/pythonbasics
|
refs/heads/main
|
/optional.py
|
# optional arguments
def user_names(first_name, last_name, middle_name = ""):
if middle_name:
full_name = first_name + " " + middle_name + " " + last_name + "."
return full_name
else:
full_name = first_name + " " + last_name + "."
return full_name
musician = user_names("Omari", "hardwick", "jj")
print(musician)
|
{"/module.py": ["/largest_number.py"]}
|
35,143
|
derick-droid/pythonbasics
|
refs/heads/main
|
/return.py
|
def get_formatted(first_name, last_name):
full_name = (first_name + " " + last_name + ".")
return full_name.title()
musian = get_formatted("john", "timothy")
print(musian)
|
{"/module.py": ["/largest_number.py"]}
|
35,144
|
derick-droid/pythonbasics
|
refs/heads/main
|
/dictionarycsdojo.py
|
naming = {
"geogre": 24,
"derrick": 23,
"enock": 34,
"jehova": 23
}
for keys, values in naming.items():
print("keys")
print(keys)
print("values")
print(values)
print(" ")
|
{"/module.py": ["/largest_number.py"]}
|
35,145
|
derick-droid/pythonbasics
|
refs/heads/main
|
/nest2dic.py
|
# creating nested dictionary with for loop
aliens = []
for alien_number in range (30):
new_alien = {
"color" : "green",
"point" : 7,
"speed" : "high"
}
aliens.append(new_alien)
print(aliens)
for alien in aliens[:5]:
if alien["color"] == "green":
alien["color"] == "red"
alien["point"] == 8
alien["speed"] == "very high"
print(alien)
|
{"/module.py": ["/largest_number.py"]}
|
35,146
|
derick-droid/pythonbasics
|
refs/heads/main
|
/files.py
|
# checking files in python
open("employee.txt", "r") # to read the existing file
open("employee.txt", "a") # to append information into a file
employee = open("employee.txt", "r")
# employee.close() # after opening a file we close the file
print(employee.readable()) # this is to check if the file is readable
print(employee.readline()) # this helps read the first line
print(employee.readline()) # this helps to read the second line after the first line
print(employee.readline()[0]) # accessing specific data from the array
# looping through a file in python
for employees in employee.readline():
print(employee)
# adding information into a file
employee = open("employee.txt", "a")
print(employee.write("\n derrick -- for ICT department"))
employee.close()
# re writing a new file or overwriting a file
employee = open("employee1.txt", "w")
employee.write("kelly -- new manager")
|
{"/module.py": ["/largest_number.py"]}
|
35,147
|
derick-droid/pythonbasics
|
refs/heads/main
|
/keyword_argument.py
|
def welcoming_greet(first_name, last_name):
print(f"hi {first_name} {last_name} ")
print("welcome abroad ")
print("hey new employee")
welcoming_greet(first_name="john", last_name="monly") # keyword argument
welcoming_greet("derrick", "okinda") # positional argument/ positional argument do come first before keyword argument
print("thanking fo accepting our call")
|
{"/module.py": ["/largest_number.py"]}
|
35,148
|
derick-droid/pythonbasics
|
refs/heads/main
|
/exits.py
|
# 7-6. Three Exits: Write different versions of either Exercise 7-4 or Exercise 7-5
# that do each of the following at least once:
# • Use an active variable to control how long the loop runs.
# • Use a break statement to exit the loop when the user enters a 'quit' value.
# active
active = True
while active:
message = int(input("enter age: "))
if message == 0:
active = False
elif message < 3:
print("your ticket is free")
elif message <= 12:
print("your ticket is $10")
else:
print("your ticket is $15")
print()
# break
while True:
message = input("enter age: ")
if message == "quit":
break
else:
print(f"your {message} is")
|
{"/module.py": ["/largest_number.py"]}
|
35,149
|
derick-droid/pythonbasics
|
refs/heads/main
|
/inputwhileloops.py
|
# prompt helps when one wants to display along message
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print(name)
print()
# use int() input
# determining the appropriaate height to ride a bicycle
height = int(input("what is your height: "))
if height >= 72:
print("yo are qualified to ride")
else:
print("Not qualified to ride ")
# module operator can be used to to find even numbers while demonstrating the basics of user input
number = int(input("enter number: "))
if number % 2 == 0:
print("it is even number")
else:
print("it is odd number ")
|
{"/module.py": ["/largest_number.py"]}
|
35,150
|
derick-droid/pythonbasics
|
refs/heads/main
|
/persona1.py
|
class Robots:
def __init__(self, name, color, weight):
self.name = name
self.color = color
self.weight = weight
def introduce_yourself(self):
print("my name is " + self.name)
print("I am " + self.color)
print("I weigh " + self.weight)
class Persona(Robots):
def __init__(self, name, personality, state):
self.name = name
self.personality = personality
self.state = state
r1 = Robots("Tom", "blue", "34kg")
r2 = Robots("Derrick", "yellow", "50kgs")
r1.introduce_yourself()
print(" ")
r2.introduce_yourself()
p1 = Persona("Alice", "aggressive", True)
p2 = Persona("Don", "talkative", False)
|
{"/module.py": ["/largest_number.py"]}
|
35,151
|
derick-droid/pythonbasics
|
refs/heads/main
|
/arguments.py
|
# positional argument
def my_pet (animal_type, animal_name):
print(f"\nI have {animal_type} ")
print(f"{animal_type} name is {animal_name} ")
my_pet("cat", "pusss")
# calling multiple functions
my_pet("dog", "rex")
|
{"/module.py": ["/largest_number.py"]}
|
35,152
|
derick-droid/pythonbasics
|
refs/heads/main
|
/forlooop.py
|
names = ["paul", "derrick", "enock", "dave"]
for name in names:
print(name)
# USING THE RANGE FUNCTIONS
for items in range (100): # THE FUNCTION IS USED TO WIDE RANGE OF VALUES RATHER THAN CODING
print(items)
# USING RANGE FUNCTIONS TO OUTPUT SEQUENCE OF NUMBERS
for items in range (2,10,2):
print(items)
# EXERCISE -- CALCULATING SUM OF PRICE IN A SHOPPING LIST
prices = [20, 30, 29, 647, 974,]
value = 0
for price in prices:
value += price
print(f"value: {value} ")
|
{"/module.py": ["/largest_number.py"]}
|
35,153
|
derick-droid/pythonbasics
|
refs/heads/main
|
/listcsdojo.py
|
a = [ 1, 2, 4, 6, 7, 8 ]
a.append(34)
print(a)
# adding a list into yhe list
a.append([1, 4, 5, 6, ])
print(a)
# swapping within the list
b = ["banana", "apple", "microsoft"]
temp = b[0]
b[0] = b[2]
b[2] = temp
print(b)
# using another method
b[1], b[2] = b[2], b[1]
print(b)
|
{"/module.py": ["/largest_number.py"]}
|
35,154
|
derick-droid/pythonbasics
|
refs/heads/main
|
/functinscsdojo.py
|
# functions as collection of codes
def function1():
print("this is s function ")
print("thi is still within the function")
print("this is outside the function")
# using function as a mapping
def function2(x, y):
return x + y
print("here we start ")
function1()
print(function2(3, 6))
|
{"/module.py": ["/largest_number.py"]}
|
35,155
|
derick-droid/pythonbasics
|
refs/heads/main
|
/randommss.py
|
import random
value = random.random() # random numbers between 1 and 0
print(value)
for i in range(3):
print(random.randint(20,56)) # this gives random numbers between numbers specified
members = ["derick", "john", "conf"]
leader = random.choice(members)
print(leader)
# exercise choosing random numbers
# dice game
class Dice:
def roll(self):
first = random.randint(1, 6)
second = random.randint(1, 6)
return first, second
dice1 = Dice()
print(dice1.roll())
|
{"/module.py": ["/largest_number.py"]}
|
35,156
|
derick-droid/pythonbasics
|
refs/heads/main
|
/testdic.py
|
# Person: Use a dictionary to store information about a person you know.
# Store their first name, last name, age, and the city in which they live. You
# should have keys such as first_name , last_name , age , and city . Print each
# piece of information stored in your dictionary.
person = {
"first_name" : "derrick",
"last_name" : "okinda",
"age" : 43,
"city" : "Nairobi"
}
print(person["first_name"])
print(person["last_name"])
print(person["age"])
print(person["city"])
print()
# Favorite Numbers: Use a dictionary to store people’s favorite numbers.
# Think of five names, and use them as keys in your dictionary. Think of a favorite
# number for each person, and store each as a value in your dictionary. Print
# each person’s name and their favorite number.
favorite_number = {
"derrick": 1,
"enock": 2,
"elisha": 3,
"charles": 4,
"denno": 5
}
print(" derrick's favorite number is " + str(favorite_number["derrick"]) + ".")
print("enock's favorite number is " + str(favorite_number["enock"]) + ".")
print("elisha's favorite number is " + str(favorite_number["elisha"]) + ".")
print("charles' favorite number is " + str(favorite_number["charles"]) + ".")
print("denno's favorite number is " + str(favorite_number["denno"]) + ".")
print()
# Glossary: A Python dictionary can be used to model an actual dictionary.
# However, to avoid confusion, let’s call it a glossary.
# • Think of five programming words you’ve learned about in the previous
# chapters. Use these words as the keys in your glossary, and store their
# meanings as values.
# • Print each word and its meaning as neatly formatted output. You might
# print the word followed by a colon and then its meaning, or print the word
# on one line and then print its meaning indented on a second line. Use the
# newline character ( \n ) to insert a blank line between each word-meaning
# pair in your output.
glossary = {
"pep" : "python enhancemnt proposal",
"programming" : "writing sets of instruction ",
"coding" : "writing codes",
}
print("pep \n" + glossary["pep"])
print("programming \n" + glossary["programming"])
print("coding \n" + glossary["coding"])
|
{"/module.py": ["/largest_number.py"]}
|
35,157
|
derick-droid/pythonbasics
|
refs/heads/main
|
/key argument.py
|
def my_pet(animal_name, animal_type):
print(f"\n I have {animal_name}")
print(f"{animal_name} is {animal_type}")
my_pet(animal_name="cat", animal_type="jesse")
|
{"/module.py": ["/largest_number.py"]}
|
35,158
|
derick-droid/pythonbasics
|
refs/heads/main
|
/persona.py
|
class Robots:
def __init__(self, name, color, weight):
self.name = name
self.color = color
self.weight = weight
def introduce_yourself(self):
print("my name is " + self.name )
print("I am " + self.color )
print("I weigh " + self.weight)
r1 = Robots("Tom", "blue", "34kg")
r2 = Robots("Derrick", "yellow", "50kgs")
r1.introduce_yourself()
print(" ")
r2.introduce_yourself()
|
{"/module.py": ["/largest_number.py"]}
|
35,159
|
derick-droid/pythonbasics
|
refs/heads/main
|
/whileloopcsdojo.py
|
# calculating total using while loops
total = 0
j = 1
while j < 5:
total += j
j += 1
print(total)
# adding elements in a list using while loop
numbers = [5, 4, 3, 2, 1, -1, -2, -3, ]
total2 = 0
i = 0
while i < len(numbers) and numbers[1] > 0:
total2 += i
i += 1
print(total2)
# adding elements in a list using while loop and breaks
numbers1 = [7, 5, 4, 3, 2, 1, -1, -2, -3, -4, -5, -6, -7]
result = 0
# i = 0
for items in numbers1:
if items < 0:
print(items)
result += items
print(result)
total3 = 0
i = -1
while numbers1[i] < 0:
total3 += i
i -= 1
print(numbers1[i])
print(i)
print(total3)
|
{"/module.py": ["/largest_number.py"]}
|
35,160
|
derick-droid/pythonbasics
|
refs/heads/main
|
/frontback.py
|
# Given a string, return a new string where the first and last chars have been exchanged.
#
# front_back('code') → 'eodc'
# front_back('a') → 'a'
# front_back('ab') → 'ba'
def front_back(str):
front = str[0]
back = str[-1]
mid = str[1:-1]
if len(str) <= 1:
print(str)
elif len(str) == 2:
print (back + front)
else:
print(back + mid + front)
pop = front_back("code")
|
{"/module.py": ["/largest_number.py"]}
|
35,161
|
derick-droid/pythonbasics
|
refs/heads/main
|
/funexer.py
|
# 8-1. Message: Write a function called display_message() that prints one sen-
# tence telling everyone what you are learning about in this chapter. Call the
# function, and make sure the message displays correctly.
def display_message ():
print("we are learning how to use finctions in this chapter")
display_message()
print()
# 8-2. Favorite Book: Write a function called favorite_book() that accepts one
# parameter, title . The function should print a message, such as One of my
# favorite books is Alice in Wonderland . Call the function, making sure to
# include a book title as an argument in the function call.
def favorite_book (name, title):
print(f"{name}'s favorite book is {title} ")
favorite_book("john", "Peeling back the mask")
|
{"/module.py": ["/largest_number.py"]}
|
35,162
|
derick-droid/pythonbasics
|
refs/heads/main
|
/pyramid.py
|
num = int(input("enter number of rows : "))
for i in range(0, num):
for j in range(i, num-1):
print(end=" ")
for j in range(i+1):
print("*", end=" ")
print()
|
{"/module.py": ["/largest_number.py"]}
|
35,163
|
derick-droid/pythonbasics
|
refs/heads/main
|
/dicdic.py
|
# dictionary inside dictionary
user_name = {
"derrick" : {
"first-name" : "okinda",
"last-name" : "kibaso",
"location" : "Thika town"
},
"ojwang": {
"first-name": "derrick",
"last-name": "ojwang'",
"location": "kiang'ombe"
}
}
for user, user_info in user_name.items():
print(user + "'s details are:")
full_name = user_info["first-name"] + " " + user_info["last-name"]
location = user_info["location"]
print(f" full name is:{full_name}")
print(f"loaction is : {location}")
|
{"/module.py": ["/largest_number.py"]}
|
35,164
|
derick-droid/pythonbasics
|
refs/heads/main
|
/classes.py
|
# creating a class for a dog
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(f"the dog {self.name} is now sitting")
def rollover(self):
print(f"{self.name} is rolling")
# creating instance of a class
my_dog = Dog("rex", 23)
print(f"my dog name is {my_dog.name}")
print(f"my dog is {my_dog.age} old")
|
{"/module.py": ["/largest_number.py"]}
|
35,165
|
derick-droid/pythonbasics
|
refs/heads/main
|
/simpledic.py
|
alien_0 = {
"colour" : "green",
"points" : 5
}
print(alien_0["colour"])
print(alien_0["points"])
new_alien = alien_0["points"]
print(f"your new point is {new_alien} that is very good")
print()
# adding values in dictionary
print(alien_0)
alien_0["x_coordinate"] = 0
alien_0["y_coordinate"] = 25
alien_0["size"] = "big head"
print(alien_0)
print()
# starting with an empty dictionary and adding values to it
students = {}
students["name"] = "derrick kibaso"
students["registration number"] = "ICT-G-4-0579-18"
print(students)
# Modifying Values in a Dictionary
print()
vampire = {
"color": "green",
}
print(vampire["color"])
vampire["color"] = "yellow"
print(vampire["color"])
# detailed example:
# to determine the speed of the vampire across its points
vampire["x_coordinate"] = 4
vampire["y_coordinate"] = 5
vampire["speed"] = "high speed"
print(vampire)
if vampire["speed"] == "medium":
x_increment = 1
elif vampire["speed"] == "high speed":
x_increment = 4
elif vampire["spedd"] == "extra speed":
x_increment = 5
new_point = vampire["x_coordinate"] + x_increment
print(f" new point: {new_point} ")
print()
# Removing Key-Value Pairs
print(vampire)
del vampire["y_coordinate"] # deleting key_value from dictionary
print(vampire)
print()
# A Dictionary of Similar Objects
favourite_languages = {
"derrick" : "java",
"sarah" : "c",
"don" : "pascal"
}
print("sarah's favourite language is " + favourite_languages["sarah"].title() + ".")
print(f"sarah is {favourite_languages["sarah"] } ")
|
{"/module.py": ["/largest_number.py"]}
|
35,166
|
derick-droid/pythonbasics
|
refs/heads/main
|
/2dlist.py
|
# 2D LISTS ARE EXAMPLE OF MATRICES
matrix = [
[1, 2, 3],
[3, 6, 8],
[6, 7, 9]
]
matrix[0] # INDEX 0 OF THE MATRIX REPRESENTS LISTS AVAILABLE IN THE LIST
print(matrix)
print(matrix[0] [1]) # ACCESSING VALUE IN THE INNER LIST
(matrix[0] [1])
print(matrix)
# ITERATING OVER A 2D LIST
matrix = [
[1, 2, 3],
[3, 6, 8],
[6, 7, 9]
]
for row in matrix:
for items in row:
print(items)
|
{"/module.py": ["/largest_number.py"]}
|
35,167
|
derick-droid/pythonbasics
|
refs/heads/main
|
/iflsttry.py
|
# 5-8. Hello Admin: Make a list of five or more usernames, including the name
# 'admin' . Imagine you are writing code that will print a greeting to each user
# after they log in to a website. Loop through the list, and print a greeting to
# each user:
# • If the username is 'admin' , print a special greeting, such as Hello admin,
# would you like to see a status report?
# • Otherwise, print a generic greeting, such as Hello Eric, thank you for log-
# ging in again.
usernames = ["derick-admin", "Erick", "charles", "yusuf"]
for name in usernames:
if name == "derick-admin":
print(f"Hello admin , would you like to see status report")
else:
print(f"Hello {name} , thank you for logging in again")
#
# 5-9. No Users: Add an if test to hello_admin.py to make sure the list of users is
# not empty.
# • If the list is empty, print the message We need to find some users!
# • Remove all of the usernames from your list, and make sure the correct
# message is printed.
users = ["deno", "geogre", "mulla", "naomi"]
users.clear()
if users:
for item in users:
print(f"hello {item}")
else:
print("we need at least one user")
print()
#
# 5-10. Checking Usernames: Do the following to create a program that simulates
# how websites ensure that everyone has a unique username.
# • Make a list of five or more usernames called current_users .
# • Make another list of five usernames called new_users . Make sure one or
# two of the new usernames are also in the current_users list.
# • Loop through the new_users list to see if each new username has already
# been used. If it has, print a message that the person will need to enter a
# new username. If a username has not been used, print a message saying
# that the username is available.
# •
# Make sure your comparison is case insensitive. If 'John' has been used,
# 'JOHN' should not be accepted.
web_users = ["derrick", "moses", "Raila", "john", "ojwang", "enock"]
new_users = ["derrick", "moses", "babu", "vicky", "dave", "denver"]
for user_name in new_users:
if user_name in web_users:
print("please enter a new user name ")
else:
print("the name already registered ")
print()
# 5-11. Ordinal Numbers: Ordinal numbers indicate their position in a list, such
# as 1st or 2nd. Most ordinal numbers end in th, except 1, 2, and 3.
# • Store the numbers 1 through 9 in a list.
# • Loop through the list.
# • Use an if - elif - else chain inside the loop to print the proper ordinal end-
# ing for each number. Your output should read "1st 2nd 3rd 4th 5th 6th
# 7th 8th 9th" , and each result should be on a separate line
ordinary_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in ordinary_numbers:
if number == 1:
print(f'{number}st')
elif number == 2:
print(f"{number}nd")
elif number == 3:
print(f"{number}rd")
else:
print(f"{number}th")
|
{"/module.py": ["/largest_number.py"]}
|
35,168
|
derick-droid/pythonbasics
|
refs/heads/main
|
/nestdic.py
|
aliens_0 = {
"color": "green",
"point": 6
}
alien_1 = {
"color": "yellow",
"point": 3
}
alien_2 = {
"color": "blue",
"point": 4
}
aliens = [alien_2, alien_1, aliens_0]
for alien in aliens:
print(alien)
print()
# using range function
alien1 = []
for alien_number in range(30):
new_alien = {
"color" : "green",
"speed" : "medium",
"point" : 8
}
alien1.append(new_alien)
print(alien1, end=" ")
# printing only the first five aliens
for alien_number in alien1[:5]:
print(alien_number)
|
{"/module.py": ["/largest_number.py"]}
|
35,169
|
derick-droid/pythonbasics
|
refs/heads/main
|
/listsmethod.py
|
# METHODS WE CAN BE USED TO OPERATE ON OUR LISTS
numbers = [5, 2, 6, 3, 2, 4, 8]
numbers.append(10) # THE APPEND FUNCTION IS USED TO ADD ITEMS IN THE LIST
print(numbers)
numbers.insert(0,23) # THE INSERT METHOD IS USED TO ADD ITEMS IN THE LIST AT ANY INDEX
print(numbers)
numbers.remove(5) # THE REMOVE FUNCTION IS USED TO REMOVE AN ITEM FROM THE LIST
print(numbers)
# numbers.clear() # THE CLEAR METHOD IS USED TO CLEAR ALL THE ITEMS FROM THE LIST
print(numbers)
numbers.pop() # THE POP METHOD IS USED TO REMOVE THE LAST ITEM IN THE LIST
print(numbers)
print(numbers.index(23)) # THE INDEX METHOD IS USED TO CHECK THE INDEX OF A VALUE IN A LIST
number = numbers.copy() # THE COPY METHOD IS USED TO COPY A LIST TO FORM A SIMILAR LIST
print(number)
print(50 in number) # THE IN OPERATOR CAN BE USED TO CHECK EXISTANCE OF AN ITEM IN A LIST
print(numbers.count(2) ) # THE COUNT METHOD CAN BE USED TO CHECK HOW MANY TIMES DOES AN ITEM APPEARS IN THE LIST
numbers.sort() # THE SORT METHOD IS USED TO ARRANGE THE FIGURES IN THE LIST IN ASCENDING ORDER
print(numbers)
numbers.reverse() # THE REVERSE METHOD IS USED TO REVERSE THE ARRANGEMENT VALUES IN A LIST
print(numbers)
# LIST METHOD EXERCISE
# TO REMOVE DUPLICATE IN A LIST
numbers2 = [5, 2, 2, 5, 6, 7, 8, 9]
new_list = []
for number in numbers2:
if number not in new_list:
new_list.append(number)
print(new_list)
|
{"/module.py": ["/largest_number.py"]}
|
35,170
|
derick-droid/pythonbasics
|
refs/heads/main
|
/sets.py
|
# sets sorting of data is not considered
# sets don't allow any duplication of data
# sets can be used to check if two sets share common data this can be by using the intersection function
course = {"maths", "Compsci", "chemistry", "history", "statistics", "Compsci"}
print(course)
print()
art_course = {"maths", "Compsci", "geography", "physics", "biology", "music"}
bus_course = {"maths", "computer ", "java ", "googles", "modes", "dental"}
print(course.intersection(art_course, bus_course))
print()
# want show not common data in the available sets we use the "difference" function
print(course.difference(art_course, bus_course))
# combine thes sets together we use the union function
print()
print(course.union(art_course, bus_course))
# creating empty set we the set function
empty_set = set()
|
{"/module.py": ["/largest_number.py"]}
|
35,171
|
derick-droid/pythonbasics
|
refs/heads/main
|
/functionbmiclculator.py
|
def bmi_calculator(name, height, weight ):
bmi = weight / (height ** 2)
print("your bmi is: ", bmi)
if bmi < 25:
print("hello " + name + " you have a normal bmi. ")
else:
print("hello " + name + " you have a normal bmi.")
return bmi
bmi1 = bmi_calculator("derrick okinda", 23, 45)
bmi1 = bmi_calculator("edna okinda", 23, 45)
bmi1 = bmi_calculator("asenath viki okinda", 23, 45)
|
{"/module.py": ["/largest_number.py"]}
|
35,172
|
derick-droid/pythonbasics
|
refs/heads/main
|
/numbers.py
|
print(2+3) # the addition operation in python
print(4_4) # the subtraction operation in python
print(3*6) # the multiplication operation in python
print(10 % 3) # the modulus operation which gives the remainder as answer
print(10 / 3) # this is a divisional operation
print(10//3) # this gives a whole answer and ignores the remainder
print(3**2) # this shows the power
# THE METHODS USED
print(abs(-10)) # this brings absolute value of a number
print(pow(3, 2)) # this also gives power of a value
print(max(4, 6)) # this shows the maximum number
print(min(4, 6)) # this shows the minimum number
print(round(3.22)) # this rounds off the value of a number
# importing other maths function
from math import *
print(floor(3.7)) # the floor method prints lowest value and ignores the decimal places
print(ceil(3.2)) # this will round off the number whatever the values are available
print(sqrt(36)) # this will the square root of an umber
|
{"/module.py": ["/largest_number.py"]}
|
35,173
|
derick-droid/pythonbasics
|
refs/heads/main
|
/upside_reightangle.py
|
num = int(input("enter row: "))
for i in range(num, 0 , -1):
for j in range(0, num-1):
print(end="")
for j in range(0,i):
print("*", end=" ")
print()
|
{"/module.py": ["/largest_number.py"]}
|
35,174
|
derick-droid/pythonbasics
|
refs/heads/main
|
/reusable_function.py
|
# USABLE FUNCTION HELPS TO AVOID CODING MORE CODES
def welcoming_greet(name):
print(f"hi {name} there")
name = input("what is your name: ")
print(name)
welcoming_greet(name)
|
{"/module.py": ["/largest_number.py"]}
|
35,175
|
derick-droid/pythonbasics
|
refs/heads/main
|
/module.py
|
# from largest_number import largest_number
# biggest_number = largest_number(numbers)
# print(biggest_number)
from largest_number import find_biggest_number
numbers = [2, 3, 73, 83, 27, 7, ]
biggest_number = find_biggest_number(numbers)
print(biggest_number)
|
{"/module.py": ["/largest_number.py"]}
|
35,176
|
derick-droid/pythonbasics
|
refs/heads/main
|
/dictionarycorey.py
|
students = {
"name ": "derick",
"age ": 25,
"course ": ["maths", "programming"]
}
print(students["name "])
print(students["age "])
print(students["course "])
print()
# accessing values which are not in the dictionary without getting an error
print(students.get("phone", "not found"))
# adding values into the dictionary
print()
students["name "] = "dave"
print(students.get("name ", "not found"))
print()
# updating the dictionary we use the the update function
students.update({"name ":"javan", "phone ":555})
print(students)
# deleting data from a dictionary we use the del funtion
print()
del students["age "]
print(students)
print()
# we can also use the pop function
age = students.pop("name ")
print(students)
print(age)
# looping over a dictionary
for key, value in students.items():
print(key, value)
|
{"/module.py": ["/largest_number.py"]}
|
35,177
|
derick-droid/pythonbasics
|
refs/heads/main
|
/strings.py
|
print("GIRAFFE")
print("Giraffe\nAcademy") # the \n is used to create new tab between the strings
print("Giraffe\"academy") # the escalation inserts quotation in between the words
phrase = "giraffe academy" # storing string in a variable
print(phrase)
# contenation of a string
print(phrase + " is cool")
# using the string methods
print(phrase.lower()) # converting to lower case
print(phrase.upper()) # converting to upper case
print(phrase.isupper()) # is used to check if string is upper case
print(phrase.islower()) # is used to check if string is in lower case
print(phrase.upper().isupper()) # thi is also applicable
print(len(phrase)) # the len function shows total number characters present in a string
print(phrase[0]) # accessing the individual characters from a string
print(phrase.index("a")) # the index function helps to allocate the index of a character in a string
print(phrase.replace("giraffe", "lion")) # the replace function is used to replace an existing character in a string with another
|
{"/module.py": ["/largest_number.py"]}
|
35,178
|
derick-droid/pythonbasics
|
refs/heads/main
|
/condtion.py
|
language = "python"
if language == "java":
print("The language is java")
elif language == "python":
print("language is python")
else:
print("there is no match at all")
# using the booleans
# and
user = "admin page"
logged_in = False
if user and logged_in == True:
print("welcome admin")
# or
if user or logged_in == True:
print("it is done")
# not
if not logged_in:
print("please log in ")
# using is value
a = [1, 2, 3]
b= [1, 2, 3 ]
print(a is b)
|
{"/module.py": ["/largest_number.py"]}
|
35,179
|
derick-droid/pythonbasics
|
refs/heads/main
|
/exerinput.py
|
# 7-1. Rental Car: Write a program that asks the user what kind of rental car they
# would like. Print a message about that car, such as “Let me see if I can find you
# a Subaru.”
car = input("what car do you want: ")
print(f"let me see if I can get {car}")
print()
# 7-2. Restaurant Seating: Write a program that asks the user how many people
# are in their dinner group. If the answer is more than eight, print a message say-
# ing they’ll have to wait for a table. Otherwise, report that their table is ready.
people = int(input("how many people are in your dinner group: "))
if people > 8:
print("sorry you will have to wait for a table")
else:
print("The table is ready")
print()
# 7-3. Multiples of Ten: Ask the user for a number, and then report whether the
# number is a multiple of 10 or not.
number = int(input("enter number: "))
if number % 10 == 0:
print("it is multiple of 10")
else:
print("not multiple of 10")
|
{"/module.py": ["/largest_number.py"]}
|
35,180
|
derick-droid/pythonbasics
|
refs/heads/main
|
/listcorey.py
|
courses = ["history", "geography", "maths", "compsci"]
# using for loop to access both index and items in the list
for index, course in enumerate(courses): # we use the enumerate function
print(index, course)
print()
# if we want to start from index 1 we add start statement
for index, course in enumerate(courses, start=1):
print(index, course)
print()
# we can turn list into a string
course_str = "-".join(courses)
print(course_str)
print()
# return a string into list
# create a new variable
new_list = course_str.split("-")
print(new_list)
|
{"/module.py": ["/largest_number.py"]}
|
35,181
|
derick-droid/pythonbasics
|
refs/heads/main
|
/ifstatementcsdojo.py
|
a = 1
b = 2
if a < b:
print("a is less than b")
else:
print("a is greater than b")
# more of if statements
f = 18
j = 4
if f > j + 10:
print("f is greater than j by 10")
elif j > f +10:
print("j is greater than f by 10")
else:
print("none of the above comparison")
# more of if statement
h = 18
z = 23
if h > z:
print("h is greater than z ")
else:
if h == z:
print("the two variables are equal to each other")
else:
print("h is less than z")
|
{"/module.py": ["/largest_number.py"]}
|
35,182
|
derick-droid/pythonbasics
|
refs/heads/main
|
/largest_number.py
|
# def largest_number(numbers):
# biggest_number = numbers[0]
# for number in numbers:
# if number > biggest_number:
# biggest_number = number
# return biggest_number
# numbers = [2, 3, 73, 83, 27, 7, ]
def find_biggest_number(numbers):
biggest_number = numbers[0]
for number in numbers:
if number > biggest_number:
biggest_number = number
return biggest_number
|
{"/module.py": ["/largest_number.py"]}
|
35,183
|
derick-droid/pythonbasics
|
refs/heads/main
|
/flags.py
|
prompt = "\nenter your message here please:"
prompt += "\n enter message:"
# using flags in while loops
active = True
while active:
message = input(prompt)
if message.lower() == "quit":
active = False
else:
print(message)
|
{"/module.py": ["/largest_number.py"]}
|
35,184
|
derick-droid/pythonbasics
|
refs/heads/main
|
/pizza.py
|
# 7-4. Pizza Toppings: Write a loop that prompts the user to enter a series of
# pizza toppings until they enter a 'quit' value. As they enter each topping,
# print a message saying you’ll add that topping to their pizza.
# exercise on while loops basics
prompt = "\n enter a serie of pizza toppings "
prompt += "\n enter toppings: "
while True:
message = input(prompt)
if message.lower() == "quit":
break
else:
print(f"we will add {message} to your pizza")
|
{"/module.py": ["/largest_number.py"]}
|
35,185
|
derick-droid/pythonbasics
|
refs/heads/main
|
/nestedloops.py
|
for x in range (5):
for y in range (4):
print(f"{x}, {y} ")
#EXERCISE OF NESTED LOOPS
numbers = [5, 2, 5, 2, 2 ]
for number in numbers: # BUT NO NESTED LOOPS USED
print("*" * number)
# USING NESTED LOOPS
numbers = [5, 2, 5, 2, 2]
for number in numbers:
output = ""
x_counts = output
for item in x_counts:
print("*" * item)
|
{"/module.py": ["/largest_number.py"]}
|
35,186
|
derick-droid/pythonbasics
|
refs/heads/main
|
/lists.py
|
# BASIC IN LST
name = ["derrick", "john", "mosh", "sarah"]
print(name)
# USING INDEX TO RETRIEVE VALUE FROM A LIST
name = ["derrick", "john", "mosh", "sarah"]
print(name[0]) # PRINTING VALUE AT INDEX ZERO
print(name[2:]) # PRINTING VALUE FROM INDEX 2 TO THE LAST INDEX IN THE LIST
print(name[:]) # PRINTS THE WHOLE VALUE IN A LISTS
print(name[1:3]) # PRINTING VALUE FROM INDEX 1 TO INDEX 3 BUT IGNORES THE VALUE AT 3RD INDEX
name[0] ="jon"
print(name) # CORRECTING AN ERROR MADE IN LIST
# LIST EXERCISE
# FINDING THE LARGEST VALUE IN A LIST
numbers = [13332,7353,38373,9837,34353,29277,3535637,]
great_value = 0
for number in numbers:
if number > great_value:
great_value = number
print(f"the largets value: {great_value} ")
|
{"/module.py": ["/largest_number.py"]}
|
35,187
|
derick-droid/pythonbasics
|
refs/heads/main
|
/loops[lst].py
|
# looping over a list of an item
magicians = ["alice", "nana", "caroh"]
for magician in magicians:
print(f"{magician.title()} you did a good work")
print("I cannot wait to see your next trick \n")
# exercise
# 4-1. Pizzas: Think of at least three kinds of your favorite pizza. Store these
# pizza names in a list, and then use a for loop to print the name of each pizza.
# • Modify your for loop to print a sentence using the name of the pizza
# instead of printing just the name of the pizza. For each pizza you should
# have one line of output containing a simple statement like I like pepperoni
# pizza.
# • Add a line at the end of your program, outside the for loop, that states
# how much you like pizza. The output should consist of three or more lines
# about the kinds of pizza you like and then an additional sentence, such as
# I really love pizza!
pizza_name = [" Neapolitan Pizza", "chicago pizza", "Greek pizza"]
for pizza in pizza_name:
print(f"i like {pizza} , it is my favourite")
print("I really like pizza")
# exercise 2
#
# 4-2. Animals: Think of at least three different animals that have a common char-
# acteristic. Store the names of these animals in a list, and then use a for loop to
# print out the name of each animal.
# 60 Chapter 4
# • Modify your program to print a statement about each animal, such as
# A dog would make a great pet.
# • Add a line at the end of your program stating what these animals have in
# common. You could print a sentence such as Any of these animals would
# make a great pet!
animals_name = ["dog", "cat", "horse"]
for animals in animals_name:
print(f"{animals} can make a good pet")
print("I like pets")
|
{"/module.py": ["/largest_number.py"]}
|
35,188
|
derick-droid/pythonbasics
|
refs/heads/main
|
/files and directories.py
|
from pathlib import Path
path = Path()
for file in path.glob("*.py"):
print(file)
# Absolute path
# relative path
path = Path("ecommerce")
print(path.exists()) # exists method checks the presence of a directory
# print(path.mkdir()) # to make a directory
# print(path.rmdir()) # this is to remove a directory
# glob method ro search files in a directory
|
{"/module.py": ["/largest_number.py"]}
|
35,189
|
derick-droid/pythonbasics
|
refs/heads/main
|
/parameter.py
|
def welcoming_greet(first_name, last_name):
print(f"hi {first_name} {last_name} ")
print("welcome abroad ")
print("hey new employee")
welcoming_greet("john", "monly")
welcoming_greet("derrick", "okinda")
print("thanking fo accepting our call")
|
{"/module.py": ["/largest_number.py"]}
|
35,190
|
derick-droid/pythonbasics
|
refs/heads/main
|
/listfunctions.py
|
lucky_numbers = [1, 2, 3, 4, 5, 6, 7]
friends = ["derrick", "jim", "jim", "trump", "majani" ]
friends.extend(lucky_numbers) # to add another list on another list
print(friends)
print(friends.count("jim")) # to count repetitive objects in a list
|
{"/module.py": ["/largest_number.py"]}
|
35,191
|
derick-droid/pythonbasics
|
refs/heads/main
|
/pastrami.py
|
# 7-9. No Pastrami: Using the list sandwich_orders from Exercise 7-8, make sure
# the sandwich 'pastrami' appears in the list at least three times. Add code
# near the beginning of your program to print a message saying the deli has
# run out of pastrami, and then use a while loop to remove all occurrences of
# 'pastrami' from sandwich_orders . Make sure no pastrami sandwiches end up
# in finished_sandwiches .
sandwich_orders = ["tuna", "Classic club", "Ham and Cheese", "pastrami", "pastrami", "pastrami"]
finished_sandwiches = []
while sandwich_orders:
if "pastrami" in sandwich_orders:
sandwich_orders.remove("pastrami") # removing pastrami from the list using while loop
making_sandwiches = sandwich_orders.pop()
print(f"I made your {making_sandwiches}")
finished_sandwiches.append(making_sandwiches)
print()
for sandwich in finished_sandwiches:
print(f"I made {sandwich} very delicious")
|
{"/module.py": ["/largest_number.py"]}
|
35,192
|
derick-droid/pythonbasics
|
refs/heads/main
|
/logicaloperator.py
|
has_high_income = True
has_good_credit = True
has_criminal_record = False
if has_high_income and has_good_credit:
print("eligible for loan")
elif has_good_credit or not has_criminal_record:
print("eligible for loan")
elif has_good_credit and has_high_income and not has_criminal_record:
print("eligible for loan")
|
{"/module.py": ["/largest_number.py"]}
|
35,193
|
derick-droid/pythonbasics
|
refs/heads/main
|
/listcomprehension.py
|
# doubling elements in a list
a = [1, 34, 6, 54, 344, 4555, 4]
b = []
for elements in a:
multiple = elements * 2
b.append(multiple)
print(b)
# list comprehension
b = [elements * 2 for elements in a]
print(b)
|
{"/module.py": ["/largest_number.py"]}
|
35,194
|
derick-droid/pythonbasics
|
refs/heads/main
|
/return_statements.py
|
def square(number):
return number * number # it returns the value of a function to the user
print(square(3))
|
{"/module.py": ["/largest_number.py"]}
|
35,195
|
derick-droid/pythonbasics
|
refs/heads/main
|
/lstnumbers.py
|
# 4-3. Counting to Twenty: Use a for loop to print the numbers from 1 to 20,
for i in range(1, 21):
print(i)
# 4-4. One Million: Make a list of the numbers from one to one million, and then
# use a for loop to print the numbers. (If the output is taking too long, stop it by
# pressing ctrl -C or by closing the output window.)
numbers = list(range(1, 1000001))
for item in numbers:
print(item)
#
# 4-5. Summing a Million: Make a list of the numbers from one to one million,
# and then use min() and max() to make sure your list actually starts at one and
# ends at one million. Also, use the sum() function to see how quickly Python can
# add a million numbers.
numbers1 = list(range(1, 1000001))
print()
print(max(numbers1))
print()
print(min(numbers1))
print()
print(sum(numbers1))
#
# 4-6. Odd Numbers: Use the third argument of the range() function to make a list
# of the odd numbers from 1 to 20. Use a for loop to print each number.
odd_numbers = list(range(1, 20, 2))
for number in odd_numbers:
print(number)
#
# 4-7. Threes: Make a list of the multiples of 3 from 3 to 30. Use a for loop to
# print the numbers in your list.
threes = list(range(3, 30, 3))
for numberz in threes:
print(numberz)
# . Cubes: A number raised to the third power is called a cube. For example,
# the cube of 2 is written as 2**3 in Python. Make a list of the first 10 cubes (that
# is, the cube of each integer from 1 through 10), and use a for loop to print out
# the value of each cube.
print()
cube = []
num = list(range(1,10))
for num1 in num:
cube1 = num1 ** 3
cube.append(cube1)
print(cube)
print()
# 4-9. Cube Comprehension: Use a list comprehension to generate a list of the
# first 10 cubes.
cubecomp = [value ** 3 for value in range(1, 10)]
print(cubecomp)
|
{"/module.py": ["/largest_number.py"]}
|
35,196
|
derick-droid/pythonbasics
|
refs/heads/main
|
/deli.py
|
# 7-8. Deli: Make a list called sandwich_orders and fill it with the names of vari-
# ous sandwiches. Then make an empty list called finished_sandwiches . Loop
# through the list of sandwich orders and print a message for each order, such
# as I made your tuna sandwich. As each sandwich is made, move it to the list
# of finished sandwiches. After all the sandwiches have been made, print a
# message listing each sandwich that was made.
sandwich_orders = ["tuna", "Classic club", "Ham and Cheese"]
finished_sandwiches = []
while sandwich_orders:
making_sandwiches = sandwich_orders.pop()
print(f"I made your {making_sandwiches}")
finished_sandwiches.append(making_sandwiches)
print()
for sandwich in finished_sandwiches:
print(f"I made {sandwich} very delicious")
|
{"/module.py": ["/largest_number.py"]}
|
35,197
|
derick-droid/pythonbasics
|
refs/heads/main
|
/listdic.py
|
# stores information of pizza being ordered
pizza = {
"crust" : "thirst",
"topping" : ["mushroom", "extra cheese"]
}
# summary of the order
print("Your ordered pizza " + pizza["crust"] + "-crust pizza has the following toppings: ")
for item in pizza["topping"]:
print(item)
# more examples
students = {
"derrick" : ["python", "Java", "c++", "javascript"],
"Kibaso" : ["HTML", "css", "javascript"]
}
for name, languages in students.items():
print(name.title() + "'s favourite language is: " )
for language in languages: # because it is a list for loop over through to print each element
print(language)
|
{"/module.py": ["/largest_number.py"]}
|
35,198
|
derick-droid/pythonbasics
|
refs/heads/main
|
/stringsploison.py
|
# Given a non-empty string like "Code" return a string like "CCoCodCode".
#
# string_splosion('Code') → 'CCoCodCode'
# string_splosion('abc') → 'aababc'
# string_splosion('ab') → 'aab'
def string_splosion(str):
result = ""
for itmes in str:
if len(str) <= 1:
print(str)
elif len(str) > 1:
print((str[0] * 2) + str[1] + str[-1])
pop = string_splosion("abc")
|
{"/module.py": ["/largest_number.py"]}
|
35,199
|
derick-droid/pythonbasics
|
refs/heads/main
|
/exponent functions.py
|
def large_number(base_number, power_number):
result = 1
for index in range(power_number):
result = result * base_number
return result
print(large_number(3, 2))
|
{"/module.py": ["/largest_number.py"]}
|
35,200
|
derick-droid/pythonbasics
|
refs/heads/main
|
/dictionary.py
|
# returning dictionary in functionn
def user_dictionary (first_name, last_name):
full = {
"first_name" : first_name,
"last_name" : last_name
}
return full
musician = user_dictionary("ford", "dancan")
print(musician)
# using optinal values in dictionary
def dev_person(occupation, age, home_town = ""):
if home_town:
person = {
"occupation" : occupation,
"age" : age,
"home_town" : home_town
}
return person
else:
person = {
"occupation" : occupation,
"age" : age
}
return person
user = dev_person("software developer", "23", "Migori")
print(user)
|
{"/module.py": ["/largest_number.py"]}
|
35,201
|
derick-droid/pythonbasics
|
refs/heads/main
|
/triangle pattern.py
|
row = int(input("enter row: "))
column = int(input("enter column: "))
for i in range(row, column):
print("*" * i)
|
{"/module.py": ["/largest_number.py"]}
|
35,202
|
derick-droid/pythonbasics
|
refs/heads/main
|
/forlooptechnique.py
|
for i in range(1, 10):
print(i+1, "-----derrick")
print()
for i in range(10):
print("derrick")
print()
for i in range(3, 7):
print(i, "---derrick")
print()
for i in range(5, 2, -1):
print(i, "---derrick")
|
{"/module.py": ["/largest_number.py"]}
|
35,203
|
derick-droid/pythonbasics
|
refs/heads/main
|
/continue.py
|
# using continue in while loops .continue is used to tell python to ignore the code and move the beginning of the loop
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
else:
print(current_number)
|
{"/module.py": ["/largest_number.py"]}
|
35,204
|
derick-droid/pythonbasics
|
refs/heads/main
|
/stringbits.py
|
# Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
#
# string_bits('Hello') → 'Hlo'
# string_bits('Hi') → 'H'
# string_bits('Heeololeo') → 'Hello'
#
def string_bits(str):
# for items in str:
if len(str) == 1:
print(str[0])
elif len(str) > 1:
print(str[0] + str[-1] + str[1:-1])
pop = string_bits("hello")
# more solutions
def string_bits(str):
result = ""
# Many ways to do this. This uses the standard loop of i on every char,
# and inside the loop skips the odd index values.
for i in range(len(str)):
if i % 2 == 0:
result = result + str[i]
return result
|
{"/module.py": ["/largest_number.py"]}
|
35,205
|
derick-droid/pythonbasics
|
refs/heads/main
|
/ifcrash.py
|
# 5-3. Alien Colors #1: Imagine an alien was just shot down in a game. Create a
# variable called alien_color and assign it a value of 'green' , 'yellow' , or 'red' .
# • Write an if statement to test whether the alien’s color is green. If it is, print
# a message that the player just earned 5 points.
# • Write one version of this program that passes the if test and another that
# fails. (The version that fails will have no output.)
alien_color = "green"
if alien_color == "green":
print("you have earned 5 points")
print()
# 5-4. Alien Colors #2: Choose a color for an alien as you did in Exercise 5-3, and
# write an if - else chain.
# 88 Chapter 5
# • If the alien’s color is green, print a statement that the player just earned
# 5 points for shooting the alien.
# • If the alien’s color isn’t green, print a statement that the player just earned
# 10 points.
# • Write one version of this program that runs the if block and another that
# runs the else block.
alien_colorz = "green"
if alien_colorz == "green":
print("you have 5 points")
else:
print("you have earned 10 points")
print()
# 5-5. Alien Colors #3: Turn your if - else chain from Exercise 5-4 into an if - elif -
# else chain.
# • If the alien is green, print a message that the player earned 5 points.
# • If the alien is yellow, print a message that the player earned 10 points.
# • If the alien is red, print a message that the player earned 15 points.
# • Write three versions of this program, making sure each message is printed
# for the appropriate color alien.
alien_colorz = "green"
alien_colorz = "red"
alien_colorz = "yellow"
if alien_colorz == "green":
print("you have earned 5 points")
elif alien_colorz == "red":
print("you have earned 10 points")
elif alien_colorz == "red":
print("you have earned 15 points")
print()
# 5-6. Stages of Life: Write an if - elif - else chain that determines a person’s
# stage of life. Set a value for the variable age , and then:
# • If the person is less than 2 years old, print a message that the person is
# a baby.
# • If the person is at least 2 years old but less than 4, print a message that
# the person is a toddler.
# • If the person is at least 4 years old but less than 13, print a message that
# the person is a kid.
# • If the person is at least 13 years old but less than 20, print a message that
# the person is a teenager.
# • If the person is at least 20 years old but less than 65, print a message that
# the person is an adult.
# • If the person is age 65 or older, print a message that the person is an
# elder.
age = int(input("enter age: "))
if age < 2:
print("The person is a baby")
elif age < 4:
print("The person is a todler")
elif age < 13:
print("The person is a kid")
elif age < 20:
print("The person is a teenager")
elif age < 65:
print("The person is an Adult")
elif age >= 65:
print("The person is an elder")
print()
# 5-7. Favorite Fruit: Make a list of your favorite fruits, and then write a series of
# independent if statements that check for certain fruits in your list.
# • Make a list of your three favorite fruits and call it favorite_fruits .
# • Write five if statements. Each should check whether a certain kind of fruit
# is in your list. If the fruit is in your list, the if block should print a statement,
# such as You really like bananas!
favourite_fruit = ["banana", "avocado", "straw berry", "grapes"]
if "banana" in favourite_fruit:
print(f"you like banana ")
|
{"/module.py": ["/largest_number.py"]}
|
35,206
|
derick-droid/pythonbasics
|
refs/heads/main
|
/arraycounts.py
|
# Given an array of ints, return the number of 9's in the array.
#
# array_count9([1, 2, 9]) → 1
# array_count9([1, 9, 9]) → 2
# array_count9([1, 9, 9, 3, 9]) → 3
def array_count9(nums):
count = 0
# Standard loop to look at each value
for num in nums:
if num == 9:
count = count + 1
print(count)
pop = array_count9([1,9,9,9])
|
{"/module.py": ["/largest_number.py"]}
|
35,207
|
derick-droid/pythonbasics
|
refs/heads/main
|
/slicelst.py
|
# 4-10. Slices: Using one of the programs you wrote in this chapter, add several
# lines to the end of the program that do the following:
# • Print the message, The first three items in the list are:. Then use a slice to
# print the first three items from that program’s list.
# • Print the message, Three items from the middle of the list are:. Use a slice
# to print three items from the middle of the list.
# • Print the message, The last three items in the list are:. Use a slice to print
# the last three items in the list.
numbers = [1, 3, 2, 4, 5, 6, 7, 8, 9]
slice1 = numbers[:3]
slice2 = numbers[4:]
slice3 = numbers[-3:]
print(f"The first three items in the list are:{slice1}")
print(f"The items from the middle of the list are:{slice2}")
print(f"The last three items in the list are:{slice3}")
print()
# 4-11. My Pizzas, Your Pizzas: Start with your program from Exercise 4-1
# (page 60). Make a copy of the list of pizzas, and call it friend_pizzas .
# Then, do the following:
# • Add a new pizza to the original list.
# • Add a different pizza to the list friend_pizzas .
# • Prove that you have two separate lists. Print the message, My favorite
# pizzas are:, and then use a for loop to print the first list. Print the message,
# My friend’s favorite pizzas are:, and then use a for loop to print the sec-
# ond list. Make sure each new pizza is stored in the appropriate list.
print()
pizzas = ["chicago pizza", "new york_style pizza", "greek pizza", "neapolitans pizza"]
friends_pizza = pizzas[:]
pizzas.append("sicilian pizza")
friends_pizza.append("Detroit pizza")
print(f"my favourite pizzas are:{pizzas}")
print()
print(f"my friend favourite pizzas are:{friends_pizza}")
print()
print("my favourite pizzas are: ")
for pizza in pizzas:
print(pizza)
print()
print("my favourite pizzas are: ")
for items in friends_pizza:
print(items)
print()
#
# 4-12. More Loops: All versions of foods.py in this section have avoided using
# for loops when printing to save space. Choose a version of foods.py, and
# write two for loops to print each list of foods.
food_stuff = ["cake", "rice", "meat", "ice cream", "banana"]
food = ["goat meat", "pilau", "egg stew", "fried", "meat stew"]
for foodz in food_stuff:
print(foodz)
print()
for itemz in food:
print(itemz)
|
{"/module.py": ["/largest_number.py"]}
|
35,208
|
derick-droid/pythonbasics
|
refs/heads/main
|
/tuples.py
|
# TUPLES ARE SIMILAR WITH LIST EXCEPT TUPLES CANNOT BE MODIFIED (THEY ARE IMMUTABLE)
# TUPLE A(LSO PARENTHESIS INSTEAD OF SQUARE BRACKETS
numbers = (1, 3, 4)
print(numbers)
print(numbers.count(4)) # THE COUNT METHOD IS USED TO COUNT ITEMS IN A TUPLE
print(numbers.index(4)) # THE INDEX METHOD IS USED TO SHOW THE INDEX OF A VALUE IN A TUPLE
|
{"/module.py": ["/largest_number.py"]}
|
35,209
|
derick-droid/pythonbasics
|
refs/heads/main
|
/constructor.py
|
# constructor is the function being called at the time of creating objects
class Point:
# constructor
def __init__(self, x, y):
self.x = x
self.y = y
def move(self):
print("move")
def draw(self):
print("draw")
point = Point(10, 37)
print(point.y)
print(point.x)
# EXERCISE
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def talk(self):
print(f" {self.first_name}is talking ")
print(f"{self.last_name} is taking")
name1 = Person("derrick", "okinda")
print(name1.first_name)
name1.talk()
print(name1.last_name)
name1.talk()
|
{"/module.py": ["/largest_number.py"]}
|
35,210
|
derick-droid/pythonbasics
|
refs/heads/main
|
/diamondshape.py
|
num = int(input("enter row: "))
num1 = int(input("enter row1: "))
# upright pyramid code
for i in range(0, num):
for j in range(0, num-i-1):
print(end=" ")
for j in range(0, i+1):
print("*", end=" ")
print()
# combining the codes to form a diamond shape
# inverse pyramid code
for i in range(num, 0, -1):
for j in range(0, num1-i):
print(end=" ")
for j in range(0, i):
print("*", end=" ")
print()
|
{"/module.py": ["/largest_number.py"]}
|
35,211
|
derick-droid/pythonbasics
|
refs/heads/main
|
/bools.py
|
# showing how to use data type in python
def are_you_sad(is_raining, has_umbrella):
if is_raining and not has_umbrella:
print(True)
else:
print(False)
are_you_sad(True, False)
are_you_sad(True, True)
# more exercise
def c_greater_than_d_plus_e(c, d, e):
# c= 48
# d = 3
# e = 8
d_plus_e = d + e
if c > d_plus_e:
print(True)
else:
print(False)
c_greater_than_d_plus_e(48, 3, 8)
c_greater_than_d_plus_e(1, 5, 8)
|
{"/module.py": ["/largest_number.py"]}
|
35,212
|
derick-droid/pythonbasics
|
refs/heads/main
|
/loopsdic.py
|
# Looping Through All Key-Value Pairs
user_0 = {
"user_name" : "arridez",
"first_name" : "derrick",
"last_name" : "beatrice",
}
for key, value in user_0.items():
print("key: \n" + key)
print("value: \n" + value)
print()
# Looping Through All the Keys in a Dictionary
favorite_languages = {
"seth" : "python",
"don" : "ruby",
"jack" : "php"
}
friends = ["seth", "jack"]
for name in favorite_languages.keys():
print(name)
print()
# checking and comparing other list and then give a message
for name, language in favorite_languages.items():
if "dave" not in favorite_languages:
print("please Dave register your name")
if name in friends:
print(f" Hi {name} your friends favorite language is {language}")
print()
# Looping Through a Dictionary’s Keys in Order
for name in sorted(favorite_languages.keys()):
print(f" Hi programmers {name}")
print()
# Looping Through All Values in a Dictionary
for value in favorite_languages.values():
print(value)
print()
# using set to remove duplicate sin the dictionary
for value in set(favorite_languages.values()):
print(value)
|
{"/module.py": ["/largest_number.py"]}
|
35,217
|
Veldrovive/alpha-zero-test
|
refs/heads/main
|
/arena.py
|
import logging
import numpy as np
from tqdm import tqdm
from gameV2 import Gomaku
from tree_search import TreeSearch
log = logging.getLogger(__name__)
class Arena:
def __init__(self, player1: TreeSearch, player2: TreeSearch, game: Gomaku, verbose=False):
self.player1 = player1
self.player2 = player2
self.game = game
self.verbose = verbose
def play_game(self):
# Plays a single game between player1 and player2
# Returns 1 if player1 won or -1 if player2 won
players = {
-1: self.player2,
1: self.player1
}
curr_player = 1
board = self.game.get_initial_board()
iterations = 0
while self.game.game_state(board) is None: # While game is ongoing
iterations += 1
player = players[curr_player]
player_board = self.game.from_perspective(board, curr_player)
action = np.argmax(player.get_action_probs(player_board, temp=0))
valid_moves = self.game.get_valid_moves(player_board)
if valid_moves[action] == 0:
raise Exception("Chosen move was invalid")
board, curr_player = self.game.advance_game(board, curr_player, action)
return curr_player * self.game.game_state(board)
def play_round(self, num_games: int):
# Plays num_games/2 games with player1 starting and num_games/2 games with player2 starting
num1 = num_games // 2
num2 = num_games-num1
player_1_won = 0
player_2_won = 0
draws = 0
for _ in tqdm(range(num1), desc="Arena.playGames (1)"):
game_result = self.play_game()
if game_result == 1:
player_1_won += 1
elif game_result == -1:
player_2_won += 1
else:
draws += 1
self.player1, self.player2 = self.player2, self.player1
for _ in tqdm(range(num2), desc="Arena.playGames (2)"):
game_result = self.play_game()
if game_result == -1:
player_1_won += 1
elif game_result == 1:
player_2_won += 1
else:
draws += 1
return player_1_won, player_2_won, draws
|
{"/arena.py": ["/gameV2.py", "/tree_search.py"], "/tree_search.py": ["/gameV2.py", "/agent.py"], "/agent.py": ["/gameV2.py"], "/trainer.py": ["/gameV2.py", "/agent.py", "/tree_search.py", "/arena.py"], "/main.py": ["/gameV2.py", "/agent.py", "/trainer.py"]}
|
35,218
|
Veldrovive/alpha-zero-test
|
refs/heads/main
|
/tree_search.py
|
import logging
import numpy as np
from gameV2 import Gomaku
from agent import Agent
log = logging.getLogger(__name__)
EPS = 1e-8
class TreeSearch:
"""
Handles monte carlo search tree operations
"""
def __init__(self, game: Gomaku, agent: Agent, args):
self.game = game
self.agent = agent
self.args = args
self.q_vals = {}
self.n_edge_visits = {}
self.n_state_visits = {}
self.state_initial_policy = {}
self.state_game_ended = {}
self.state_valid_moves = {}
def get_action_probs(self, board: np.ndarray, temp: int = 1):
log.debug("Getting action probabilities with board:\n%s", self.game.to_string(board))
for i in range(self.args["numMCTSSims"]):
log.debug("Initializing new monte carlo search: %d", i)
self.search(board) # Run a bunch of monte carlo simulations
str_board = self.game.to_string(board)
# We will use http://ccg.doc.gold.ac.uk/ccg_old/papers/browne_tciaig12_1.pdf page 5 section 3 robust child selection
counts = np.array([self.n_edge_visits[(str_board, action)] if (str_board, action) in self.n_edge_visits else 0 for action in range(self.game.get_actions_size())])
if temp == 0:
# Choose only the best action. This is done at inference time and later in training
best_action_count = np.max(counts)
best_actions = np.argwhere(counts == best_action_count).flatten()
chosen_best_action = np.random.choice(best_actions)
probs = np.zeros(len(counts))
probs[chosen_best_action] = 1
return probs
# Use a slightly randomized action space
counts = counts ** (1 / temp)
probs = counts / np.sum(counts)
return probs
def search(self, board: np.ndarray):
log.debug("Started search")
str_board = self.game.to_string(board)
if str_board not in self.state_game_ended:
# TODO: Make sure that this game over works with the value function
self.state_game_ended[str_board] = self.game.game_state(board)
if self.state_game_ended[str_board] is not None:
return -1*self.state_game_ended[str_board]
if str_board not in self.state_initial_policy:
# Then this is a leaf to our tree
self.state_initial_policy[str_board], state_value = self.agent.predict(board)
valid_moves = self.game.get_valid_moves(board)
self.state_initial_policy[str_board] *= valid_moves # Mask invalid moves
valid_moves_sum = np.sum(self.state_initial_policy[str_board])
if valid_moves_sum > 0:
self.state_initial_policy[str_board] /= valid_moves_sum # Normalize to a probability distribution
else:
# If no move the agent wants to make is valid, make a random valid move.
log.info("Making random move from: %s", valid_moves)
self.state_initial_policy[str_board] += valid_moves / np.sum(valid_moves)
self.state_valid_moves[str_board] = valid_moves
self.n_state_visits[str_board] = 0 # This is initialized here and updated lower down. We do not count an initial check as a visit
return -state_value
valid_moves = self.state_valid_moves[str_board]
best_q = -float("inf")
best_action = -1
for action in np.where(valid_moves == 1)[0]:
if (str_board, action) in self.q_vals:
u = self.q_vals[(str_board, action)] + self.args["cpuct"] * self.state_initial_policy[str_board][action] * np.sqrt(self.n_state_visits[str_board]) / (1 + self.n_edge_visits[(str_board, action)])
else:
u = 0 + self.args["cpuct"] * self.state_initial_policy[str_board][action] * np.sqrt(self.n_state_visits[str_board] + EPS)
if u > best_q:
best_q = u
best_action = action
next_board, next_player = self.game.advance_game(board, 1, best_action)
next_board = self.game.from_perspective(next_board, next_player)
true_value = self.search(next_board) # This new board is a flipped old board so the agent learns to play for the white team
log.debug("Recursive search returned")
if (str_board, best_action) in self.q_vals:
# Then we need to update the q value to take the new down-tree value into account
self.q_vals[(str_board, best_action)] = (self.n_edge_visits[(str_board, best_action)] * self.q_vals[(str_board, best_action)] + true_value) / (self.n_edge_visits[(str_board, best_action)] + 1)
self.n_edge_visits[(str_board, best_action)] += 1
else:
# Then we have no q value to update so we initialize it to the down-tree value
self.q_vals[(str_board, best_action)] = true_value
self.n_edge_visits[(str_board, best_action)] = 1
self.n_state_visits[str_board] += 1
return -true_value # The call above this one is for the other player so the value is the negative of this player's value
|
{"/arena.py": ["/gameV2.py", "/tree_search.py"], "/tree_search.py": ["/gameV2.py", "/agent.py"], "/agent.py": ["/gameV2.py"], "/trainer.py": ["/gameV2.py", "/agent.py", "/tree_search.py", "/arena.py"], "/main.py": ["/gameV2.py", "/agent.py", "/trainer.py"]}
|
35,219
|
Veldrovive/alpha-zero-test
|
refs/heads/main
|
/agent.py
|
import logging
import os
import torch
from torch import optim
from tqdm import tqdm
import numpy as np
from time import time
from agent_net import Network
from gameV2 import Gomaku
log = logging.getLogger(__name__)
args = {
'lr': 0.001,
'dropout': 0.3,
'epochs': 10,
'batch_size': 64,
'cuda': torch.cuda.is_available(),
'num_channels': 2
}
class Agent:
def __init__(self, game: Gomaku):
self.net = Network(game, args)
self.board_y, self.board_x = game.get_board_size()
self.action_size = game.get_actions_size()
log.info(f"Using cuda: {args['cuda']}")
if args["cuda"]:
self.net.cuda()
def train(self, examples):
# Examples is an array of (board, policy, value)
optimizer = optim.Adam(self.net.parameters()) # TODO: Maybe try using an adabound or something?
for epoch in range(args["epochs"]): # TODO: Why is there no randomization here? There's only one shuffle in trainer.py
log.debug(f"Epoch: {epoch}")
self.net.train()
total_policy_loss = 0
total_value_loss = 0
batch_count = int(len(examples) / args["batch_size"])
counter = tqdm(range(batch_count), desc="Training")
for i in counter:
sample_ids = np.random.randint(len(examples), size=args["batch_size"]) # Grabs random indeces of examples
boards, policies, values = list(zip(*[examples[i] for i in sample_ids]))
boards = torch.FloatTensor(np.array(boards).astype(np.float64))
target_policies = torch.FloatTensor(np.array(policies))
target_values = torch.FloatTensor(np.array(values).astype(np.float64))
if args["cuda"]:
boards, target_policies, target_values = boards.contiguous().cuda(), target_policies.contiguous().cuda(), target_values.contiguous().cuda()
out_policies, out_values = self.net(boards)
loss_policy = self.policy_loss(target_policies, out_policies)
loss_value = self.value_loss(target_values, out_values)
total_loss = loss_policy + loss_value
total_policy_loss += loss_policy.item()
total_value_loss += loss_value.item()
counter.set_postfix(Loss_policy=total_policy_loss/(i+1), Loss_value=total_value_loss/(i+1))
optimizer.zero_grad()
total_loss.backward()
optimizer.step()
def policy_loss(self, targets, outputs):
return -torch.sum(targets * outputs) / targets.size()[0]
def value_loss(self, targets, outputs):
return torch.sum((targets - outputs.view(-1)) ** 2) / targets.size()[0]
def predict(self, board: np.ndarray):
start = time()
board = torch.FloatTensor(board.astype(np.float64)) # TODO: Make sure this doesn't modify game.board in place
if args["cuda"]:
board = board.contiguous().cuda()
board = board.view(1, self.board_x, self.board_y) # Reshape? TODO: Figure out why this is 1 deep instead of two splitting up the players like in the paper
self.net.eval()
with torch.no_grad(): # No need to compute gradients
policy, value = self.net(board)
inference_time = time() - start
return torch.exp(policy).data.cpu().numpy()[0], value.data.cpu().numpy()[0]
def save_checkpoint(self, folder="checkpoints", filename="checkpoint.pth.tar"):
filepath = os.path.join(folder, filename)
os.makedirs(folder, exist_ok=True)
torch.save({
'state_dict': self.net.state_dict()
}, filepath)
def load_checkpoint(self, folder="checkpoints", filename="checkpoint.pth.tar"):
filepath = os.path.join(folder, filename)
if not os.path.isfile(filepath):
raise Exception(f"No model found at {filepath}")
map_location = None if args["cuda"] else 'cpu' # Move to the correct device
checkpoint = torch.load(filepath, map_location=map_location)
self.net.load_state_dict(checkpoint["state_dict"])
|
{"/arena.py": ["/gameV2.py", "/tree_search.py"], "/tree_search.py": ["/gameV2.py", "/agent.py"], "/agent.py": ["/gameV2.py"], "/trainer.py": ["/gameV2.py", "/agent.py", "/tree_search.py", "/arena.py"], "/main.py": ["/gameV2.py", "/agent.py", "/trainer.py"]}
|
35,220
|
Veldrovive/alpha-zero-test
|
refs/heads/main
|
/trainer.py
|
import logging
import numpy as np
from collections import deque
from tqdm import tqdm
from pickle import Pickler, Unpickler
import os
from gameV2 import Gomaku
from agent import Agent
from tree_search import TreeSearch
from arena import Arena
log = logging.getLogger(__name__)
class Trainer:
def __init__(self, game: Gomaku, agent: Agent, args):
self.game = game
self.agent = agent
self.opponent = Agent(self.game) # Create an agent that we will play against
self.args = args
self.tree = TreeSearch(self.game, self.agent, self.args)
self.past_train_examples = []
self.skip_first_self_play = False
self.apply_symmetry = True
self.curr_player = None
def play_episode(self):
log.debug("Starting new episode")
train_examples = []
board = self.game.get_initial_board()
self.curr_player = 1 # While plays first? Doesn't really matter, we can just flip it later.
episode_step = 0
game_state = None
while game_state is None: # While the game state is ongoing
episode_step += 1
# Board is from the perspective of white. Flip it if the opponent is playing
perspective_board = self.game.from_perspective(board, self.curr_player)
temp = int(episode_step < self.args["tempThreshold"])
policy = self.tree.get_action_probs(perspective_board, temp=temp)
if self.apply_symmetry:
symmetries = self.game.get_symmetries(perspective_board, policy)
for sym_board, sym_policy in symmetries:
# These examples do not yet have a value
train_examples.append((sym_board, self.curr_player, sym_policy))
# TODO: Check if symmetries are correct
else:
train_examples.append((perspective_board, self.curr_player, policy))
# Choose a random action from the list of possible actions with a probability equal to that actions's prob
action = np.random.choice(len(policy), p=policy)
board, self.curr_player = self.game.advance_game(board, self.curr_player, action)
game_state = self.game.game_state(board)
final_board = board
final_policy = [0]*64
# At this point, the game is over and we know the true value for all actions
if game_state == 0:
# Then this game was a draw and all gradients would be 0. No need to train on these examples.
return []
training_data = []
for board, player, policy in train_examples:
# A 1 game state means the current player won and -1 means current player lost
value = game_state * (-1 if player == self.curr_player else 1)
# self.log_board(board*player, policy, value, player)
training_data.append((board, policy, value))
# self.log_board(final_board, final_policy, game_state*self.curr_player*-1, self.curr_player*-1)
# log.info("Game ended with %d winning", game_state)
# exit(0)
return training_data
def log_board(self, board, policy, value, player):
policy_board = np.reshape(policy, (8, 8))
board = self.game.to_string(board)
log.info(f"\nBoard:\n{board}\n--------\nPolicy:\n{policy_board}\n--------\nValue: {value}, Player: {player}\n \n")
def train(self):
log.info("Starting training")
for i in range(self.args["numIters"]):
log.info("Starting iteration: %d", i)
if not self.skip_first_self_play or i > 0:
training_data = deque([], maxlen=self.args["maxlenOfQueue"])
log.info("Starting to play episodes")
for _ in tqdm(range(self.args["numEps"]), desc="Self Play"):
# Recreate the search tree at the current board
self.tree = TreeSearch(self.game, self.agent, self.args)
training_data += self.play_episode()
self.past_train_examples.append(training_data)
log.info("%d training examples available:", len(self.past_train_examples))
if len(self.past_train_examples) > self.args["numItersForTrainExamplesHistory"]:
# We have too much data. Pop one
log.info("Too many past training examples, removing one.")
self.past_train_examples.pop(0)
log.info("Finished playing episodes. Saving history")
self.save_train_history(i)
train_data = []
for episode in self.past_train_examples:
train_data.extend(episode)
np.random.shuffle(train_data)
# Load the old network into the opponent for self play test
self.agent.save_checkpoint(folder=self.args["checkpoint"], filename="temp.pth.tar")
self.opponent.load_checkpoint(folder=self.args["checkpoint"], filename="temp.pth.tar")
opponent_tree_search = TreeSearch(self.game, self.opponent, self.args)
self.agent.train(train_data)
agent_tree_search = TreeSearch(self.game, self.agent, self.args)
log.info("Starting self play for evaluation")
arena = Arena(opponent_tree_search, agent_tree_search, self.game)
opponent_wins, agent_wins, draws = arena.play_round(self.args["arenaCompare"])
log.info("Opponent Wins: %d, Agent Wins: %d, Draws: %d", opponent_wins, agent_wins, draws)
if opponent_wins + agent_wins == 0 or agent_wins / (opponent_wins + agent_wins) < self.args["updateThreshold"]:
# Then we reject the model as there were all draws or our new model lost too many
log.info("New model failed to beat old model. Loading old checkpoint.")
self.agent.load_checkpoint(folder=self.args["checkpoint"], filename="temp.pth.tar")
else:
# Then our new agent is better than the last one so we should save it
# We use i+1 as the index as this is the next model
log.info("New model beat old model.")
self.agent.save_checkpoint(folder=self.args["checkpoint"], filename=self.get_checkpoint_filename(i+1))
self.agent.save_checkpoint(folder=self.args["checkpoint"], filename='best.pth.tar')
def get_checkpoint_filename(self, iteration):
return 'checkpoint_' + str(iteration) + '.pth.tar'
def save_train_history(self, iteration: int):
folder = self.args["checkpoint"]
os.makedirs(folder, exist_ok=True)
filename = os.path.join(folder, self.get_checkpoint_filename(iteration) + ".examples")
with open(filename, "wb+") as f:
Pickler(f).dump(self.past_train_examples)
def load_train_history(self, iteration: int):
folder = self.args["checkpoint"]
filename = os.path.join(folder, self.get_checkpoint_filename(iteration) + ".examples")
if not os.path.isfile(filename):
raise Exception("Could not find past examples: " + filename)
else:
with open(filename, "rb") as f:
self.past_train_examples = Unpickler(f).load()
self.skip_first_self_play = True
|
{"/arena.py": ["/gameV2.py", "/tree_search.py"], "/tree_search.py": ["/gameV2.py", "/agent.py"], "/agent.py": ["/gameV2.py"], "/trainer.py": ["/gameV2.py", "/agent.py", "/tree_search.py", "/arena.py"], "/main.py": ["/gameV2.py", "/agent.py", "/trainer.py"]}
|
35,221
|
Veldrovive/alpha-zero-test
|
refs/heads/main
|
/game.py
|
from typing import List
import numpy as np
class Gomaku:
content = {
-1: "b",
0: " ",
1: "w"
}
inverse_content = {
"b": -1,
" ": 0,
"1": 1
}
@staticmethod
def from_string_array(board: List[List[str]]):
size = len(board)
game = Gomaku(size)
for y in range(size):
for x in range(size):
val = Gomaku.inverse_content[board[y][x]]
game.board[y, x] = val
return game
@staticmethod
def from_string(board: str):
lines = board.split("\n")
game = Gomaku(len(lines))
for y in range(len(lines)):
for x in range(len(lines[0])):
val = Gomaku.inverse_content[lines[y][x]]
game.board[y, x] = val
return game
def __init__(self, size: int):
self.size = size
self.board = np.zeros((size, size), int)
def get_board_size(self):
return self.size, self.size
def get_actions_size(self):
# The index of action (y, x) is y*self.size + x
return self.size ** 2
def get_valid_moves(self):
# Any location that has a 0 is a valid move
zeros = np.where(self.board == 0)
valid_moves = zeros[0]*self.size + zeros[1]
all_moves = np.zeros(self.get_actions_size(), dtype=int)
all_moves[valid_moves] = 1
return all_moves
def game_over(self):
# Returns -1 is black won and 1 if white won. 0 if there was a draw. None if the game is ongoing.
# TODO: Check if there is a valid 5 in a row
if len(self.get_valid_moves()) == 0:
return 0
return None
def advance_game(self, player: int, action: int):
# Plays a piece onto the board
action_y, action_x = action // self.size, action % self.size
self.board[action_y, action_x] = player
return self.board, -player
def __str__(self):
# Converts the game board to a string
return '\n'.join([''.join([self.content[x] for x in line]) for line in self.board])
if __name__ == "__main__":
print("Running game unit tests")
board_size = 8
g1 = Gomaku(board_size)
size = g1.get_board_size()
actions = g1.get_actions_size()
valid_moves = g1.get_valid_moves()
print(f"Size: {size} - Number of actions: {actions}")
print(f"Valid actions: {valid_moves}")
print(f"Game board:\n{g1}")
assert size == (board_size, board_size)
assert actions == board_size*board_size
assert len(valid_moves) == actions
g1.advance_game(-1, 1*board_size+4)
print(f"Game board:\n{g1}")
valid_moves = g1.get_valid_moves()
print(f"Valid actions: {valid_moves}")
assert 1*board_size+4 not in valid_moves
print(f"Valid Actions: {np.where(valid_moves == 1)[0]}")
|
{"/arena.py": ["/gameV2.py", "/tree_search.py"], "/tree_search.py": ["/gameV2.py", "/agent.py"], "/agent.py": ["/gameV2.py"], "/trainer.py": ["/gameV2.py", "/agent.py", "/tree_search.py", "/arena.py"], "/main.py": ["/gameV2.py", "/agent.py", "/trainer.py"]}
|
35,222
|
Veldrovive/alpha-zero-test
|
refs/heads/main
|
/main.py
|
import logging
import torch
import numpy as np
import random
import coloredlogs
from gameV2 import Gomaku
from agent import Agent
from trainer import Trainer
log = logging.getLogger(__name__)
coloredlogs.install(level='INFO') # Change this to DEBUG to see more info or INFO to see less.
args = {
'numIters': 1000,
'numEps': 100, # Number of complete self-play games to simulate during a new iteration.
'tempThreshold': 15, #
'updateThreshold': 0.6, # During arena playoff, new neural net will be accepted if threshold or more of games are won.
'maxlenOfQueue': 200000, # Number of game examples to train the neural networks.
'numMCTSSims': 25, # Number of games moves for MCTS to simulate.
'arenaCompare': 40, # Number of games to play during arena play to determine if new net will be accepted.
'cpuct': 1,
'checkpoint': './temp/',
'load_model': False,
'load_file': 'best.pth.tar',
'numItersForTrainExamplesHistory': 20,
}
seed = 1
if seed is not None:
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
def main():
game = Gomaku(8)
agent = Agent(game)
if args["load_model"]:
log.info("Loading old model: %s/%s", args["checkpoint"], args["load_file"])
agent.load_checkpoint(folder=args["checkpoint"], filename=args["load_file"])
else:
log.info("Creating new model")
trainer = Trainer(game, agent, args)
log.info("Starting training")
trainer.train()
if __name__ == "__main__":
main()
|
{"/arena.py": ["/gameV2.py", "/tree_search.py"], "/tree_search.py": ["/gameV2.py", "/agent.py"], "/agent.py": ["/gameV2.py"], "/trainer.py": ["/gameV2.py", "/agent.py", "/tree_search.py", "/arena.py"], "/main.py": ["/gameV2.py", "/agent.py", "/trainer.py"]}
|
35,223
|
Veldrovive/alpha-zero-test
|
refs/heads/main
|
/gameV2.py
|
import logging
from typing import List, Tuple, Optional
import numpy as np
log = logging.getLogger(__name__)
class Gomaku:
content = {
-1: "b",
0: "-",
1: "w"
}
inverse_content = {
"b": -1,
"-": 0,
"1": 1
}
def from_string_array(self, board_seed: List[List[str]]):
# This is the format the game will be delivered in in the competition
board = np.zeros((self.size, self.size))
for y in range(self.size):
for x in range(self.size):
val = Gomaku.inverse_content[board_seed[y][x]]
board[y, x] = val
return board
def from_string(self, board_seed: str):
# This is the format that game.to_string returns
board = np.zeros((self.size, self.size))
lines = board_seed.split("\n")
for y in range(len(lines)):
for x in range(len(lines[0])):
val = Gomaku.inverse_content[lines[y][x]]
board[y, x] = val
return board
def get_initial_board(self):
return np.zeros((self.size, self.size))
def get_symmetries(self, board: np.ndarray, policy: np.ndarray):
"""
This is a bit confusing. Each board state has 7 other states that represent the exact same value for the
current player. We can see that any rotation of 90 degrees is a new state that has the exact same value as the
old one. We can also see if we apply either a vertical or horizontal mirror to this new state we end up with
another novel state. Combining any more rotations and mirrors just ends up at an already seen state.
If we neglect these symmetries, we forfeit a simple data augmentation that multiplies our data by 8. So it's
not really an option to not do this. The numpy is confusing, though.
board: The (size, size) shape numpy array representing the current board state
policy: A size*size length numpy array representing the probability of making any given move
"""
augmented_boards = []
# We reshape the policy into a board so that when we rotate or reflect it the policy changes correctly
policy_board = np.reshape(policy, (self.size, self.size))
for i in [0, 1, 2, 3]: # For 0, 90, 180, and 270 degrees of rotation
rot_board = np.rot90(board, i)
rot_policy_board = np.rot90(policy_board, i)
flipped_board = np.fliplr(rot_board)
flipped_policy_board = np.fliplr(rot_policy_board)
augmented_boards.extend([(rot_board, rot_policy_board.ravel()), (flipped_board, flipped_policy_board.ravel())])
return augmented_boards
def __init__(self, size: int):
self.size = size
def get_board_size(self) -> Tuple[int, int]:
return self.size, self.size
def get_actions_size(self) -> int:
# The index of action (y, x) is y*self.size + x
return self.size ** 2
def get_valid_moves(self, board: np.ndarray) -> np.ndarray:
# Any location that has a 0 is a valid move
zeros = np.where(board == 0)
valid_moves = zeros[0]*self.size + zeros[1]
all_moves = np.zeros(self.get_actions_size(), dtype=int)
all_moves[valid_moves] = 1
return all_moves
def game_state(self, board: np.ndarray) -> Optional:
# Returns -1 is black won and 1 if white won. 0 if there was a draw. None if the game is ongoing.
# TODO: Check if there is a valid 5 in a row
def detect_five(y_start, x_start, d_y, d_x):
seq_length = None
seq_player = None
y_max = self.size - 1
x_max = self.size - 1
while 0 <= y_start <= y_max and 0 <= x_start <= x_max:
cur_player = board[y_start, x_start]
if cur_player == seq_player:
seq_length += 1
else:
if seq_length == 5:
return seq_player
seq_length = None
seq_player = None
if cur_player != 0:
seq_length = 1
seq_player = cur_player
y_start += d_y
x_start += d_x
return None
# Check for a winner
winner = None
x_start = 0
for y_start in range(len(board)):
# Check directions (0, 1) and (1, 1)
winner = winner or detect_five(y_start, x_start, 0, 1)
winner = winner or detect_five(y_start, x_start, 1, 1)
x_start = len(board[0]) - 1
for y_start in range(len(board)):
# Check direction (1, -1)
winner = winner or detect_five(y_start, x_start, 1, -1)
y_start = 0
for x_start in range(len(board[0])):
# Check direction (1, 0)
winner = winner or detect_five(y_start, x_start, 1, 0)
if x_start > 1:
# Check the rows that were not on the y pass
winner = winner or detect_five(y_start, x_start, 1, 1)
if x_start < len(board[0]) - 1:
# Chck the rows that were not on the second y pass
winner = winner or detect_five(y_start, x_start, 1, -1)
if winner is not None:
return winner
if np.max(self.get_valid_moves(board)) < 1:
return 0
return None
def advance_game(self, board: np.ndarray, player: int, action: int) -> Tuple[np.ndarray, int]:
# Plays a piece onto the board
action_y, action_x = action // self.size, action % self.size
new_board = board.copy()
new_board[action_y, action_x] = player
return new_board, -player
def from_perspective(self, board: np.ndarray, player: int) -> np.ndarray:
# If player is -1 then the board will be flipped such that the player -1 has the white pieces
return player*board
def to_string(self, board: np.ndarray) -> str:
# Converts the game board to a string
return '\n'.join([''.join([self.content[x] for x in line]) for line in board])
|
{"/arena.py": ["/gameV2.py", "/tree_search.py"], "/tree_search.py": ["/gameV2.py", "/agent.py"], "/agent.py": ["/gameV2.py"], "/trainer.py": ["/gameV2.py", "/agent.py", "/tree_search.py", "/arena.py"], "/main.py": ["/gameV2.py", "/agent.py", "/trainer.py"]}
|
35,228
|
yusing/RSS-Scrapper
|
refs/heads/master
|
/scrap.py
|
import asyncio
import concurrent.futures
import threading
import warnings
from asyncio.runners import run
from datetime import datetime
from textwrap import wrap
from time import sleep
from urllib.parse import urlparse
import mysql.connector
import newspaper
import requests
from bs4 import BeautifulSoup
from bs4.element import ResultSet
from dateutil.parser import parse
from mysql.connector.cursor import MySQLCursor
from newspaper import Config
from newspaper.article import Article
warnings.filterwarnings("ignore") # suppress all warnings
log_file = open('log.txt', 'w')
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"
}
feeds_url = [
'https://trends.google.com/trends/trendingsearches/daily/rss?geo=HK', # Google Trends HK
'https://www.reddit.com/.rss', # Reddit main page
# add any rss feed below (e.g. https://www.youtube.com/feeds/videos.xml?channel_id=[CHANNEL_ID]
]
parse_done : int
articles_count : int
feeds_done : int
rows_inserted : int
last_url : str
show_rss_dl_status : bool
show_scrapping_status : bool
show_timer : bool
feeds : list[tuple[str,str]] = []
config_en = Config()
config_en.memoize_articles = False
config_en.browser_user_agent = headers["User-Agent"]
config_en.headers = headers
config_en.fetch_images = False
def log(text):
log_file.write(str(text))
log_file.write('\n')
def background(f):
def wrapped(*args, **kwargs):
try:
return asyncio.get_event_loop().run_in_executor(None, f, *args, **kwargs)
except:
return asyncio.new_event_loop().run_in_executor(None, f, *args, **kwargs)
return wrapped
@background
def insert_db(entry: tuple[str]):
global last_url
global rows_inserted
try:
db = mysql.connector.connect(
host='localhost',
user='root',
database='news'
)
last_url = entry[5]
cursor : MySQLCursor= db.cursor()
cursor.execute('''
INSERT IGNORE INTO news (source, date, title, summary, text, url)
VALUES (%s, %s, %s, %s, %s, %s)
''', entry)
db.commit()
db.close()
if cursor.rowcount != 0:
rows_inserted += 1
except:
pass
@background
def setShowRSSDownloadStatus(show : bool):
global show_rss_dl_status
show_rss_dl_status = show
while show_rss_dl_status:
print('\033[H\033[J', end='')
print(f'{len(feeds)}/{len(feeds_url)} ({len(feeds)/len(feeds_url)*100:.2f}%) Downloading RSS')
sleep(.1)
@background
def setShowScrappingStatus(show : bool):
global show_scrapping_status
global last_url
global rows_inserted
show_scrapping_status = show
while articles_count == 0:
sleep(.5)
while show_scrapping_status:
print('\033[H\033[J', end='')
print(f'Scrapping articles {parse_done}/{articles_count} ({parse_done/articles_count*100:.2f}%) ({rows_inserted} rows inserted)', end=' ')
print(f'URL: "{last_url[:80]+"... (truncated)" if len(last_url)>80 else last_url}"')
sleep(.1)
@background
def setShowTimer(show: bool, time: int = 0):
global show_timer
show_timer = show
while time > 0:
print('\033[H\033[J', end='')
print(f'Next scrapping is starting in {time//3600:02d}:{(time%3600)//60:02d}:{time%60:02d}')
time -= 1
sleep(1)
@background
def downloadRSS(url: str):
global headers
r = requests.get(url, headers=headers)
if r.status_code == requests.codes.ok:
feeds.append((r.content, url))
else:
log(f'failed to download RSS from {url}')
feeds.append((None, None))
@background
def parseArticle(articles: ResultSet, host: str, src_ele: str, summary_ele: str, date_ele: str, url_ele: str):
global parse_done
global config_en
global articles_count
articles_count += len(articles)
for a in articles:
src = a.find(src_ele)
summary = a.find(summary_ele)
date = a.find(date_ele)
if src is None:
src = host
else:
src = src.text
if summary is None:
summary = a.find('description') # fallback
if summary is not None:
summary = summary.text
url = a.find(url_ele)
if url is not None:
url = url.text.strip()
else:
url = ''
if url != '':
article = Article(url, config=config_en)
if date is not None:
try:
date = parse(date.text)
except:
date = None
try:
article.download()
article.parse()
except Exception as ex:
log(f'{ex}, url is "{url}"')
finally:
if article.publish_date is datetime and date is None:
date = article.publish_date.strftime('%Y-%m-%d %H:%M:%S')
insert_db((src, date, article.title, summary, article.text, article.url))
parse_done += 1
@background
def parseRedditComments(comments: ResultSet, subreddit: str, link: str, title: str, summary: str, date: str):
global parse_done
global articles_count
text = ''
articles_count += 1
for comment in comments:
if comment.author is not None:
try:
user = comment.author.find('name').text
date = parse(comment.updated.text).strftime('%Y-%m-%d %H:%M')
content = BeautifulSoup(comment.content.text).p
if content is not None:
content = content.text
formatted = "\n ".join(wrap(content, 70))
text += f'{user} ({date}):\n {formatted}\n'
except Exception as ex:
log(ex)
insert_db((subreddit, date, title, summary, text, link))
parse_done += 1
@background
def parseYouTubeRSS(a):
global articles_count
global parse_done
articles_count += 1
title = a.find('title').text
link = a.find('link', {'rel': 'alternate'})['href']
author = f'YouTube/{a.author.find("name").text}'
date = parse(a.find('published').text).strftime('%Y-%m-%d %H:%M')
summary = a.find('media:group').find('media:description').text
# source, date, title, summary, text, url
insert_db((author, date, title, summary, None, link))
parse_done += 1
@background
def scrapRSS(rss:str, url: str):
soup = BeautifulSoup(rss, features='xml')
if 'reddit.com' in url:
for a in soup.findAll('entry'):
url = a.find('link')['href']+'/.rss'
r = requests.get(url, headers=headers)
if r.status_code != requests.codes.ok:
log(f'failed to download reddit rss {url}')
continue
bs = BeautifulSoup(r.content, features='xml')
subreddit = bs.find('category')['label']
link = bs.find('link', {'rel': 'alternate'})['href']
summary = bs.find('subtitle')
if summary is not None:
summary = summary.text
title = bs.find('title').text
date = parse(bs.find('updated').text).strftime('%Y-%m-%d %H:%M')
comments = bs.find_all('entry')
parseRedditComments(comments, subreddit, link, title, summary, date)
elif 'youtube.com' in url:
for a in soup.findAll('entry'):
parseYouTubeRSS(a)
else:
if 'trends.google.com' in url:
root = 'ht:news_item'
url_ele = 'ht:news_item_url'
src_ele = 'ht:news_item_source'
summary_ele = 'ht:news_item_snippet'
date_ele = 'pubDate'
else:
root = 'item'
url_ele = 'link'
src_ele = 'source'
summary_ele = 'summary'
date_ele = 'pubDate'
try:
host = urlparse(url).netloc
except Exception as ex:
log(f'Error parsing url "{ex}"')
return
if soup.find(root) is not None:
articles = soup.findAll(root)
else:
articles = soup.findAll('entry')
if articles is not None:
try:
parseArticle(articles, host, src_ele, summary_ele, date_ele, url_ele)
except Exception as ex:
log(ex)
def fetch_news():
db = mysql.connector.connect(
host='localhost',
user='root',
database='news'
)
db.cursor().execute('''
CREATE TABLE IF NOT EXISTS news(
url VARCHAR(512) UNIQUE,
source VARCHAR(255) NOT NULL,
date DATETIME,
title VARCHAR(255) NOT NULL UNIQUE,
summary VARCHAR(1024) NOT NULL,
text TEXT NOT NULL
)''')
print('\033[?25l') # hide cursor
global feeds
global feeds_done
global parse_done
global articles_count
global last_url
global rows_inserted
def downloadAllFeeds():
feeds.clear()
for feed in feeds_url:
downloadRSS(feed)
while (len(feeds) < len(feeds_url)):
sleep(1)
def parseAllArticles():
for feed, url in feeds:
if feed is not None:
scrapRSS(feed, url)
while (parse_done < articles_count) or articles_count == 0:
sleep(1)
while True:
parse_done = 0
articles_count = 0
feeds_done = 0
rows_inserted = 0
last_url = ''
setShowRSSDownloadStatus(True)
downloadAllFeeds()
setShowRSSDownloadStatus(False)
setShowScrappingStatus(True)
parseAllArticles()
setShowScrappingStatus(False)
setShowTimer(True, 1800)
sleep(1800)
if __name__ == "__main__":
fetch_news()
|
{"/query.py": ["/scrap.py"]}
|
35,229
|
yusing/RSS-Scrapper
|
refs/heads/master
|
/query.py
|
import mysql.connector
import sys
import webbrowser
from scrap import fetch_news
from hanziconv import HanziConv
if len(sys.argv) == 1:
command = 'help'
else:
command = sys.argv[1]
args = sys.argv[2:]
news_db = mysql.connector.connect(
host='localhost',
user='root',
database='news'
)
cursor = news_db.cursor()
extra = ''
cursor.execute("set session sql_mode=''")
text = 'text'
if command == 'search' or command == 's':
if len(args) == 0:
print('expect a keyword to search')
exit(1)
if 'within' in args: # within days
try:
within = int(args[args.index('within')+1])
except:
print("Require integer after 'within'")
exit(1)
extra += f' AND (DATEDIFF(NOW(), date)) <= {within}'
if 'from' in args: # search by source
try:
source = args[args.index('from')+1]
if 'exactly' in args:
cond = f'="{source}"'
else:
cond = f'LIKE "%{source}%"'
except:
print("Require news source after 'from'")
exit(1)
extra += f' AND source {cond}'
if 'sort' in args:
try:
sort_col = args[args.index('sort')+1]
if 'desc' in args:
sort_order = 'desc'
else:
sort_order = 'asc'
except:
print("Require column name and order after 'sort'")
exit(1)
extra += f' ORDER BY {sort_col} {sort_order}'
if 'chs' in args:
args[0] = HanziConv.toSimplified(args[0]) # convert tp CHS
if 'cs' in args:
title = 'title'
pattern = args[0]
else:
title = 'LOWER(title)'
pattern = args[0].lower()
if 'exactly' not in args:
pattern = f'%{pattern}%'
if 'summary' in args:
text = 'summary'
command = f'SELECT source, date, title, url, {text} FROM news WHERE {title} LIKE "{pattern}"' + extra
print(f'Execute "{command}"')
cursor.execute(command)
results = cursor.fetchall()
if len(results) == 0:
print('Nothing found')
exit(0)
else:
i = 0
for _ in results:
if _[1] is None:
print(f'{i}. {_[0]}: {_[2]}')
else:
print(f'{i}. {_[0]}: {_[2]} ({_[1]})')
i += 1
if len(results) > 1:
print(f'{i}. Cancel')
choice = int(input('Which: '))
while (choice < 0 or choice > len(results)):
print('out of range')
choice = int(input('Which: '))
else:
choice = 0
if choice == len(results): # cancel
exit(0)
result = results[choice]
print(f'URL: {result[3]}')
if len(result[4]) == 0:
ask = input('No content is stored. Open it in web browser? (y/n): ')
if ask.lower() == 'y':
webbrowser.open(result[3])
else:
content = result[4]
if type(content) == bytes:
print(content.decode('UTF-8'))
else:
print(content)
elif command == 'count' or command == 'c':
col_name = '*'
if 'by' in args:
try:
col_name = args[args.index('by')+1]
except:
print('expect column name after count by')
exit(1)
command = f'SELECT {col_name}, COUNT(*) FROM news'
extra += f' GROUP BY {col_name}'
elif 'source' in args:
col_name = 'source'
try:
source = args[args.index('source')+1]
except:
print('expect column name after count source')
exit(1)
command = f'SELECT source, COUNT(*) FROM news where source LIKE "%{source}%"'
else:
command = 'SELECT COUNT(*) FROM news'
if 'within' in args: # within days
try:
within = int(args[args.index('within')+1])
except:
print("Require integer after 'within'")
exit(1)
extra += f' WHERE (DATEDIFF(NOW(), date)) <= {within}'
if 'sort' in args:
if 'desc' in args:
sort_order = 'desc'
else:
sort_order = 'asc'
extra += f' ORDER BY {col_name} {sort_order}'
command += extra
print(f'Execute "{command}"')
cursor.execute(command)
results = cursor.fetchall()
for _ in results:
if len(_) > 1:
count = _[1]
col = _[0]
else:
count = _[0]
col = '*'
print(f'{count:6} articles from {col_name} {col}')
elif command == 'list' or command == 'l':
if len(args) == 0:
print("Require news source after 'list'")
exit(1)
command = f'SELECT source, title FROM news WHERE source LIKE "%{args[0]}%"'
print(f'Execute "{command}"')
cursor.execute(command)
results = cursor.fetchall()
for result in results:
print(result[1])
elif command == 'fetch' or command == 'f':
fetch_news()
elif command == 'help' or command == 'h':
print('''
news-query.py command [arguments] [options]
commands:
- c[ount] count news
- s[earch] search for news
- l[ist] list all news of a specific source
- f[etch] fetch news
- h[elp] print this help message
count:
[options]:
- within N_DAYS count news within N days (override 'by' option)
- by COLUMN count news by column
- source SOURCE count news of specific source
- sort [ORDER] sorting order [asc | desc] (default: asc)
search:
arguments:
- KEYWORD keyword to search
[options]:
- within N_DAYS search news within N days
- from SOURCE search news from specific source
- sort COLUMN [ORDER] sorting order [asc | desc] (default: asc)
- chs search in Simplified Chinese
- cs case-sensitive search
- exactly search with no wildcard
- summary display summary instead of content
list:
argument:
- SOURCE_NAME name of the news source
fetch: No arguments
''')
else:
print(f'Unknown command "{command}"')
exit(1)
|
{"/query.py": ["/scrap.py"]}
|
35,257
|
aimerou/rfid-restaurant-app
|
refs/heads/main
|
/models.py
|
from pymongo import MongoClient
class Carte:
"""
Modèle Carte. Pour effectuer les différentes transactions avec la base de données.
"""
client = MongoClient("mongodb+srv://ali:ali221@cluster0.xie2q.mongodb.net/restaudb?retryWrites=true&w=majority")
db = client.restaudb
collection = db.carte
def __init__(self, prenom, nom, solde, uid):
self.prenom = prenom
self.nom = nom
self.solde = solde
self.uid = uid
def toJSON(self):
return {
"prenom": self.prenom,
"nom": self.nom,
"solde": self.solde,
"uid": self.uid
}
@classmethod
def get_student_by_uid(cls, uid):
return cls.collection.find_one({
"uid": uid
})
@classmethod
def update_solde(cls, uid, solde):
return cls.collection.find_one_and_update(
{'uid': uid},
{'$set': {"solde": solde}},
)
@classmethod
def update_etudiant(cls, uid, prenom, nom, solde):
return cls.collection.find_one_and_update(
{'uid': uid},
{'$set': {"solde": solde, "prenom": prenom, "nom": nom}},
)
@classmethod
def register_student_to_bd(cls, student):
return cls.collection.insert_one(student)
@classmethod
def liste_etudiant(cls):
return cls.collection.find({})
|
{"/register_student.py": ["/get_uid.py", "/models.py"], "/solde_management.py": ["/get_uid.py", "/leds_management.py", "/models.py"]}
|
35,258
|
aimerou/rfid-restaurant-app
|
refs/heads/main
|
/get_uid.py
|
import RPi.GPIO as GPIO #Importe la bibliothèque pour contrôler les GPIOs
from pirc522 import RFID
import time
GPIO.setmode(GPIO.BOARD) #Définit le mode de numérotation (Board)
GPIO.setwarnings(False) #On désactive les messages d'alerte
rc522 = RFID() #On instancie la lib
def get_uid():
"""
Fonction pour lire le code RFID de la carte de l'étudiant.
"""
print('En attente d\'un badge (pour quitter, Ctrl + c): ') #On affiche un message demandant à l'utilisateur de passer son badge
rc522.wait_for_tag() #On attnd qu'une puce RFID passe à portée
(error, tag_type) = rc522.request() #Quand une puce a été lue, on récupère ses infos
if not error : #Si on a pas d'erreur
(error, uid) = rc522.anticoll() #On nettoie les possibles collisions, ça arrive si plusieurs cartes passent en même temps
if not error : #Si on a réussi à nettoyer
time.sleep(1) #On attend 1 seconde pour ne pas lire le tag des centaines de fois en quelques milli-secondes
return "".join(map(str, uid))
return None
#print(get_uid())
|
{"/register_student.py": ["/get_uid.py", "/models.py"], "/solde_management.py": ["/get_uid.py", "/leds_management.py", "/models.py"]}
|
35,259
|
aimerou/rfid-restaurant-app
|
refs/heads/main
|
/leds_management.py
|
#!/usr/bin/env python3.5
#-- coding: utf-8 --
import RPi.GPIO as GPIO #Importe la bibliothèque pour contrôler les GPIOs
from pirc522 import RFID
import time
GPIO.setmode(GPIO.BOARD) #Définit le mode de numérotation (Board)
GPIO.setwarnings(False) #On désactive les messages d'alerte
LED_RED = 3 #Définit le numéro du port GPIO qui alimente la led rouge
LED_GREEN = 5 #Définit le numéro du port GPIO qui alimente la led verte
RFID_UID = [179, 165, 146, 96, 228] #Définit l'UID du badge RFID
#Définit la fonction permettant d'allumer une led
def turn_led_on (led) :
GPIO.setup(led, GPIO.OUT) #Active le contrôle du GPIO
GPIO.output(led, GPIO.HIGH) #Allume la led
#Définit la fonction permettant d'éteindre une led
def turn_led_off (led) :
GPIO.setup(led, GPIO.OUT) #Active le contrôle du GPIO
GPIO.output(led, GPIO.LOW) #Eteind la led
#Définit la fonction permettant d'allumer la rouge et éteindre la verte
def turn_red_on () :
turn_led_off(LED_GREEN) #Eteind la led verte
turn_led_on(LED_RED) #Allume la led rouge
time.sleep(1)
turn_both_off()
#Définit la fonction permettant d'allumer la verte et éteindre la rouge
def turn_green_on () :
turn_led_off(LED_RED) #Eteind la led rouge
turn_led_on(LED_GREEN) #Allume la led verte
time.sleep(2)
turn_both_off()
# Eteint les deux leds au démarrage du programme
def turn_both_off():
turn_led_off(LED_RED)
turn_led_off(LED_GREEN)
|
{"/register_student.py": ["/get_uid.py", "/models.py"], "/solde_management.py": ["/get_uid.py", "/leds_management.py", "/models.py"]}
|
35,260
|
aimerou/rfid-restaurant-app
|
refs/heads/main
|
/register_student.py
|
import time
from get_uid import get_uid
from models import Carte
from afficher_etudiant import afficher_etudiant, etudiant_existe, afficher_liste_etudiants
def register_student():
"""
Fonction pour enregistrer un nouvel étudiant au niveau de la base de données.
"""
i = 0
while i < 2:
afficher_liste_etudiants()
print("*******ENREGISTREMENT D'UN NOUVEL ETUDIANT *********\n\n")
prenom = input("Entrer le prénom de l'étudiant: ")
nom = input("Entrer le nom de l'étudiant: ")
solde = int(input("Entrer le solde de l'étudiant : "))
id_carte = get_uid()
if etudiant_existe(id_carte):
Carte.update_etudiant(id_carte, prenom, nom, solde)
print("\nMise à jour des informations ...")
print("\n********Enregistrment terminé!*********")
else:
Carte.register_student_to_bd({
"prenom": prenom,
"nom": nom,
"solde": solde,
"uid": id_carte
})
print("\n********Enregistrment terminé!*********")
afficher_etudiant(
{
"prenom": prenom,
"nom": nom,
"solde": solde,
"uid": id_carte
}
)
time.sleep(2)
register_student()
|
{"/register_student.py": ["/get_uid.py", "/models.py"], "/solde_management.py": ["/get_uid.py", "/leds_management.py", "/models.py"]}
|
35,261
|
aimerou/rfid-restaurant-app
|
refs/heads/main
|
/solde_management.py
|
from get_uid import get_uid
from leds_management import *
from models import Carte
from afficher_etudiant import afficher_etudiant
SOLDE_PETIT_DEJ = 50
SOLDE_REPAS = 100
def get_student_by_uid(uid):
"""
C'est une fonction pour avoir l'étudiant correspondant à l'uid de la carte
"""
for student in TEST_STUDENTS:
if student["id_carte"] == uid:
return student
return None
def charger_carte():
"""
C'est une fonction qui nous permet de recharger la carte de létudiant
"""
while True:
print("\n********* RECHARGEMENT DE CARTE **********\n")
uid = get_uid()
etudiant = Carte.get_student_by_uid(uid)
afficher_etudiant(etudiant)
if etudiant != None:
montant = int(input("Entrer le solde à ajouter: "))
etudiant['solde'] += montant
Carte.update_solde(uid, etudiant['solde'])
turn_green_on()
afficher_etudiant(etudiant)
continue
turn_red_on()
print("uid inexistant!")
def debiter_carte():
"""
C'est une fonction qui nous permet de débiter la carte de létudiant
"""
while True:
print("\n********* DEBITEMENT DE CARTE **********\n")
uid = get_uid()
etudiant = Carte.get_student_by_uid(uid)
if etudiant != None:
print("Etudiant Identifié!")
afficher_etudiant(etudiant)
print("Entrer le type de repas !")
print("1. Petit-déjeuner")
print("2. Repas")
type_repas = int(input("Entrer 1 ou 2 : "))
if type_repas !=1 and type_repas!=2:
turn_red_on()
print("Choix non pris en charge!")
continue
elif type_repas == 1 and etudiant["solde"] >=SOLDE_PETIT_DEJ :
etudiant['solde'] -= SOLDE_PETIT_DEJ
Carte.update_solde(uid, etudiant['solde'])
elif type_repas == 2 and etudiant["solde"] >=SOLDE_REPAS:
etudiant['solde'] -= SOLDE_REPAS
Carte.update_solde(uid, etudiant['solde'])
else:
turn_red_on()
print("*****Solde insuffisant!*****")
turn_green_on()
afficher_etudiant(etudiant)
continue
turn_red_on()
print("****Etudiant inexistant!*****")
|
{"/register_student.py": ["/get_uid.py", "/models.py"], "/solde_management.py": ["/get_uid.py", "/leds_management.py", "/models.py"]}
|
35,283
|
jGaboardi/watermark
|
refs/heads/master
|
/watermark/watermark.py
|
# -*- coding: utf-8 -*-
"""
Function to print date/time stamps and
various system information.
Authors: Sebastian Raschka <sebastianraschka.com>, Tymoteusz Wołodźko
License: BSD 3 clause
"""
from __future__ import absolute_import
import datetime
import importlib
import os
import platform
import subprocess
import time
import types
from multiprocessing import cpu_count
from socket import gethostname
import platform
try:
from py3nvml import py3nvml
except ImportError:
py3nvml = None
try:
import importlib.metadata as importlib_metadata
except ImportError:
# Running on pre-3.8 Python; use importlib-metadata package
import importlib_metadata
import IPython
from .version import __version__
def watermark(
author=None,
email=None,
github_username=None,
website=None,
current_date=False,
datename=False,
current_time=False,
iso8601=False,
timezone=False,
updated=False,
custom_time=None,
python=False,
packages=None,
conda=False,
hostname=False,
machine=False,
githash=False,
gitrepo=False,
gitbranch=False,
watermark=False,
iversions=False,
gpu=False,
watermark_self=None,
globals_=None
):
'''Function to print date/time stamps and various system information.
Parameters:
===========
author :
prints author name
github_username :
prints author github username
email :
prints author email
website :
prints author or project website
current_date :
prints current date as YYYY-mm-dd
datename :
prints date with abbrv. day and month names
current_time :
prints current time as HH-MM-SS
iso8601 :
prints the combined date and time including the time zone
in the ISO 8601 standard with UTC offset
timezone :
appends the local time zone
updated :
appends a string "Last updated: "
custom_time :
prints a valid strftime() string
python :
prints Python and IPython version (if running from Jupyter)
packages :
prints versions of specified Python modules and packages
conda :
prints name of current conda environment
hostname :
prints the host name
machine :
prints system and machine info
githash :
prints current Git commit hash
gitrepo :
prints current Git remote address
gitbranch :
prints current Git branch
watermark :
prints the current version of watermark
iversions :
prints the name/version of all imported modules
gpu :
prints GPU information (currently limited to NVIDIA GPUs), if available
watermark_self :
instance of the watermark magics class, which is required
for iversions.
'''
output = []
args = locals()
watermark_self = args['watermark_self']
del args['watermark_self']
if not any(args.values()) or args['iso8601']:
iso_dt = _get_datetime()
if not any(args.values()):
args['updated'] = True
output.append({"Last updated": iso_dt})
output.append(_get_pyversions())
output.append(_get_sysinfo())
else:
if args['author']:
output.append({"Author": args['author'].strip("'\"")})
if args['github_username']:
output.append({"Github username": \
args['github_username'].strip("'\"")})
if args['email']:
output.append({"Email": args['email'].strip("'\"")})
if args['website']:
output.append({"Website": args['website'].strip("'\"")})
if args['updated']:
value = ""
if args['custom_time']:
value = time.strftime(args['custom_time'])
elif args['iso8601']:
value = iso_dt
else:
values = []
if args['current_date']:
values.append(time.strftime("%Y-%m-%d"))
elif args['datename']:
values.append(time.strftime("%a %b %d %Y"))
if args['current_time']:
time_str = time.strftime("%H:%M:%S")
if args['timezone']:
time_str += time.strftime("%Z")
values.append(time_str)
value = " ".join(values)
output.append({"Last updated": value})
if args['python']:
output.append(_get_pyversions())
if args['packages']:
output.append(_get_packages(args['packages']))
if args['conda']:
output.append(_get_conda_env())
if args['machine']:
output.append(_get_sysinfo())
if args['hostname']:
output.append({"Hostname": gethostname()})
if args['githash']:
output.append(_get_commit_hash(bool(args['machine'])))
if args['gitrepo']:
output.append(_get_git_remote_origin(bool(args['machine'])))
if args['gitbranch']:
output.append(_get_git_branch(bool(args['machine'])))
if args['iversions']:
if watermark_self:
ns = watermark_self.shell.user_ns
elif globals_:
ns = globals_
else:
raise RuntimeError(
"Either `watermark_self` or `globals_` must be provided "
"to show imported package versions."
)
output.append(_get_all_import_versions(ns))
if args['gpu']:
output.append(_get_gpu_info())
if args['watermark']:
output.append({"Watermark": __version__})
return _generate_formatted_text(output)
def _generate_formatted_text(list_of_dicts):
result = []
for section in list_of_dicts:
if section:
text = ""
longest = max(len(key) for key in section)
for key, value in section.items():
text += f"{key.ljust(longest)}: {value}\n"
result.append(text)
return "\n".join(result)
def _get_datetime(pattern="%Y-%m-%dT%H:%M:%S"):
try:
dt = datetime.datetime.now(tz=datetime.timezone.utc)
iso_dt = dt.astimezone().isoformat()
except AttributeError: # timezone only supported by Py >=3.2:
iso_dt = time.strftime(pattern)
return iso_dt
def _get_packages(pkgs):
packages = pkgs.split(",")
return {package: _get_package_version(package)
for package in packages}
def _get_package_version(pkg_name):
"""Return the version of a given package"""
if pkg_name == "scikit-learn":
pkg_name = "sklearn"
try:
imported = importlib.import_module(pkg_name)
except ImportError:
version = "not installed"
else:
try:
version = importlib_metadata.version(pkg_name)
except importlib_metadata.PackageNotFoundError:
try:
version = imported.__version__
except AttributeError:
try:
version = imported.version
except AttributeError:
try:
version = imported.version_info
except AttributeError:
version = "unknown"
return version
def _get_pyversions():
return {
"Python implementation": platform.python_implementation(),
"Python version": platform.python_version(),
"IPython version": IPython.__version__,
}
def _get_sysinfo():
return {
"Compiler": platform.python_compiler(),
"OS": platform.system(),
"Release": platform.release(),
"Machine": platform.machine(),
"Processor": platform.processor(),
"CPU cores": cpu_count(),
"Architecture": platform.architecture()[0],
}
def _get_commit_hash(machine):
process = subprocess.Popen(
["git", "rev-parse", "HEAD"], shell=False, stdout=subprocess.PIPE
)
git_head_hash = process.communicate()[0].strip()
return {"Git hash": git_head_hash.decode("utf-8")}
def _get_git_remote_origin(machine):
process = subprocess.Popen(
["git", "config", "--get", "remote.origin.url"],
shell=False,
stdout=subprocess.PIPE,
)
git_remote_origin = process.communicate()[0].strip()
return {"Git repo": git_remote_origin.decode("utf-8")}
def _get_git_branch(machine):
process = subprocess.Popen(
["git", "rev-parse", "--abbrev-ref", "HEAD"],
shell=False,
stdout=subprocess.PIPE,
)
git_branch = process.communicate()[0].strip()
return {"Git branch": git_branch.decode("utf-8")}
def _get_all_import_versions(vars):
to_print = {}
imported_pkgs = {
val.__name__.split(".")[0]
for val in list(vars.values())
if isinstance(val, types.ModuleType)
}
imported_pkgs.discard("builtins")
for pkg_name in imported_pkgs:
pkg_version = _get_package_version(pkg_name)
if pkg_version not in ("not installed", "unknown"):
to_print[pkg_name] = pkg_version
return to_print
def _get_conda_env():
name = os.getenv('CONDA_DEFAULT_ENV', 'n/a')
return {"conda environment": name}
def _get_gpu_info():
if py3nvml is None:
return {"GPU Info": "Install the gpu extra "
"(pip install 'watermark[gpu]') "
"to display GPU information for NVIDIA chipsets"}
try:
gpu_info = [""]
py3nvml.nvmlInit()
num_gpus = py3nvml.nvmlDeviceGetCount()
for i in range(num_gpus):
handle = py3nvml.nvmlDeviceGetHandleByIndex(i)
gpu_name = py3nvml.nvmlDeviceGetName(handle)
gpu_info.append(f"GPU {i}: {gpu_name}")
py3nvml.nvmlShutdown()
return {"GPU Info": "\n ".join(gpu_info)}
except py3nvml.NVMLError_LibraryNotFound:
return {"GPU Info": "NVIDIA drivers do not appear "
"to be installed on this machine."}
except:
return {"GPU Info": "GPU information is not "
"available for this machine."}
|
{"/watermark/watermark.py": ["/watermark/version.py"], "/watermark/magic.py": ["/watermark/__init__.py"], "/watermark/tests/test_watermark.py": ["/watermark/__init__.py"], "/watermark/__init__.py": ["/watermark/version.py", "/watermark/magic.py", "/watermark/watermark.py"], "/watermark/tests/test_watermark_gpu.py": ["/watermark/__init__.py"]}
|
35,284
|
jGaboardi/watermark
|
refs/heads/master
|
/watermark/version.py
|
try:
import importlib.metadata as importlib_metadata
except ImportError:
# Running on pre-3.8 Python; use importlib-metadata package
import importlib_metadata
try:
__version__ = importlib_metadata.version("watermark")
except Exception:
__version__ = "unknown"
|
{"/watermark/watermark.py": ["/watermark/version.py"], "/watermark/magic.py": ["/watermark/__init__.py"], "/watermark/tests/test_watermark.py": ["/watermark/__init__.py"], "/watermark/__init__.py": ["/watermark/version.py", "/watermark/magic.py", "/watermark/watermark.py"], "/watermark/tests/test_watermark_gpu.py": ["/watermark/__init__.py"]}
|
35,285
|
jGaboardi/watermark
|
refs/heads/master
|
/setup.py
|
# Sebastian Raschka 2014-2022
# IPython magic function to print date/time stamps and
# various system information.
# Author: Sebastian Raschka <sebastianraschka.com>
#
# License: BSD 3 clause
from os.path import dirname, join, realpath
from textwrap import dedent
from setuptools import find_packages, setup
PROJECT_ROOT = dirname(realpath(__file__))
REQUIREMENTS_FILE = join(PROJECT_ROOT, "requirements.txt")
with open(REQUIREMENTS_FILE) as f:
install_reqs = f.read().splitlines()
install_reqs.append("setuptools")
# Also see settings in setup.cfg
setup(
name="watermark",
license="newBSD",
description=(
"IPython magic function to print date/time stamps and "
"various system information."
),
author="Sebastian Raschka",
author_email="mail@sebastianraschka.com",
url="https://github.com/rasbt/watermark",
packages=find_packages(exclude=[]),
install_requires=install_reqs,
extras_require={'gpu': ['py3nvml>=0.2']},
long_description=dedent(
"""\
An IPython magic extension for printing date and time stamps, version
numbers, and hardware information.
Contact
=============
If you have any questions or comments about watermark,
please feel free to contact me via
email: mail@sebastianraschka.com
This project is hosted at https://github.com/rasbt/watermark
The documentation can be found at
https://github.com/rasbt/watermark/blob/master/README.md"""
),
)
|
{"/watermark/watermark.py": ["/watermark/version.py"], "/watermark/magic.py": ["/watermark/__init__.py"], "/watermark/tests/test_watermark.py": ["/watermark/__init__.py"], "/watermark/__init__.py": ["/watermark/version.py", "/watermark/magic.py", "/watermark/watermark.py"], "/watermark/tests/test_watermark_gpu.py": ["/watermark/__init__.py"]}
|
35,286
|
jGaboardi/watermark
|
refs/heads/master
|
/watermark/magic.py
|
# -*- coding: utf-8 -*-
"""
IPython magic function to print date/time stamps and
various system information.
Author: Sebastian Raschka <sebastianraschka.com>
License: BSD 3 clause
"""
from IPython.core.magic import Magics
from IPython.core.magic import magics_class
from IPython.core.magic import line_magic
from IPython.core.magic_arguments import argument
from IPython.core.magic_arguments import magic_arguments
from IPython.core.magic_arguments import parse_argstring
from watermark import watermark
class PackageNotFoundError(Exception):
pass
@magics_class
class WaterMark(Magics):
"""
IPython magic function to print date/time stamps
and various system information.
"""
@magic_arguments()
@argument('-a', '--author', type=str,
help='prints author name')
@argument('-gu', '--github_username', type=str,
help='prints author github username')
@argument('-e', '--email', type=str,
help='prints author email')
@argument('-ws', '--website', type=str,
help='prints author or project website')
@argument('-d', '--date', action='store_true',
help='prints current date as YYYY-mm-dd')
@argument('-n', '--datename', action='store_true',
help='prints date with abbrv. day and month names')
@argument('-t', '--time', action='store_true',
help='prints current time as HH-MM-SS')
@argument('-i', '--iso8601', action='store_true',
help='prints the combined date and time including the time zone'
' in the ISO 8601 standard with UTC offset')
@argument('-z', '--timezone', action='store_true',
help='appends the local time zone')
@argument('-u', '--updated', action='store_true',
help='appends a string "Last updated: "')
@argument('-c', '--custom_time', type=str,
help='prints a valid strftime() string')
@argument('-v', '--python', action='store_true',
help='prints Python and IPython version')
@argument('-p', '--packages', type=str,
help='prints versions of specified Python modules and packages')
@argument('-co', '--conda', action='store_true',
help='prints name of current conda environment')
@argument('-h', '--hostname', action='store_true',
help='prints the host name')
@argument('-m', '--machine', action='store_true',
help='prints system and machine info')
@argument('-g', '--githash', action='store_true',
help='prints current Git commit hash')
@argument('-r', '--gitrepo', action='store_true',
help='prints current Git remote address')
@argument('-b', '--gitbranch', action='store_true',
help='prints current Git branch')
@argument('-w', '--watermark', action='store_true',
help='prints the current version of watermark')
@argument('-iv', '--iversions', action='store_true',
help='prints the name/version of all imported modules')
@argument('--gpu', action='store_true',
help='prints GPU information (currently limited to NVIDIA GPUs),'
' if available')
@line_magic
def watermark(self, line):
"""
IPython magic function to print date/time stamps
and various system information.
"""
args = vars(parse_argstring(self.watermark, line))
# renaming not to pollute the namespace
# while preserving backward compatibility
args['current_date'] = args.pop('date')
args['current_time'] = args.pop('time')
args['watermark_self'] = self
formatted_text = watermark.watermark(**args)
print(formatted_text)
def load_ipython_extension(ipython):
ipython.register_magics(WaterMark)
|
{"/watermark/watermark.py": ["/watermark/version.py"], "/watermark/magic.py": ["/watermark/__init__.py"], "/watermark/tests/test_watermark.py": ["/watermark/__init__.py"], "/watermark/__init__.py": ["/watermark/version.py", "/watermark/magic.py", "/watermark/watermark.py"], "/watermark/tests/test_watermark_gpu.py": ["/watermark/__init__.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.