# Welcome ## CPRG-100: Introduction to Python
## Course Information
### Grading | Activity | Points | |----------------------------|----------| | Assignment 1 | 25% | | Assignment 2 | 25% | | Assignment 3 | 50% |
### Resources Slides, problem sets/assignments, and additional resources can be found on the Brightspace/D2L website.
## What is Python?
### Example Python Code ```python def main(): print("Hello World!"); main() ```
### Example: Draw a Square
1. Find a whiteboard and a dry erase marker. 2. Uncap the dry erase maker. 3. Hold the marker in your hand. 4. Place the marker against the whiteboard. 5. Move your hand 1 foot to the right. 6. Stop. 7. Move your hand 1 foot down...
### Interpreted vs Compiled Languages **Interpreted** - Python, JavaScript, Ruby, PHP **Compiled** - C#, Java
### A Brief History of Python - late 1980s: designed by Guido van Rossum - Fun fact: Python is not named after the snake. It's named after Monty Python. - 1991: Python 0.9.0 released - 2000: Python 2.0 released - used for a long time and you will come across many tutorials that still use Python 2.0 so be aware - 2008 - Python 3.0 released - similar to Python 2.0 but there are subtle differences We will be using Python 3 in this class. If you look up any tutorials online, make sure to specify that you're using Python 3.
### Some Programming Tips - **Attention to Detail**: Pay attention to the tiny details. 90% of bugs are spelling mistakes, indentation errors, misplaced punctuation, wrong capitalization and similar errors. - **Your Code Will Have Bugs**: No programmer writes perfect code. Use the skills you'll learn in this class to try to solve the problem by yourself before turning to Google. Then, try researching the issue on Google before turning to others for help. - **Practice, Practice, Practice**: If you finish the activities and assignments early, think about what else you can do to improve the program. Keep practicing so you can keep learning.
### What tools do you need? To work with Python, you need to install: - Python - a text editor
### Activity: Install Python 1. Open up a command prompt on your computer. 2. Type ```python``` and press ```Enter```. If you get a message saying ```'python' is not recognized as an internal or external command, operable or batch file.``` then you need to install Python. If you don't get this message, let me know. 3. To install Python, go to https://www.python.org/downloads/ and download and install the latest version of python (3.7.3). **Check the box that says add Python 3.7 to your path.** 4. In your command prompt, run ```python```. If it does not run, let me know. You may need to reinstall if you forget to check the box that says "Add python to the PATH". 5. Type `3+3`. What do you see? 6. Type `exit()` to exit python.
### Activity - Create Your First Script 1. Make a folder on your desktop called `sait-python` 2. Inside this folder, make a new file called `hello.py`. 3. Write this code in your new python file and save. ```python print("Hello World") ``` 4. In your terminal, type: ```cmd python Desktop/sait-python/hello.py ``` 5. What do you see? 6. Make your script print another line. 7. Put an # (octothorpe, pound, hash, etc.) character at the beginning of a line. What did it do?
### Code Comments It's important to document your code! The way programmers do this is through comments. ```python # This is a comment. It begins with an octothorpe. It should be used to describe the code below it. print("This is printing out some text.") # Python's style guide recommends using the # sign per line of comment # # You can use the # sign on an otherwise empty line to make breaks between paragraphs (as seen above). ``` As we're going through different code examples, create comments to take notes on your code. Especially anything that's confusing!
### Python Variables - Assign a value to a new variable: ```python x = 2 print(x) ``` - Reassign the value later: ```python y = 5 y = 1 print(y) ```
### Assign Multiple Values - Assign a value to multiple variables: ```python x = y = z = 10 print(x) print(y) print(z) ``` - Assign multiple values to multiple variables: ```python x, y, z = 1, "Python", 999.99 print(x) print(y) print(z) ```
### Rules for Variable Names - begin with letters or _ - only contain letters, numbers, and _ - case sensitive - avoid reserved words ([list of Python keywords](http://www.pythonkey.com/python-identifiers-keywords/#keywords-list)) - choose names for clarity and meaning (generally avoid single letter variable names (e.g. `a = 2`)) - prefer underscore for multiple_words (instead of camelCase) - pick a naming convention and stick with it
### Examples of Variable Names OK: ```python num_people = 5 _num = 10 assignment_10 = True ``` Not OK: ```python 2_cool_for_school = True so_happy! = False $school = "Sait" ```
### Clearing and Deleting Values - You can clear values from variables ```python x = 5 x = None print(x) print(type(x)) ``` - You can also delete variable entirely ```python y = 10 del y print(y) ``` While x still exists (but has no value), y doesn't exist at all. X has a special type called NoneType.
### Activity: Create a Variable - In your .py file, create a variable and give it a valid name and value. - Then, print the value. - What happens if you use an invalid name? - Try clearing and deleting your variable.
## Data Types 1. number 2. string 3. list 4. tuple 5. dictionary
### Number - Python supports 3 different numerical types - **int** (plain integers): positive or negative whole numbers - **float** (floating point values): written in decimal points - **complex** (complex numbers): take the form of x + yJ where x and y are floating numbers and J represents the square root of -1 (an imaginary number). Not used much in Python programming. ```python x = 1 print(type(x)) y = 1.5 print(type(y)) z = 1+2J print(type(z)) ``` You can use the built-in `type()` method to see what type each piece of data is.
## Operators
### Arithmetic Operators - `+` plus - `-` minus - `/` divide - `*` multiply - `%` modulus (the remainder after dividing num1 by num2) - `**` exponent - `//` floor division (rounds down to nearest whole number) ```python a = 3+2 # 5 b = 5.5/2 # 2.75 c = 2%2 # 0 (the remainder after dividing 2 by 2) d = 3//2 # 1 (1.5 rounds down to 1) e = 3**2 # 9 (3 to the power of 2) ```
### Activity: Let's Do Some Math 1. In your `hello.py` file: - print 5 divided by 2 - print the remainder after dividing 9 by 5 - print 10 to the power of 100 2. Print the type of each answer.
### Comparison Operators - `==` equal to - `!=` not equal to - `>` greater than - `<` less than - `>=` greater than or equal to - `<=` less than or equal to ```python a = 2 == 3 # False b = 2 != 3 # True c = 2 > 3 # False d = 2 < 3 # True e = 2 >= 3 # False f = 2 <= 3 # True ``` - Boolean Type ```python a = 2 == 3 print(type(a)) ```
### Activity: Let's Compare 1. In your `hello.py` file print the following tests: - Is 20 greater than 11? - Is 20 equal to 20? - Is 7 not equal to 11? 2. Print the type of each answer.
### Assignment Operators Used to directly assign the answer of an operation to another varibable or to assign the value of one variable to another. - `=` assign a value to the variable - `+=` take the variable's value and add a new value to it - `-=` subtract a new value from the variable's value - `*=` multiply the variable's value by a new value - `/=` divide the variable's value by a new value - `%=` get the remainder of the variable's value divided by a new value - `**=` get the variable's value raised to a new value - `//=` get the variable's value divided by a new value and round down
### Activity: Assignment Operators Here's some examples of how assignment operators work. ```python a = 1 # a equals 1 b += 1 # b equals b + 1 c -= 1 # c equals c - 1 d *= 1 # d equals d * 1 e /= 1 # e equals e / 1 f %= 2 # f equals the remainder of f / 2 g **= 2 # g equals g to the power of 2 h //= 2 # h equals h / 2 (rounded down) ``` 1. Create the variable a and assign it the value of 5. 2. Assign a the remainder after dividing a by 1.5. 3. Assign a the value of a to the power of 3. 4. Assign a the value of a multiplied by 70. 4. Assign a the value of a divided by 2 (and round down). 5. What is a?
### Bitwise Operators - Used to perform bitwise logical operations on integers. Whenever you need to control specific bits. - Much less used than arithmetic operators. - Used more often in low-level programming (like when working on embedded devices) We're not going to get into that here since it's a more advanced topic, but you should know that they exist.
## Back to Data Types 1. number 2. string 3. list 4. tuple 5. dictionary
### Strings - Strings are a list of characters and can use any symbol. ```python greeting = "Hello World" ``` - Often used to store words or sentences - A number represented as a string can't be used to do math because it's a string, not a number. ```python sentence = "This is a string." x = "3" print(type(x)) ```
### Manipulating Strings #### Slicing Strings - Take part of the string and ignore the rest ```python string[a:b] # returns part of the string from the a character to the b character, including a but excluding b string[:b] # if you omit the first index, the slice starts at the beginning of the string string[a:] # if you omit the second index, the slice goes to the end of the string ```
In python, start counting indices from 0. The first letter in a string is in the 0 index. The 2nd letter in a string is in the 1st index.
```python greeting = "Hello Beautiful World!" short_greeting = greeting[:5] greeting_adjective = greeting[6:15] greeted = greeting[16:] print(short_greeting, greeting_adjective, greeted) ```
### Manipulating Strings #### Concatenating Strings - Add two strings together ```python old_string = "Here is some text." new_string = old_string + " And here is some extra text." print(new_string) ```
### Beware Math with Strings If you try to perform math with strings, you may find some weird things happening in your code. Always check to make sure you used a number when you want a number, not a string. ```python a = "4" b = 2 print(a*b) # 44 because you are printing `a` twice. x = "4" y = 2 print (x+y) # TypeError because you can't concatenate a number to a string or add a string to a number ```
### Activity: Making Strings 1. Create a variable called my_first_name and assign it the value of your first name. 2. Create a variable called my_last_name and assign it the value of your last name. 3. Create a variable called my_full_name and assign it the value of my_first_name and my_last_name concatenated together. 4. Print the last 3 characters in your full name. 5. Try printing the middle 3 characters of your full name.
### Lists - Lists hold lists of data - lists can contain multiple data types (like numbers and strings and even other lists) ```python fruits = ["Apples", "Oranges", "Bananas"] numbers = [1, 2, 3] favorite_things = ["red", "video games", "tea"] superman = ["Superman", 84, True, ["Batman", "Robin"]] ```
### Getting Information from a List Similar to strings, we can also get items in a list. ```python list = ['abcd', 786, 2.23, ['John', 70.2, True]] tiny_list = [123, 'Smith', False] # Python uses zero-based indexing (the first item is 0) first_item = list[0] second_and_third = list[1:3] # includes index 1 through 3, excluding 3 name = list[3][0] # access item from multi-dimensional array double_tiny_list = tiny_list * 2 large_list = list + tiny_list ```
### Manipulating Lists - Create new items in the list ```python # Add 1 item to the list fruits = ["oranges", "apples", "bananas"] fruits.append("watermelon") # Add multiple items to the list fruits.extend(["canteloupe", "pineapple"]) # Insert item in a particular spot in the list fruits.insert(3, "kiwi") # kiwi becomes the 4th item in the list ``` - Remove an item from the list ```python # Remove item if you know which item you want to remove fruits.remove("watermelon") # Remove item in specific index fruits.pop(2) ```
### Manipulating Lists - Update item in list ```python # Access item in specific index and assign it a new value fruits[2] = "mango" print(fruits) ```
Other List Methods
### Activity: Create a List Print your list after each task. 1. Create a list of 3 of your favorite foods. 2. Add an item to the list. 3. Remove an item from the list. 4. Add 2 items to the list at the same time. 5. Remove an item in index 2. 6. Change the value of the item in index 1.
### Tuple - Similar to lists but cannot be updated - Read-only ```python vegetables = ( 'carrots', 'broccoli', 'celery') print(vegetables) ``` You cannot change items in a tuple.
### Getting Info from Tuple Similar to strings and lists, we can also get slices of a tuple or concatenate tuples. ```python tuple = ('abcd', 786, 2.23, ['John', 70.2, True]) tiny_tuple = (123, 'Smith', False) # Python uses zero-based indexing (the first item is 0) first_item = tuple[0] second_and_third = tuple[1:3] # includes index 1 through 3, excluding 3 name = tuple[3][0] # access item from multi-dimensional array double_tiny_tuple = tiny_tuple * 2 large_tuple = tuple + tiny_tuple ```
### Manipulating Tuples - Unlike lists, we cannot create new items, update, or remove items from a tuple. ```python tuple = ('abcd', 786, 2.23, ['John', 70.2, True]) tuple.append("cauliflower") # AttributeError: 'tuple' object has no attribute 'append' ``` - Weirdly, you can manipulate lists within a tuple ```python tuple[3].append("whoa!") print(tuple) ``` This is because that list can still be found in the same location in memory, even if you changed the list itself.
Additonal Reading:
Python tuples are immutable but may change
### Lists vs Tuples - General rule of thumb: If you don't need to change the items in the list of values, use a tuple instead of a list.
### Activity: Create a Tuple Print your tuple after each task. 1. Create a tuple with 3 items: - a string - a number - a list of 3 items 2. Print a slice of the tuple with just the last item in it. 3. Try using the list insert method to add an item to your tuple. What error do you get?
### Dictionaries - Dictionaries are a type of collection that work with a key-value pair - Used if you want to associate one value with another - You can store any type of data in a dictionary - Keys must be unique ```python favorites = {'vegetable': 'celery', 'fruit': 'apples', 'tv show': 'Leverage', 'number': 16} ```
### Getting Information from a Dictionary ```python favorites = {'vegetable': 'celery', 'fruit': 'apples', 'tv show': 'Leverage', 'numbers': [1, 16], 'books': {'scifi': 'Red Shirts' , 'nonfiction': 'Hello Design World'} } # Instead of using index like lists, dictionaries use keys to access values favorite_vegetable = favorites['vegetable'] # get all the keys in a dictionary favorite_categories = favorites.keys() # get all the values in a dictionary favorite_things = favorites.values() # Keep in mind that .keys() and .values() return special types print(favorites.keys()) print(type(favorites.keys())) ``` Later, I'll show you how to convert dict_keys and dict_values into lists.
### Manipulating Dictionaries Create new items in the dictionary ```python # Add 1 item to the dictionary favorites = {'vegetable': 'celery', 'fruit': 'apples', 'tv show': 'Leverage', 'number': 16} favorites['dessert'] = 'ice cream' ``` Remove items from the dictionary ```python # Delete an entry from the dictionary. Specify the key to delete. del favorites['vegetable'] # Clear the dictionary of all key-value pairs favorites.clear() ```
### Manipulating Dictionaries Update item in dictionary ```python # Access specific key and assign it a new value favorites['fruit'] = 'orange' print(favorites) # Merge a dictionary with another dictionary more_favorites = {'color': 'blue', 'animal': 'cat'} favorites.update(more_favorites) print(favorites) ```
More Info on Dictionaries
### Activity: Create a Dictionary Print your dictionary after each task. 1. Create a dictionary about yourself. - For now, just include your last name and first name. 2. Add your age to the dictionary. 3. Print the values of the dictionary. 4. Merge another dictionary into the first dictionary. The new dictionary should hold your eye color and height. 5. Remove your height from the dictionary. 6. Clear the dictionary.
## Decision Making
## Boolean Variables
### Boolean Variables - Represent logical values: ```True``` and ```False```. ```python catsAreBest = True dogsRule = False ```
### Boolean Variables - Some values are considered ```falsy```. - They evaluate to ```False``` in a Boolean context. ```python # the following variables will evaluate as False my_name = ''; # empty string num_of_kids = 0; # 0 favorites = [] # empty list person = {} # empty dictionary ``` - ```None``` will also evaluate as ```False```. - Most everything else evaluates as ```True```. - You can check to see if a value evaluates to True or False ```python bool(([])) # False ```
## Control Flow
### The `if` statement Use ```if``` statements to decide which lines of code to execute, based on a condition. ```python # Template Code if condition: # statements to execute # Example age = 30 if age > 18: print('You are an adult') ```
### Refresher: Comparison Operators | Symbol | Purpose | | --------- | ----------------------------------------------- | | ```==``` | Tests if LHS is Equal to RHS | | ```!=``` | Tests if LHS is Not equal to RHS | | ```<``` | Tests if LHS is Less than RHS | | ```>``` | Tests if LHS is Greater than RHS | | ```<=``` | Tests if LHS is Less than or equal to RHS | | ```>=``` | Tests if LHS is Greater than or equal to RHS |
### Activity: Temperature - Make a variable called "temperature". - Write some code that tells you to put on a coat if it is below 10 degrees.
### The `else` statement Use ```else``` to provide an alternate set of instructions. ```python age = 30 if age >= 16: print('Yay, you can drive!') else: print('Sorry, you have to wait before you can drive.') ```
### The `elif` statement If you have multiple conditions, you can use ```elif```. ```python age = 30 if age >= 65: print('I am at least 65 years old.') elif age >= 30: print('I am at least 30 years old.') elif age >= 18: print('I am at least 18 years old.') else: print('I am younger than 18 years old.') ```
### Activity: Modify Temperature Code Modify your "wear a coat" code for these conditions: - If it's less than 10 degrees, wear a coat. - If it's less than 0 degrees, wear a coat and a hat. - If it's less than -20 degrees, stay inside. - Otherwise, wear whatever you want. **Hint:** Think about the order of your if, elif, and else statements. The test must fail in order to move on to the next test. If a test passes, it won't keep testing later conditions.
### Answer ```python temperature = 20 if temperature < -20: print("Stay inside.") elif temperature < 0: print("Wear a coat and hat.") elif temperature < 10: print("Wear a coat.") else: print("Wear whatever you want.") ```
### Nested `if` Statements You can nest if statements to handle even more complex logic. ```python age = 30 if age > 30: print("You are older than 30.") if age > 60: print("You are also older than 60.") else: print("You are 30 or younger.") ``` Try not to nest too many if statements or it will make your code hard to read and understand.
### Logical Operators ```and``` - True if both LHS **and** RHS are True ```or``` - True if LHS **or** RHS is True ```not``` - True if operand is **not** True (True if operand is False)
### Using Logical Operators ```python likes_dogs = True likes_cats = True # If/Else Statement to check which animals a person likes if likes_dogs and likes_cats: print('I like dogs and cats.') elif likes_dogs or likes_cats: print('I like cats or dogs, but not both.') else: print("I don't like dogs or cats.") # If Statement to see if person doesn't like dogs if not likes_dogs: print("They don't like dogs.") ```
### Activity: Logical Operators - Create two variables (`sunny` and `warm`) - Create an If/Else Statement with the following conditions (you can use `elif`) - If it's sunny and warm, tell them to wear sunglasses and sunscreen. - Otherwise, if it's sunny or warm, tell them to enjoy the half-nice weather. - Otherwise, tell them to wear a jacket.
## Loops
### `while` loops ```while``` will repeat the same code over and over while some condition is true. ```python while (condition is True): # do something ``` ```python bottles_of_beer = 99 # initial value to check while bottles_of_beer > 0: print(bottles_of_beer) bottles_of_beer -= 1 # Take 1 away each time. We don't want to get stuck in an infinite loop. ```
### `while` loops continued If the user is providing information, they're in control of when the loop stops. This loop will continue over and over until the user enters the right password. ```python password = "" while password != "123456": password = input("What is the password? ") ```
input()
is a built-in method that allows us to ask the user for information.
### Warning: Infinite Loops Make sure something changes in the loop or your loop will go on forever. ```python bottles_of_beer = 99 # initial value to check while bottles_of_beer > 0: print(bottles_of_beer) ``` This will print "99" forever because we didn't do anything to change the loop.
### Activity: While Loop Write a while loop that prints out the numbers 1 through 10.
**Bonus:** Try printing out the times table by nesting a while loop inside a while loop. - 1x1 = 1 - 1x2 = 2 - all the way to 10x10 = 100
### Answers ```python num = 1 num2 = 1 while num < 11: print(num) num += 1 # increase num by 1 each time so we get closer to 11 ``` ```python num = 1 num2 = 1 while num < 11: while num2 < 11: print(num*num2) num2 += 1 # increase num2 by 1 each time we get closer to 11 num2 = 1 # start num2 over at 1 every time we exit the num2 while loop num += 1 # increase num by 1 each time so we get closer to 11 ```
### `for` loops ```for``` loops are very similar to `while` loops but they are used for iterating over a collection. ```python for var in iterable: # do something ``` ```python # will count 1 to 10 for i in range(1,11): print(i) # will loop through a list fruits = ["oranges", "apples", "bananas"] for fruit in fruits: print(fruit) # will loop through characters in a string name = "Heather" for letter in name: print(letter) ``` You can also loop through tuples and dictionaries.
### Nested `for` Loops You can nest for loops to write more complicated code. ```python # will loop through a list and print each letter in each string fruits = ["oranges", "apples", "bananas"] for fruit in fruits: for letter in fruit: print(letter) ```
### Activity: For Loop - Create a list `weather` and loop over it to print out different types of weather.
**Bonus:** Create a list of lists. - For example: ```python shopping = [["oranges", "apples"], ["jeans", "shirt"], ["bagels", "muffins"]] ``` - Use a nested `for` loop to print out each item.
### Answers ```python weather = ["sun", "rain", "snow", "fog"] for type in weather: print(type) ``` ```python shopping = [["oranges", "apples"], ["jeans", "shirt"], ["bagels", "muffins"]] for category in shopping: for item in category: print(item) ```
### Loop Control Statements There are 3 loop control statements you can use to alter the loop. - `break` - Breaks out of the current loop. - `continue` - Loop skips whatever is remaining in that iteration and starts executing the next iteration of the loop. - `pass` - used when you do not want any command or code to execute
### Loop Control Statement Examples ```python # Breaks out the loop as soon as it gets to the "h" for letter in 'Python': if letter == 'h': break print(letter) # Skips h and continues to the next letter for letter in 'Python': if letter == 'h': continue print(letter) # Nothing happens when pass is executed. Pass is often used as placeholder code. Eventually, you may do something if the letter is "h". for letter in 'Python': if letter == 'h': pass print(letter) ```
### Activity: Loop Control 1. Create a list of animal types. 2. Loop through the list and print each item. 3. Break when you get to the 3rd item in the list.
### Loops and Logic You can add other statements or logical operators inside loops. ```python # Count from 1 to 100 for i in range(1, 101): if i % 3 == 0: # Prints 'Fizz' after multiples of three print(i, 'Fizz') elif i % 5 == 0: # Prints 'Buzz' after multiples of five print(i, 'Buzz') else: print(i) ```
### Activity: Logic in Loops - Write a for loop that will iterate from 0 to 20. - For each iteration, check if the current number is even or odd, and print the number and whether it's even or odd.
### Converting Between Data Types So far, we've been working with numbers or strings, but sometimes we want to combine them. For example, maybe we want to print out a number as part of a string. ```python num = 11 item = "apples" num_of_items = num + "apples" # TypeError: unsupported operand type(s) for +: 'int' and 'str' num_of_items = str(num) + "apples" # "11 apples" ```
### Type Conversion Methods ```python # Turn data into an integer string = "10010" num = int(string) # Turn data into a floating number floating_num = float(string) # Turn data into a tuple tuple = tuple(string) # Turn data into a list list = list(string) ``` The `input()` method will always return a string. If you want to do math with numbers entered by the user, you'll need to convert it into a number. ```python age = input("How old are you? ") age_prediction = "You will be " + str(int(age) + 5) + " in 5 years." print(age_prediction) ```
How to Convert Data Types in Python 3
### Activity: Magic Trick Input any number and I'll predict what you end up with after some math. 1. Use the `input()` method to enter any number between 1 and 20. 2. Add 1 to the number. 3. Double the new number. 4. Add 4 to the new number. 5. Divide the new number by 2. 6. Subtract the original number from the new number. 7. Print a statement like: "The final number is " + final_number. Did you get the number 3?
## Functions ![](img/lego-blocks.jpg)
### Declaring Functions To declare (create) a function, you can give it a name, then include all the code for the function. ```python def function_name(parameters): # statements ``` ```python def parrotFacts(): print('Some parrot species can live for over 80 years.') print('Kakapos are a critically endangered flightless parrot.') ```
### Using Functions To invoke (use) a function, type its name, followed by a parenthesis ```()``` ```js parrotFacts() ```
### Activity: Write a Function - Write a function that prints out a sentence. - Call that function in your code.
### Arguments Functions can accept input values, called ```arguments```. ```python def function_name(parameters): # statements function_name(arguments) ``` ```python def call_kitten(name): print('Come here, ' + name + '!') # prints 'Come here, Fluffy!' call_kitten('Fluffy') ``` ```python def add_numbers(a, b): print(a + b) # prints 12 add_numbers(5, 7) # prints 21 add_numbers(9, 12) ```
### Arguments You can pass ```variables``` into functions. ```python def add_one(num): new_number = num + 1 print('You now have ' + str(new_number)) # Declare variables number_kittens = 5 number_puppies = 4 # Use them in functions add_one(number_kittens) add_one(number_puppies) ```
### Activity: Write a Simple Function - Write a simple function to print out a first name and a last name. - Update the function to accept a first and last name as arguments.
### Returning Values - So far, we've been printing inside our functions. But really,you should use `return` inside a function. - `return` will allow the function to give back a value to use later. ```python def square(num): return num * num print(square(4)) # prints '16' square_of_five = square(5) # square_of_five equals '25' ``` ```return``` will immediately end a function. No code can follow after a return statement.
### Activity: Return Statements - Add a return statement to your "name" function. - Use that function to set the value of a variable.
## Python Modules
### What is a module? - Modules are used to help organize and compartmentalize code - A Module is like a regular python program but it just contains functions and variables - You can import this file to use it in other programs
### How to Create a Module So far, we've been working in `hello.py`, but now we're going to create new files to hold our modules. - Create a new file called `support.py`. - In this file, add the following code: ```python def add_one(num): return num + 1 school = "SAIT" ``` - Go back to your `hello.py` file. - At the very top, import the `support` module. ```python import support ```
### How to Create a Module (part 2) - Now, you can call the functions and access the variables held in support.py. In `hello.py`, write: ```python add_to_5 = support.add_one(5) print(add_to_5) print(support.school) ```
There's a lot you can do with modules. Read
Python Modules and Packages
to learn more.
### Activity: Create a Module 1. Create a new file called `greeting.py`. 2. Inside that file, write the following code: ```python def greet(name): return("Hello " + name) ``` 3. Create a new file called `main.py`. 4. Inside this file, import the greeting module. ```python import greeting ``` 5. Then, call the greet function inside `main.py`. ```python greeting.greet("Heather") ```
### Importing Python Modules - There are a number of modules built into the [Python Standard Library](https://docs.python.org/3/library/) that we can use to get access to system functionality or standardized solutions. - The Python Standard Library is part of every Python installation. Once you find a module you want to use, you can simply import it like we imported the module we wrote. ```python import math # Some of the many methods and constants we get access to once importing math.pi # Gives you the value of pi math.ceil(num) # Rounds the number up math.floor(num) # Rounds the number down math.sqrt(num) # Returns the square root of num ```
### Activity: Import a Python Module 1. Import the math module. 2. Create a function that takes a number and multiplies it by pi. 3. Return the number rounded up.
### Validating Strings - One common module import is the `re` module. This allows us to validate our strings and check to see if they have invalid characters. - Provides regular expression matching operations. - This is great for: - searching for specific characters or phrases - cleaning data - validating passwords - and more! ```python import re ```
For more information and practice with regular expressions: [https://regexone.com/](https://regexone.com/)
### Validating Strings Example Let's say you need to validate names to make sure they only contain lowercase or uppercase letters, or hyphens. You can simplify this process by using regular expressions and the `re` module. ```python import re # ^[A-Z][a-z]*$ is a pattern that checks names to make sure they start with an uppercase letter followed by lowercase letters which may or may not be followed by a hyphen and more letters. valid_expression = re.compile(r'^[A-Z][a-z]*$') # Take the valid_expression and use it to compare to other strings. first_name = valid_expression.match("Taylor") print(first_name) #
(means it found a match) second_name = valid_expression.match("J@seph") print(second_name) # None (means it didn't find a match) third_name = valid_expression.match("jane") print(second_name) # None (means it didn't find a match) ```
### Activity: Use the `re` module 1. Import the re module into your code 2. Compile a regular expression that looks for all uppercase letters ('[A-Z]') 3. Use `match()` to test the following strings: - "HELLO" - "world" - "Hello" - "World"
## File I/O
### What is a file? - Used to permanently store data on a hard drive, for example. - .txt - .csv - .json - When we want to read from or write to a file, we follow this order of operations: 1. Open a file 2. Read or write (perform operation) 3. Close the file
### Activity: Create a Sample .txt File For now, we're going to create an example .txt file that we can practice with in a bit. In your folder, create sample.txt and write/save the following lines: ```txt Hello world! Python is a lot of fun to learn. We can do all sorts of things including reading and writing to files. Let's get started! ```
### How to Open a File - Python has a built-in function `open()` used to open a file. - We can specify the mode while opening the file. - `r` - Open a file for reading. (default) - `w` - Open a file for writing. Creates a new file if it doesn't exist. Truncates (empties) the file. - `a` - Opens for appending at the end of the file without truncating it. Creates a new file if it doesn't exist. - `r+` - Opens a file for reading and writing. Starts at beginning of file. Doesn't create a new file if it doesn't exist. - `w+` - Opens a file for writing and reading. Truncates file. Creates a new file if it doesn't exist. - `a+` - Opens a file for both appending and reading. Starts at end of file. Creates new file if it doesn't exist.
You can also open files in Binary format by adding a `b` after the `r`, `w`, or `a`. To find out more:
https://www.nayuki.io/page/what-are-binary-and-text-files
### Opening Files ```python file = open('text.txt') # Open file in read mode. file = open('text.txt', 'w') # Open file in write mode. file = open('text.txt', 'r+') # Open file in read+ mode. ```
### Reading from files - Python contains 3 functions to read files: - `read()` - reads the entire file - `readline()` - reads a single line from the file - `readlines()` - reads the entire file line by line ```python file = open('text.txt') text = file.read() print(text) ``` - `readlines()` is considered much slower and less efficient than `read()` - If you need to read line by line, try a loop ```python for line in file: print(line) ```
### Activity: Reading In `hello.py`, try opening and then reading your file in different ways.
### Writing to Files When writing to a file, any information inside the file already will be overwritten. ```python file = open('test.txt', 'w') file.write("This is a test. Let's write to this file.") ``` We'll need to use `w+` if we want to write AND read from the file. ```python file = open('test.txt', 'w+') file.write("This is another test.") # After writing, the file's current position will be at the end of the file. We'll need to move it back to the beginning. file.seek(0) text = file.read() print(text) ``` If you want to check the current position of the file, you can use `file.tell()`.
### Activity: Write to a File 1. Rewrite your code to open the file and write some new text to it instead. 2. Seek to the beginning of the file. 3. Print the text.
### Writing Multiple Lines Instead of having to type `file.write()` for each line, we can use `writelines()` with a list of lines we want to add. ```python todo_list = ["To Do: \n", "Pick up mail\n", "Go to class\n", "Do homework\n"] file = open('test.txt', 'w') file.writelines(todo_list) ``` `\n` is how we tell the program to write a new line.
### Activity: Write Multiple Lines 1. Create your own to do list in a list. 2. Write to `sample.txt`. 3. Open the file in a text editor and verify that you changed the file.
### Appending to Files - Appending is very similar to writing, but instead of overwriting the file, you're adding to the existing file. ```python file = open('test.txt', 'a') file.write("Let's add to the file!") ``` We can use the same `write()` and `writelines()` methods when appending.
### Activity: Add to Your To-do List 1. Open `sample.txt`. 2. This time, add several more tasks to your to-do list.
### Closing a File When you're finished with a file, you want to close it so that you clear your memory buffer. - This means you will no longer be able to read from the file. You'll have to open it again if you want to do more with it later. ```python # Good: Basic method file.close() # Better: With statement. Closes file by itself. with open('test.txt') as file: # perform file operations ```
### Activity: Close Your File You're finished writing your to-do list now, so make sure to close the file. Bonus: Rewrite your code to open the file using the `with` statement instead.
### Working with CSV - CSV files are used to store a large number of variables - or data. (Similar to Excel but very simplified) - CSV - Comma Separated Values - Very useful for importing or exporting spreadsheets and databases - Python has a CSV module you can use to make working with these files even simpler
### CSV Module - You can use loop and .split() methods to get data from CSV files. - OR, you can use the CSV module. ```python import csv # Reading to a CSV File with open('sample.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row) ```
### Writing with CSV Module `writerow()` and `writerows()` ```python # Writing to a CSV File address = ['Jane','Awesome','210 Rainbow Lane','Calgary','AB','T2A 4E8'] with open('sample.csv', 'w') as file: writer = csv.writer(file) writer.writerow(address) # Writing Multiple Lines to a CSV File addresses = [['Jane','Awesome','210 Rainbow Lane','Calgary','AB','T2A 4E8'],['Joe','Canada','1115 Terrace Blvd','Calgary','AB','T2B 4A8']] with open('sample.csv', 'w') as file: writer = csv.writer(file) writer.writerows(addresses) ``` - Writing with Python to CSV adds a blank row between each line
For more info:
https://docs.python.org/3/library/csv.html
### Activity: Working With Spreadsheets 1. Download the sample.csv file from BrightSpace 2. Print out every row 3. Create a new .csv file (in Python) and add a new address to it.
### Moving and Deleting Files in Python To move, copy, or delete a file in Python, you will need to import the `os` module. Let's say we have a file sitting in a folder called d1 and we want to move it to a folder named d2. ```python import os # Create new directory os.mkdir('d2') # Move a file by renaming its path # The destination direction needs to exist in order for this to work. os.rename('d1/sample.txt', 'd2/sample.txt') # Delete sample.txt os.remove('d2/sample.txt') ```
## Handling Exceptions
### What are Exceptions? - Python has many built-in exceptions which forces your program to output an error when something goes wrong. - When an exception occurs, the current process stops and waits for the the exception to be handled. If it isn't handled, the program crashes. ```python def a(): b() def b(): c() def c(): # broken code that causes exception to occur # if exception isn't handled in c, passes exception to b, and then to a ```
### Why Should You Handle Exceptions? - If you're using an app, do you want the app to completely stop when an error occurs? - Or maybe instead it should handle it or let you know what's going on.
### Built-In Exceptions Python provides us with quite a few basic exception classes that are already defined and can be used in general cases ([link](https://airbrake.io/blog/python-exception-handling/class-hierarchy)). Example: `ImportError` is raised when you try to import a module which does not exist. ```python import non_existing_module ``` In the console: ```console Traceback (most recent call last): File "hello.py", line 1, in
import does_not_exist ModuleNotFoundError: No module named 'does_not_exist' ``` `ModuleNotFoundError` is a subclass of `ImportError`.
### Handling Exceptions Python handles exceptions using `try` and `except` blocks. - `try` - write the code which might raise an exception. - `exception` - write the code to handle this exception. Exception Raised ```python for i in range(3): print(3/i) print("This doesn't print because the exception was not handled") ``` Handling Exception ```python try: for i in range(3): print(3/i) except: print("You divided by 0") print('This prints because the exception was handled') ```
### Multiple Except Blocks It is possible to have multiple except blocks for one try block. ```python a,b=1,0 try: print(a/b) print("This won't be printed") print('10'+10) except TypeError: print("You added values of incompatible types") except ZeroDivisionError: print("You divided by 0") ```
### Except Block with Multiple Exceptions You can also have one except block handle multiple exceptions. ```python try: print('10'+10) print(1/0) except (TypeError,ZeroDivisionError): print("Invalid input") ```
### Generic Except After All Other Excepts ```python try: print('1'+1) print(ignore) print(1/0) except NameError: print("i does not exist") except ZeroDivisionError: print("Cannot divide by 0") except: print("Something went wrong") ```
### `finally` Optionally, you may include a `finally` exception block after the last except block. The code under this block executes no matter what (error or no error). ```python try: print(1/0) except ValueError: print("This is a value error.") finally: print("This will print no matter what.") ```
### Managing Files `try...finally` is often used for handling files. ```python try: file = open('test.txt') # perform file operations finally: f.close() ``` You will want to close this file whether or not the operations you performed on it were successful. Finally, makes sure that the file is closed no matter what.
### `raise` Sometimes you may want to deal with a situation by raising your own exception. Use the most specific Exception that fits your issue ([link](https://docs.python.org/3/library/exceptions.html#exception-hierarchy)). ```python x = 10 if x > 5: raise ValueError('x should not exceed 5.') ``` Otherwise, you can use the generic Exception. ```python raise Exception('Meaningful message indicating the source of the error') ```
### Activity: Exceptions 1. Write a function to compute 5/0 and use try/except to catch the exceptions. 2. Write a function to add any 2 numbers together. Raise an Exception if one of the numbers is 2.


GitHubIf social coding is your thing
Google GroupsIf you're from IITB
FBIf you want to follow interesting topics!


Missing autistic East Kilbride schoolboy found safe and well
Police Scotland has confirmed that Aiden Lochrie has been located.
by Record ReporterA 14-year-old autistic boy has been found safe and well after going missing in East Kilbride.
Police confirmed news that Aiden Lochrie has been traced, hours after an appeal was launched to help find him.
The teenager was reported missing after failing to return home from Duncanrig Secondary in the town yesterday afternoon.
The police thanked everyone who helped locate Aiden.
For the latest news and breaking news visit dailyrecord.co.uk
Get all the big headlines, pictures, analysis, opinion and video on the stories that matter to you.
Follow us on Twitter @Daily_Record - the official Daily Record Twitter account - real news in real time.
We're also on Facebook - your must-see news, features, videos and pictures throughout the day from the Daily Record, Sunday Mail and Record Online.


#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <libgen.h>
#include <stdlib.h>
#include <ctype.h>
#include <fnmatch.h>
#include "devtag-allinone.h"
Go to the source code of this file.
Defines | |
| #define | DEVTAG_ALLINONE |
Functions | |
| int | devtag_usb_scan (struct dev_head *result, const struct devinfo_head *sel) |
| int | devtag_dev_scan (struct dev_head *result, const struct devinfo_head *sel) |
| int | devtag_lookup2 (char *buf, size_t bufsize, char *constbuf, size_t constsize, const char *devname) |
| int | devtag_lookup (char *buf, size_t bufsize, const char *devname) |
| char * | devtag_get (const char *devname) |
| #define DEVTAG_ALLINONE |
Definition at line 1 of file devtag-allinone.c.
| int devtag_dev_scan | ( | struct dev_head * | result, | |
| const struct devinfo_head * | sel | |||
| ) |
Definition at line 259 of file devtag-allinone.c.
References devtag_usb_scan().
| char* devtag_get | ( | const char * | devname | ) |
| int devtag_lookup | ( | char * | buf, | |
| size_t | bufsize, | |||
| const char * | devname | |||
| ) |
Definition at line 435 of file devtag-allinone.c.
References devtag_lookup2().
Referenced by devtag_get().
| int devtag_lookup2 | ( | char * | buf, | |
| size_t | bufsize, | |||
| char * | constbuf, | |||
| size_t | constsize, | |||
| const char * | devname | |||
| ) |
Definition at line 373 of file devtag-allinone.c.
References devname::devname, dev::devnames, devtag_usb_scan(), devname_head::head, dev_head::head, devinfo_head::head, and dev::next.
Referenced by devtag_lookup().
| int devtag_usb_scan | ( | struct dev_head * | result, | |
| const struct devinfo_head * | sel | |||
| ) |
Definition at line 58 of file devtag-allinone.c.
Referenced by devtag_dev_scan(), and devtag_lookup2().


lab02 : ASCII Art: Logical operators, integrating github into your workflow
| num | ready? | description | assigned | due |
|---|---|---|---|---|
| lab02 | true | ASCII Art: Logical operators, integrating github into your workflow | Tue 04/17 10:00AM | Mon 04/23 11:59PM |
Pre-lab prep
-
Read this article on git basic workflow
-
Remotely log into your account on the csil servers and try to complete Step 1a of the lab that walks you through doing some initial ONE-TIME git configurations in your CoE account on CSIL.
*Read through the entire lab, and identify parts that seem unclear to you. You can let your mentor know about this at the beginning of the lab.
Goals for this lab
By the time you have completed this lab, you should be able to
- Use if/else and for loops to print various kinds of shapes with "ASCII Art"
- Show that you understand how to work through the basic process of test-driven development in C++
- Integrate github into your work flow
Skills Needed
By now, we expect that you are comfortable with these basic skills from lab00 and lab01 so we will no longer describe them in as much detail as we did previously:
- Using a text-editor to create and/or edit C++ programs
- Compiling and running C++ programs
- Using the computers in both the CSIL and the Phelps labs to do basic things:
- Performing basic management of directories and files with Unix commands such as mkdir, cd, pwd, ls, cp, mv
- Submitting assignments in this class with the gradescope system, and checking your results
Step 0: Check-in with your mentor
-
At the start of every lab, you and your partner should get together with your mentor group and mentor. Your mentor will give you any initial instructions as required for the lab, guiding you on the key learning goals and any challenging aspects that you need to pay special attention to. They will also take your attendance for that lab. This is also a time when you will check in about your progress in the programming assignments. Make sure that you always have the latest version of your code pushed to github before your weekly check-in with your mentor.
-
If you reported a different partner to your mentor last week, please update your mentor before you proceed with the rest of the lab
-
Choose who will be the pilot for the first part of the lab. The pilot should sit down in front of the computer now. The navigator gets a chair and sits next to the pilot. You should exchange roles after awhile, before the pilot gets tired, and before the navigator gets bored or distracted.
-
If your partner shows up late, let your mentor know. Points will be deducted for students who don’t show up on time. If you face difficulties with pair programming consult your mentor.
Below are the links to different sections of the lab:
- Step by step instructions to getting setup with github
- Ascii Art
- An example for you to follow: starL
- What you’ll be doing
- Step by Step Instructions
- Evaluation and grading
Step by Step Instructions to getting setup with github
Step 1a: Do some initial ONE-TIME git configurations (this step has to be done individually)
-
On separate machines, log onto your account.
-
Open a terminal window. As a reminder, that’s the Application Menu, then System Tools, then Terminal Window.
-
In your ~/cs16 directory, type the following commands, replacing Alex Triton with your name and<EMAIL_ADDRESS>with your email address.
git config --global user.name "Alex Triton"
git config --global user.email<EMAIL_ADDRESS>- Next, generate a private/public key pair and upload your public key to your github account. To do this refer to this tutorial: https://ucsb-cs56-pconrad.github.io/topics/github_ssh_keys/ In the process of setting up your key pair, when asked for a passphrase just press enter. By doing this step you will avoid having to enter a password or passphrase everytime you push your code to git.
Step 1b: Create a new repo, add your partner as collaborator and clone the git repo that contains the starter code
-
Create a repo for this lab on the pilot’s github account (just like you did in lab00): To do this, open a browser and navigate to www.github.com. Log into the pilot’s github account. From the drop down menu on the left, select our class organization: ucsb-cs16-s18-mirza and proceed to create a new repo. You may refer to the instructions in lab00. Follow this naming convention: If your github username is jgaucho and your partner’s is alily, your should name your repo lab02_agaucho_alily (usernames appear in alphabetical order). Also you must set the visibity of your repo to be ‘PRIVATE’ when creating it. We will not repeat these instructions in subsequent labs.
-
The pilot should add the navigator as a collaborator on github. To do this navigate to the git repo you just created. Choose the settings tab. Then click on the ‘Collaborators and teams’ option on the left. Scroll all the way down and add the navigator’s github account. Then press on the ‘Add collaborator’ button. Now you and the navigator share the ownership of your git repo. You won’t work with your new repo until the end of the lab.
Step 2: Clone the repo in the pilot’s account and get the starter code
- On the terminal, change to your cs16 directory:
cd ~/cs16
- Using the web-browser, navigate to your newly created repo on github. Find the address of your git repo. Click on the green “clone or download button”. If your git repo was named lab02_alily_jgaucho, then the git address should something like: “git@github.com:ucsb-cs16-s18-mirza/lab02_alily_jgaucho.git”. Now clone your repo into your csil account by typing the following on the terminal, replacing the last argument with the address of your git repo
git clone git@github.com:ucsb-cs16-s18-mirza/lab02_alily_jgaucho.git
- Type ls to see your new git repo directory and change into that directory
cd lab02_alily_jgaucho
- Copy the starter code by typing the following command:
cp /cs/faculty/dimirza/cs16/labs/lab02/* ./
You should see the following files:
$ls
backslash.cpp README.md starC.cpp starL.cpp starT.cpp starZ.cpp
Step 3: Using the git command line tools to save the first version of your code
Its now time to use the git-command line tools to perform version control for the files in your git repo.  The above commands save a snapshot of your code on github. To check that this was done sucessfully open a web-browser and navigate to your repo on github. Then check to see that the starter code appears in your repo.
 All the previous versions will be available to you as well and you have the option of reverting to older versions (We will see how in later labs). As you go through the rest of this lab you will essentially need to use these commands to keep track of the different versions of your code.
Congratulations on integrating git into your workflow! Now proceed to the programming part of this assignment.
What we’ll be doing in this lab: ASCII Art
There was a time when laser printers either hadn’t been invented yet, or were not yet widely available. Thus, the only kind of printer most folks had access to was something called a "line printer", which printed only from left to right, top to bottom, and could only print the kinds of characters you find on a typewriter keyboard.
So, you might find folks making pictures like this one, found at http://chris.com/ascii/
.ze$$e. .ed$$$eee.. .$$$$$$$P"" z$$$$$$$$$$$$$$$$$ee$$$$$$" .d$$$$$$$$$$$$$$$$$$$$$$$$$" .$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$e.. .$$****""""***$$$$$$$$$$$$$$$$$$$$$$$$$$$be. ""**$$$$$$$$$$$$$$$$$$$$$$$L z$$$$$$$$$$$$$$$$$$$$$$$$$ .$$$$$$$$P**$$$$$$$$$$$$$$$$ d$$$$$$$" 4$$$$$ z$$$$$$$$$ $$$P" d$$$$$$$$$F $P" $$$$$$$$$$F *$$$$$$$$" "***"" Gilo94'
For now, we’ll be keeping things much simpler: we are going to do some very simple ASCII art of letters, numbers and symbols, in order to practice with if/else and for loops.
The first few exercises will be very simple, but they get progressively more challenging.
An example for you to follow: starL
As an example, we will write a C++ function that returns a C++ string that when printed to cout, makes the shape of prints the letter L with stars, at any width or height, provided both width and height are >= 2
If either the parameter width or height is less than 2, the function returns an empty string.
The function will have the following function prototype:
string starL(int width, int height);
-
As a reminder, a function prototype is the first line of the function definition (the header) followed by a semicolon instead of the function body—it is used to introduce the function to the compiler, in case the function definition isn’t coming until later.
-
You can read more about function prototypes here: C++: function prototypes
The following table shows various calls to this function, along with what the string returned looks like when printed using cout << starL(w,h);
The rule is that the L should have width at least 2, and height at least 2, otherwise the result is an empty string, and printing an empty string results in no output.
So, this is a fairly easy function to write. This will do the job, and is provided for you as an example of how functions like this should be written.
To test whether this function works, we can write a simple main that takes the command line arguments, converts them to integers with stoi, and then passes those to the function:
What you’ll be doing
What you’ll be doing in this lab is writing three similar functions: startT, starC and starZ.
Sample values returned from starT
Sample values returned from starC
starC renders the letters C, but requires a minimum width of 2, and a minimum height of 3. Otherwise it returns an empty string.
Sample values returned from starZ
starZ renders the letters Z, but requires a minimum width of 3. It only takes one parameter, because the height and width are always assumed to be equal.
Step by Step Instructions
Step 1: Practicing with the starL program
First compile the starL.cpp file that you have in this week’s directory with the option (-std=c++11 ) as per the following command:
g++ -std=c++11 -o starL starL.cpp
Run the program with a few command line parameters. You’ll notice something special happens when you pass in the command line parameters -1 -1.
./starL 3 4 ./starL 4 3 ./starL ./starL 2 1 ./starL -1 -1
With the command line parameters -1 -1, the program runs a set of tests on itself to make sure that the function starL inside the program is functioning correctly. So, you should be able to get some feedback on whether your code is correct before you even send it to gradescope. The code uses stoi to convert the argv[1] and argv[2] to integer values, and compare against -1.
Look over the code and try to understand how it works. When you feel ready, move on to the next step, and try tackling the starT.cpp, starC.cpp and starZ.cpp programs.
Step 2: Writing the starT program
Your job now is to start edit the starT.cpp program, which has a function inside of it that is a “stub”. That function does NOT produce the correct output—it always just returns the string “stub”. You need to replace that code with a proper implementation of starT. You can use the implementation of starL in the starL.cpp file as a model.
Compile your starT.cpp to the execuatable star. Suppose we want your program to draw a T with width 3 and height 2, we will run your starT executable as follows:
$./starT 3 2
In general the parameters to the startT program are width, followed by height. You should take this into consideration when writing your main function. To write the starT() function refer back to the description of starT earlier in this lab. You can also run the program with arguments of -1 -1 to run the internal tests and see whether your implementation is correct.
When you think you have a correct implementation, try submitting to the gradescope system. You can submit just your starT.cpp program to see how far along you’ve gotten.
Note that this will show failures for starC.cpp
and starZ.cpp
, which are files that you’ll be working on at a later step.
You could also just submit the “stubs” for those—though those will fail some or all of the tests.
Either way, for now, concentrate only on the test failures that pertain to starT.cpp and try to address any problems you encounter. If you fix these NOW before moving on to starC.cpp and/or starZ.cpp, you will likely have better success, because what you learn from fixing your mistakes will help you get those other parts solved more quickly and easily.
Some rules to keep in mind for the starT function:
- EVERY line of your T should have exactly the same number of characters, and should end in a newline—remember to pad out each line with spaces.
- Return a string that represents the letter T with the correct width and height, but only if height >=2, and width is an odd number >=3
- if the height and width values are not valid, return an empty string
Hints: recall that:
- the
%
operator can be used to test where a number is odd or even - the
&&
operator means “and” - the
||
operator means “or” - the opposite of >= is <, not <=
Also, for starT.cpp:
- If there are not exactly two command line args after the program name (one for width and one for height), print a usage message:
Usage: ./starT width height
- If the height and width are both -1, then invoke the internal tests. Don’t change those. If you do, then you may lose points.
Save the new version of your code with the starT implementation by typing out the following commands:
git add starT.cpp
git commit -m "Implemented starT()"
git push origin master
Step 3: Writing the starC program
Next, write the starC program. Follow the same basic procedure as for the starT.cpp program.
To get started, look at the table near the top of this lab that shows correct output for the starC program, as well as looking at the test cases in the runTests() function of the starC.cpp file in your directory.
Note that you’ll need to add some code to the main, but this time the rules are different. The minimum width is 2, and the minimum height is 3—everything else returns a null string (except for the values -1 for width and -1 for height—when passed in combination, the tests should be run.)
When:
- You can run your code with:
./starC -1 -1
and all the tests pass - You can run your code on values such as
./starC 4 5
and./starC 5 4
and see the same output as what is shown in the table, AND - When typing in a command line that doesn’t have exactly two arguments after
./starC
produces the correct error message
then, you are ready to try testing your code on gradescope.
Note that failures for starZ.cpp
may still show up, but we need not be concerned about those yet.
Concentrate only on the test failures that pertain to starC.cpp and starT.cpp and try to address any problems you encounter. Once all of those pass, move on to the starZ.cpp program:
Save the new version of your code with the starT and starC implementation by typing out the following commands:
git add starC.cpp
git commit -m "Implemented starC()"
git push origin master
Step 4: Writing the starZ program
For the starZ.cpp program, we have these rules:
- Take only one command line parameter: the width. The height will automatically be set equal to the width.
The starZ function follows these rules:
- return a string that draws the letter Z with the correct width and height, but only if width >=3
- return an empty string if the value passed in for width is not valid, print nothing at all.
Hints for the middle part of the Z:
- Take a look at the program backslash.cpp which is in your directory. Try compiling and running it. Look at the source code and see if there are any hints there.
- As you can see, it produces a backslash.cpp produces a backslash of a given width, as shown here. Look at the source code, and consider how you might turn backslash.c into forwardslash.c—in fact, that might be a good warm-up exercise for making the starZ.c program. Note that the backslash.cpp program does not contain an internal test harness.
- Note that the backslash.cpp program uses several “helper functions”. You might find that to be a useful technique in writing your own code. You may introduce whatever helper functions would be useful to you.
-bash-4.1$ ./backslash
Usage: ./backslash width
-bash-4.1$ ./backslash 3
*
*
*
-bash-4.1$ ./backslash 5
*
*
*
*
*
-bash-4.1$ ./backslash 2
*
*
-bash-4.1$ ./backslash 4
*
*
*
*
-bash-4.1$
As with starC.cpp, you should add code to starZ.cpp so that you are able to invoke the internal tests by typing ./starZ -1
. Note that this time, there is only one parameter.
And, if there is not exactly one parameter, there should be an appropriate “usage” message that follows the pattern of the other programs—except that there is only a width parameter in this program.
When you have a version that can pass its internal tests, try submitting it along with your starT.cpp and starC.cpp to gradescope.
If there are errors reported, fix them.
When you have a clean build, you are nearly done with this lab.
Note: You MUST make one final submission that includes ALL of your files. For getting incremental feedback while working on the lab, it is fine to submit one at a time, but for GRADING purposes, your LAST submission (in time) must be a complete submission of EVERYTHING. In the ideal case (for you), that submission is completely “green”, i.e. all test cases pass, and you have a perfect score (at least from the standpoint of the points you are awarded for passing the test cases.)
Make sure you add your pair partner as a collaborator (this should show up on the right side of your screen on gradescope after you submit your files).
If there are parts you can’t figure out, be sure to submit all of your files anyway to maximize the number of points you receive based on the parts that ‘'’are’’’ working.
Make sure you do a final git add .., git commit … and git push .. to make sure the latest version of your code is available on github.
Evaluation and Grading
Correctness
- (100 pts) 15 tests, 5-10 points each, executed by the gradescope system
End of lab check off points:
-
(10 pts) Correct creation of the lab02 github repo in our class organization following the naming conventions provided in the lab. Adding your partner as collaborator and partner accepting the invitation. Both partners joining the same group on gradescope.
-
(10 pts) All three programs have good programming style, including proper use of indentation, reasonable choices for variable names, readable code, reasonable use of whitespace, and other good programming practices. You must have good header comments as illustrated in the coding examples done in class. First line should be the name of your file, followed by date of creation, author and a brief description of the program. You must use curly braces in the body of all control structures (if-else, for and while) even if they contain a single statement. You should not mix tabs and spaces when indenting your code


[gecode-users] Configure fails on Gentoo Linux
Mikael Zayenz Lagerkvist
zayenz at gmail.com
Tue Sep 16 16:05:56 CEST 2008
On Tue, Sep 16, 2008 at 3:56 PM, Vasilij Savin
<Vasilij.Savin.8691 at student.uu.se> wrote:
> I have finally managed to get past java dependency hell. :)
Great.
> Some points to consider if default way fails as I had it in Gentoo.
>
> if JAVAC defined as : JAVAC = javac then
> redefine _cur: _cur = <JAVA_HOME>, where your JVM resides
> define $_JTOPDIR: $_JTOPDIR = $_cur
> commment out path construction for $_JTOPDIR
>
> It is sort of hardcoding hack, but it seems to work.
It might be a good idea to add a way of directly specifying the java
paths for odd architectures. Something for us to think about.
> Now there is another problem I am tackling now. I have installed the Gecode
> all by default. But now pkg-config fails:
>
> checking for GECODE... configure: error:
> The pkg-config configuration files for Gecode 2.2.0 were not found.
>
> Please make sure that Gecode is installed, and that the directory
> <prefix>/lib/pkgconfig is on the default path for pkg-config.
> Otherwise, extend the PKG_CONFIG_PATH environment variable accordingly.
>
> I have checked both gecode and gecode/j installing instructions and there is
> no mentioning how this should be done. I am going to try to follow the given
> instructions and report the results.
This is really as simple as following the instructions that configure
spits out: add <prefix>/lib/pkgconfig to PKG_CONFIG_PATH, er extend
the default paths for pkg-config.
Cheers,
Mikael
--
Mikael Zayenz Lagerkvist, http://www.ict.kth.se/~zayenz/
More information about the gecode-users
mailing list


 Maybe you'd like to add one?
{% endif %} {% if obj.description and obj.image %}{% else %}This track has no video. Maybe you'd like to add one? Send a message to Abe.Cede via Socialclub with a video URL.
{% endif %} {% endif %}This track has no video. Maybe you'd like to add one? Send a message to Abe.Cede via Socialclub with a video URL.
{% endif %} {% endif %}


Consider the following abstract syntax tree:
Program | FnExp / \ p,q,r PrimAppExp | * / \ VarExp PrimAppExp | | p + / \ VarExp VarExp | | q r
Which one of the following SLang 1 expressions does it represent?
fn(p,q,r)=>*(p,+(q,r))
fn(p,q,r)=>+(p,*(q,r))
(fn(p,q,r)=>*(p,+(q,r)))
(fn(p,q,r)=>+(p,*(q,r)))
Review the differences between concrete syntax and abstract syntax.
Where are parentheses used in SLang 1?


@main("Face") {
Info on Faces
Colour: N4
Overall Rating: 4.2 / 5
Price: €22.00
Description:
An oil-controlling formula that offers a natural matte finish with medium to
full coverage.
A modern foundation that combines a natural matte finish and medium to full
buildable coverage with broad spectrum UVA/UVB SPF 15/PA++ protection. Applies,
builds and blends easily and evenly. Comfortable and long-wearing, it helps
minimize the appearance of pores and imperfections, giving skin a smoother, more
flawless look and finish.


No jobs found! Do you want to add one?
0">
Click at to review the details of a job!
{{selectedJob.title}}
{{selectedJob.location }}
Job type: {{selectedJob?.jobType.toString().replace('_', ' ')}}
Experience level: {{selectedJob?.experienceLevel.toString().replace('_', ' ')}}
Uploaded: {{selectedJob?.date}}
Tags:
{{tag?.tag.replace('_', ' ')}}
{{getTotalViews(this.jobViews.get(selectedJob?.id))}} view
{{getTotalViews(this.jobViews.get(selectedJob?.id))}} views
{{selectedJob?.info}}


Wstęp do języka PHP.
Brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex! Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy veldt fox. Bright vixens jump; dozy fowl quack. Quick wafting zephyrs vex bold Jim.
Jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex! Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy veldt fox. Bright vixens jump; dozy fowl quack.
assertSame(0, count($stack));
array_push($stack, 'foo');
$this->assertSame('foo', $stack[count($stack)-1]);
$this->assertSame(1, count($stack));
$this->assertSame('foo', array_pop($stack));
$this->assertSame(0, count($stack));
}
}
?>


Okay, so my roomie cum best friend Mohit Kherwa wanted to build a bot which would crash land into some unknown location on Mars but still find its way to the human base station. Since we were not getting a bot to Mars anytime soon, I suggested we build one that finds its way from our room to the next. And so we did. With help from wingies Shikhar Kothari and Harsh Meena.
What went inside
We fixed IR sensors on the front and to the left. To measure the speed or the distance covered, we made white patches on the inside surface of the black wheel. Around 10 of them. There was an IR sensor pointed at the wheel. Essentially, we were receiving a square wave as input from the sensor. Measure the frequency, and voila, you have the bot’s speed! (We learnt later that this is the principle behind a tachometer.) The bot had three wheels, one freely rotating in the front(castor wheel), and two motors (standard 2W) with the rear two, for differential mechanism. And an Arduino, motor driver shield and a 12V battery. Well, so much for the hardware.
The Algorithm
The bot’s initial position was set to origin and thus it marked the coordinate system. Y axis was in the forward direction, and x to the right. We planned to put up an LCD display and buttons on the bot to enter the final coordinates. The coordinates of the destination was hard coded into the bot during testing. They were stored in variables x and y.
Here’s the logic which we adopted in our arduino code:
-
If y<0 Turn 180 degree. Change the sign of x and y. (This step is to make sure that the final position is always ahead of the bot.) Else Go to step 2.
- Move forward and decrease y accordingly until (y is decreased because the destination
is getting closer)
- y=0;
if x=0 as well, Terminate the program. The bot has reached its destination. Else go to step 5. - There is some obstacle ahead. (i.e, Front IR sensor goes off)
Go to Step 3.
- y=0;
-
Turn Right. Move forward and decrease x accordingly as long as the left IR sensor gives a high. Go to Step 4.
-
Turn Left. Go to Step 2.
- If x<0, turn left, set y= -x and x=0.
Go to step 2.
(The bot just rotated the coordinate system by 90 degree and started all over again)
If x>0, turn right, set y= x and x=0.
Go to step 2.
You can find the code here.
Sounds straightforward, but…
The first real difficulty was the wheels slipping on the ground. This was sorted out by using rubberised wheels and bringing down the RPM of the motors by lowering the duty cycle of the PWM output to the motors.
The second more serious difficulty was that due to manufacturing tolerances, the motors were not identical. Even when the same PWM signal was given to both motors, one tended to go slightly faster and this sometimes led to large cumulative error. We only had an IR sensor on one wheel, so only that wheel’s angular velocity could be measured.
We tried to correct this error calibrating the duty cycle of the PWM signal to the motors but unfortunately this calibration was dependent on battery voltage- when the battery voltage dropped by half a volt, the bot had to be recalibrated. Then we tried adding an IR sensor to the other wheel and add a feedback system for self-calibration, but the Arduino was not fast enough to collect that much data and process it- angular frequencies of the wheels were wrongly calculated and the bot went haywire. The proposed workaround was to use stepper motors, but then we never got around to implementing it- this was done in the few days following the endsems and all of us had to go home by that time.
The error was never great enough to defeat the purpose of the bot - the bot usually reached its target with a tolerance of a few centimeters. The error was noticeable only when the battery was heavily drained.


Active*
(
per 100k)
Deaths
(
per 100k)
Recovered*
(
per 100k)
*Active and recovered totals are estimates based on the CDC formula documented
here
. See
source code
for more information.
Viral
Explore the spread of COVID-19 in the United States by county
Active cases
Active cases per 100k
Density of cases
Doubling time
New cases
Total deaths
Deaths per 100k
Deaths as % of cases
Total cases per 100k
Explore date range
*Active and recovered totals are estimates based on the CDC formula documented
here
.
Labor Day
Thanksgiving
Christmas
Sturgis
One month ago
Two weeks ago


Read Me
The App that will read for you!
Read my document from :
nothing here yet
Made By Team Better Than Tunnel Snakes
ConUHacks II 2017


pyGM: Graphical Models¶
-
class
pyGM.
GraphModel
(factorList=None, copy=True, isLog=False)[source]¶ A basic graphical model class; represents a collection of factors.
Example:
>>> flist = readUai('myfile.uai') # read a list of factors from a UAI format file >>> model = GraphModel(flist) # makes a copy of the factors for manipulation
The model may be stored in an exponential, product of factors form: f(X) = prod_r f_r(X_r), or in a log-probability, sum of factors form: heta(X) = sum_r heta_r(X_r).
Various accessor functions enable finding factors that depend on one or more variables, variables that share one or more factors (their Markov blanket), manipulations to the graph (such as eliminating one or more variables), and visualization (through networkx).
-
addFactors
(flist, copy=True)[source]¶ Add a list of factors to the model; factors are copied locally unless copy = False
-
condition
(evidence)[source]¶ Condition (clamp) the graphical model on a partial configuration (dict) {Xi:xi, Xj:xj, …}
-
condition2
(vs, xs)[source]¶ Condition (clamp) the graphical model on the partial configuration vs=xs (may be lists or tuples)
-
connectedComponents
()[source]¶ Find the connected components of the model’s Markov graph. Returns a list of sets of variables.
-
drawBayesNet
(**kwargs)[source]¶ Draw a Bayesian Network (directed acyclic graph) using networkx function calls
- Args:
**kwargs
: remaining keyword arguments passed to networkx.draw()
Example: >>> model.drawBayesNet( labels={0:‘0’, … } ) # keyword args passed to networkx.draw()
-
drawFactorGraph
(var_color='w', factor_color=(0.2, 0.2, 0.8), **kwargs)[source]¶ Draw a factorgraph using networkx function calls
- Args:
- var_color (str, tuple): networkx color descriptor for drawing variable nodes
factor_color (str, tuple): networkx color for drawing factor nodes
var_labels (dict): variable id to label string for variable nodes
factor_labels (dict): factor id to label string for factor nodes
**kwargs
: remaining keyword arguments passed to networkx.draw()
Example: >>> model.drawFactorGraph( var_labels={0:‘0’, … } ) # keyword args passed to networkx.draw()
-
drawLimid
(C, D, U, **kwargs)[source]¶ Draw a limited-memory influence diagram (limid) using networkx
- Args:
**kwargs
: remaining keyword arguments passed to networkx.draw()
Example: >>> model.drawLimid(C,D,U, var_labels={0:‘0’, … } ) # keyword args passed to networkx.draw()
-
drawMarkovGraph
(**kwargs)[source]¶ Draw a Markov random field using networkx function calls
- Args:
**kwargs
: remaining keyword arguments passed to networkx.draw()
Example: >>> model.drawMarkovGraph( labels={0:‘0’, … } ) # keyword args passed to networkx.draw()
-
eliminate
(elimVars, elimOp)[source]¶ Eliminate (remove) a set of variables from the model
- Args:
- elimVars (iterable): list of variables to eliminate (in order of elimination) elimOp (str or lambda-fn): function to eliminate variable v from factor F; ‘max’, ‘min’, ‘sum’, ‘lse’, or a user-defined custom function, e.g., ‘lambda F,v: …’
-
isBN
(tol=1e-06)[source]¶ Check whether the graphical model is a valid Bayes net (one CPT per variable)
-
logValue
(x, subset=None)[source]¶ Evaluate log F(x) = sum_r log f_r(x_r) for some (full) configuration x. If optional subset != None, uses only the factors in the Markov blanket of subset.
-
makeCanonical
()[source]¶ Add/merge factors to make a canonical factor graph: singleton factors plus maximal cliques
-
makeMinimal
()[source]¶ Merge factors to make a minimal factor graph: retain only factors over maximal cliques
-
markovBlanket
(v)[source]¶ Get the Markov blanket of variable v (all variables involved in a factor with v)
-
property
nfactors
¶ The number of factors in the model
-
property
nvar
¶ The number of variables ( = largest variable id) in the model
-
nxMarkovGraph
(all_vars=False)[source]¶ Get networkx Graph object of the Markov graph of the model
Example: >>> G = nxMarkovGraph(model) >>> nx.draw(G)
-
removeFactors
(flist)[source]¶ Remove a list of factors from the model
>>> model.removeFactors(model.factorsWith([0])) # remove all factors involving X0
-
toExp
()[source]¶ Convert internal factors to exp form (product of probabilities) if not. May use ‘isLog’ to check.
-
value
(x, subset=None)[source]¶ Evaluate F(x) = prod_r f_r(x_r) for some (full) configuration x. If optional subset != None, uses only the factors in the Markov blanket of subset.
-
property
vars
¶ List of variables in the graphical model; equals model.X
-


Async parsing
| The parallel parser is also an async parser. But for the most users the parallel parser adds too much overhead. |
If you want to write parsers to run in Javascript environments, then async operations are the norm. The async
parser is a version of the parser were you can return core.async
channels from the readers instead of raw
values. This allows for the creation of parsers that do network requests or any other async operation.
The async parser is still semantically a serial parser, and it will have the same flow characteristics
of the regular parser (the order or resolution is preserved).
To write an async parser we use the p/async-parser
function. Here is an example:
(ns com.wsscode.pathom.book.async.intro
(:require [com.wsscode.pathom.core :as p]
[cljs.core.async :as async :refer [go <!]]
[com.wsscode.pathom.trace :as pt]
[com.wsscode.pathom.connect :as pc]))
(pc/defresolver async-info [_ _]
{::pc/output [:async-info]}
(go
(<! (async/timeout (+ 100 (rand-int 1000))))
{:async-info "From async"}))
(pc/defresolver foo [_ _]
{::pc/output [:foo]}
{:foo "Regular"})
(def register [async-info foo])
(def parser
(p/async-parser {::p/env {::p/reader [p/map-reader
pc/async-reader2]}
::p/plugins [(pc/connect-plugin {::pc/register register})
pt/trace-plugin]}))
Try the example:
The core plugins work normally with the async parser, so error and profiling will work as expected.
Error propagation
When an exception occurs inside a core.async
channel the error is triggered as part of the channel exception handler.
That doesn’t compose very well and for the parser it’s better if we have something more like the async/await
pattern available within the JS environments. Pathom provides some macros to facilitate this; instead of using
go
and <!
, use the provided go-catch
and <?
macros, as shown in the following example:
(ns com.wsscode.pathom.book.async.error-propagation
(:require [cljs.core.async :as async]
[com.wsscode.common.async-cljs :refer [go-catch <?]]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom.core :as p]
[com.wsscode.pathom.trace :as pt]))
(pc/defresolver async-info [_ _]
{::pc/output [:async-info]}
(go-catch
(<? (async/timeout (+ 100 (rand-int 1000))))
{:async-info "From async"}))
(pc/defresolver async-error [_ _]
{::pc/output [:async-error]}
; go catch will catch any exception and return then as the channel value
(go-catch
; <? macro will re-throw any exception that get read from the channel
(<? (async/timeout (+ 100 (rand-int 1000))))
(throw (ex-info "Error!!" {}))))
(pc/defresolver foo [_ _]
{::pc/output [:foo]}
{:foo "Regular"})
(def register [async-info async-error foo])
(def parser
(p/async-parser {::p/env {::p/reader [p/map-reader
pc/async-reader2]}
::p/plugins [(pc/connect-plugin {::pc/register register})
p/error-handler-plugin
pt/trace-plugin]}))
Use com.wsscode.common.async-clj
for Clojure and com.wsscode.common.async-cljs
for ClojureScript. If you are writing a
cljc file, use the following:
[#?(:clj com.wsscode.common.async-clj
:cljs com.wsscode.common.async-cljs)
:refer [go-catch <?]]
JS Promises
In JS world most of the current async responses come as promises, you can use the <!p
macro to read from promises
inside the go
blocks as if they were channels. Example:
(ns com.wsscode.pathom.book.async.js-promises
(:require [com.wsscode.common.async-cljs :refer [go-catch <!p]]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom.core :as p]
[goog.object :as gobj]))
(pc/defresolver random-dog [env {:keys []}]
{::pc/output [:dog.ceo/random-dog-url]}
(go-catch
{:dog.ceo/random-dog-url
(-> (js/fetch "https://dog.ceo/api/breeds/image/random") <!p
(.json) <!p
(gobj/get "message"))}))
(def parser
(p/parallel-parser
{::p/env {::p/reader [p/map-reader
pc/parallel-reader
pc/open-ident-reader
p/env-placeholder-reader]
::p/placeholder-prefixes #{">"}}
::p/plugins [(pc/connect-plugin {::pc/register [random-dog]})
p/error-handler-plugin
p/trace-plugin]}))


{% extends sub_base_template %} {%- block subtitle %}Thank You - {{ super() }}{% endblock %} {%- block content %} {{- super() }}
{{ contestant.display_name }} thanks you for your contribution.
Now show the world why Boulder is #1 in community driven innovation!
SHARE ON


Serbia’s president hospitalized with cardiovascular problems
BELGRADE, Serbia (AP) - The office of Serbia’s president says he has been hospitalized with cardiovascular problems.
The statement released Saturday says that Aleksandar Vucic was admitted to the military hospital in Belgrade, the capital, on Friday afternoon.
No other details were immediately available. Serbian media have reported in the past that the 49-year-old Vucic suffers from high blood pressure.
TOP STORIES
Franklin Graham calls on nation to pray for Trump as impeachment effort gains speed
Nancy Pelosi goes for slam dunk -- and crashes to court
Skeptics chuckle as climate activist Greta Thunberg sets sail for Europe on 'plastic yacht'
A former extreme nationalist during the 1990s’ war in the former Yugoslavia, Vucic and his Serbian Progressive Party came to power seven years ago promising to take Serbia into the European Union.
The populist leader has since faced accusations of curbing media freedoms and democracy. Vucic’s government has strengthened Serbia’s close relations with traditional Slavic ally Russia.
Sign up for Daily Newsletters
Copyright © 2019 The Washington Times, LLC.
Please read our comment policy before commenting.


Dewgong
Pokemon of water and ice type from the 1st generation of Pokemon, at number 87 in the national Pokedex. Evolves from Seel.


E-Commerce
The following sections suggests features that can benefit e-commerce solutions, e.g. web stores, that integrates with Bring's APIs. Each section represents a part of a suggested order process and contains a list of suggested features for that step in the process.
Selecting a shipping method Shipping Guide API
| Feature | Suggested web store implementation |
|---|---|
| Selection of a shipping method | Display minimum 2 available shipping methods and support manual selection of a shipping method |
| Shipping method titles | Display shipping method titles defined in the response from Bring Shipping Guide API or the overridden titles |
| Sort order of shipping methods | Display shipping methods in the exact order defined in the response from Bring Shipping Guide API or in an overridden order |
| Shipping method language | Provide Bring Shipping Guide API queries with the language displayed to the end user to ensure that the description of the methods are in the preferred language |
| Estimated time of delivery | Display estimated time of delivery for shipment methods |
| Posten / Bring logo | Display Posten / Bring logo with the shipping methods in accordance with guidelines by Posten/Bring |
| Order weight | Include total weight of order in grams in Bring Shipping Guide API queries |
| Order dimensions or volume | Include dimensions or volume of order in Bring Shipping Guide API queries |
| Adjust Bring Shipping Guide API prices | Display adjusted prices |
| Rounding of prices | Display rounded prices for shipping methods |
| Relative price | Display value added service charges separately at selection. Shipping method prices are relative to the currently selected shipping method's price |
| Coupon code for discounted or free shipment | Display input field for coupon code and adjust prices according to the code |
| Support free shipment based on criteria | Adjust price if some criteria are met |
| Hide shipping method(s) based on total price | Hide shipping method(s) if the total price of items exceeds given max price |
| eVarsling | Include eVarsling data when requesting shipping methods from Bring Shipping Guide API |
| Parcel delivered at post office | Include whether a parcel is delivered at the post office or not when quering Bring Shipping Guide API for prices |
| Support item dimensions | Include item dimensions (if available) when quering Bring Shipping Guide API for prices |
Selecting a pickup point Pickup Point API
Freedom of choice is essential when shopping online and that is also true when it comes to choosing your favorite pickup point. The Pickup Point API let’s your customers decide which pickup point they prefer; for example the closest one to their work place, kindergarten or perhaps mother in law. Via the API you can also display, in addition to the address, the opening hours of the pickup point.| Feature | Suggested web store implementation |
|---|---|
| Selection of a delivery point | Display available delivery points and support manual selection of a delivery point |
| Selection of a delivery point on a map | Display available delivery points on a map and support manual selection of a delivery point |
| Address/postal code for pickup point queries | Ensure address specifications in pickup point queries (country code and postal and/or address) |
Booking details Booking API
| Feature | Suggested web store implementation |
|---|---|
| Delivery option | Customer can choose delivery option and price is updated accordingly |
| Message for recipient | Support free text information for receiver in transport booking |
| Instructions for driver | Support free text instructions for the driver |
| Cash on delivery | Support display of "Cash on delivery" as an option for supported shipping methods |
| Customs declaration | Display input field for the end user or provide customs information when performing the booking throught Bring Booking API |
| Order weight | Include total weight of order in grams when creating a booking through Bring Booking API |
| Order dimensions or volume | Include dimensions or volume when creating a booking through Bring Booking API |
| Tracking link | Display a shipment tracking link returned by the Bring Booking API for the customer on the order confirmation (page and/or email) |
| Expected delivery time | Display expected delivery time on the receipt |
Label management Booking API
The Booking API sends all necessary EDI messages and a PDF label is returned in responses. Having a label management system makes it possible for the web shops to print it's own labels and attach it to the shipments.| Feature | Suggested web store implementation |
|---|---|
| Label list | Support handling of label URLs returned by the Bring Booking API for local printing |
Tracking Tracking API
| Feature | Suggested web store implementation |
|---|---|
| Manual tracking | Enable manual tracking for the customer by displaying a search field |
Configuration Booking API Shipping Guide API
| Feature | Suggested web store implementation |
|---|---|
| Configurable API key | Make API key configurable and include it in the requests to Shipping Guide API and Booking API to enable agreement prices, prices for value added services, lead time and coverage |
| Limit receiver countries | Limit countries available for shipments (receiver country) |
| Supported sender countries | Sender countries available for use by the Bring APIs are supported |
Error handling and validation Booking API Pickup Point API Shipping Guide API Postal Code API
Well-written applications include error-handling code that allows them to recover gracefully from unexpected errors. The order should still be intact, even if the Shipping Guide returns an error or a timeout occurs.| Feature | Suggested web store implementation |
|---|---|
| Shipping Guide errors | Log error data and prevent display of error message to end users. Bring shipping methods should not be displayed to the customer when an error occurs. |
| Booking errors | Log error data and prevent display of error message to end users. |
| Tracking errors | Log error data and prevent display of error message to end users. |
| Verify postal code | Verify receiver's postal code by using Postal Code API |


Movie Title:
showing
Ticket Quantity:
Total Price: $
Please resubmit the form to make any changes to your order.
Confirmation number:
Display your confirmation number when you arrive at the theatre.


The Bluemix Backend for Frontend template demonstrates how to create and deploy a backend to support integration for an omnichannel application on the IBM Bluemix Cloud Platform. The project has the the ability to browse a list of products and supports the viewing of images for each item in the product list using REST API endpoints.
A "Backend for Frontend" application defines different backend services and capaiblities for different frontend clients. Using this architecture, developers can expose custom APIs from their backend to deliver client solutions with a scalable Compute infrastructure using the Bluemix platform.
This lightweight Node backend uses Bluemix Mobile services, Cloudant NoSQL DB, Object Storage, and a LoopBack runtime to expose a Swagger definition through API Connect.
The following sections explain what each of these services do, how they are implemented in this backend, and where to get more detailed information about the services from the official documentation.
The LoopBack framework is a set of Node.js modules that you can use independently or together to quickly build REST APIs.
A LoopBack application interacts with datasources through the LoopBack model API, available locally within Node.js, remotely over REST, and via native client APIs for iOS, Android, and HTML5. Using these APIs, apps can query databases, store data, upload files, send emails, create push notifications, register users, and perform other actions provided by datasources and services.
In this backend, we use LoopBack for a single point of REST integration for our Cloudant NoSQL DB datasource and images stored on Object Storage.
Click the View API Reference button to browse the API for the Bluemix Backend for Frontend template.
For more information about LoopBack, see the official
documentation below.
Cloudant NoSQL DB provides access to a fully managed NoSQL JSON data layer that's always on. This service is compatible with CouchDB,
and accessible through a simple to use HTTP interface for mobile and web application models.
In this backend, we provision a Cloudant NoSQL DB service instance and supply that with data from a
products.json file which contains a list of products for the Backend for Frontend template.
If you open the Cloudant NoSQL DB service instance, you can browse the data inside the template. Each document contains information about the price,
rating, description, etc. for each article of clothing that is available from the store.
For more information about Cloudant NoSQL DB, see the official documentation below.
Object Storage provides an unstructured cloud data store to build and deliver cloud applications and services with lowered cost, reliability, and speed to market.
Bluemix developers and users can access and store unstructured data content and can interactively compose and connect to applications and services.
The Object Storage service also provides programmatic access via API, SDKs and a consumable UI for object management.
In this backend, we provision a Object Storage service instance and supply that with data from a
clothes folder which contains the images for the template.
If you open the Object Storage service instance, you can browse the data inside the template. The clothes container contains the images
of each item available.
For more information about Object Storage, see the official documentation below.
Finely tune mobile apps with operational analytics from real time performance and data usage. Ensure communications with your backend systems are secure.
Let your app users to log in with custom accounts or existing social accounts.
In this backend, we protect an endpoint that is only accessible after authentication with the Mobile Client Access service from the mobile application.
For more information about Mobile Client Access, see the official documentation below.
The Push Notification service provides a unified push service to send real-time notifications to mobile and web applications. The service provides the ability to personalize and send notifications to a segment of users, single user or broadcast to all users.
In this backend, we provision a Push Notifications service instance for sending push notifications to a mobile or web app.
For more information about Push Notifications, see the official documentation below.
Mobile Analytics for Bluemix provides developers, IT administrators, and business stakeholders insight into how their mobile app is performing and how it is being used.
Monitor performance and usage of all your applications from your desktop or tablet. Quickly identify trends and anomalies, drill down to resolve issues and trigger alerts when key
metrics cross critical thresholds.
In this backend, we use Mobile Analytics to view device sessions, monitor crashes, and create custom charts.
For more information about Mobile Analytics, see the official documentation below.


--- layout: post title: Blog Post #3 ---
Write a list of questions you'll need to find answers to for this to work
How do you design a successful maze?
How do you sent a player to a new html page?
How do you attach an image in html?
How do you randomize the pages?
How do you send a player back to the beginning?


What am I looking at? Covid-19 is caused by a virus called SARS-CoV-2. This virus uses a spike protein to enter host cells and infect the body. The spike protein is shown here to the right.
Gamma
How is the Gamma variant different? How is the Gamma variant different? The Gamma variant, also known as lineage P.1, is also of concern to public health because it is known to spread faster than earlier forms of the virus. The Gamma variant is structurally different from its wild type counterpart and, therefore, may differ in function. It has the following mutations located on the spike protein: L18F, T20N, P26S, D138Y, R190S, K417T, E484K, N501Y, D614G, H655Y, T1027I.
K417T- After mutation, the network plots clearly show that T417 loses contact with N370.
N501Y- The interaction network plots are the same before and after the mutation, although the protein structures indicate some missing π-stackings after mutation.
D614G- Similar to N501Y, D614G does not affect local interactions before and after the mutationr.
N501Y and D614G have the same network plots before and after the mutation, although there are some small changes, such as missing some π-stacking. The same interactions in plots indicate the mutation does not affect the local interactions, but it could still affect binding recognition and have an effect on the ACE2 receptor. Scroll down to learn more!
Mutations can affect ACE2-COVID complex formation
Protein loops are regions of proteins that do not have regular structure. As a result, loops are much more flexible, and they are important for many things, including receptor and antibody binding. The spike protein binds to ACE2 by creating interactions, notably hydrogen bonds, between residues on ACE2 and on the spike protein. Loss of these interactions leads to poorer binding, whereas gain of interactions leads to stronger binding. Many antibodies target specific residues, and mutations at these residues can decrease effectiveness of those antibodies.
In the gamma variant, two mutations (K417T and N501Y) could affect formation of the SARS-CoV-2 and ACE2 complex. The K417T mutation loses a hydrogen bond and the N501Y gains a hydrogen bond between ACE2 and the spike protein. It is difficult to say whether the combination of these mutations leads to increased or decreased binding affinity for ACE2. Further research should focus on these mutations and their effects on interactions, as the K417T mutant has been reported to reduce the effectiveness of some antibody concoctions. Additionally, the novel interaction produced by N501Y may lead to greater binding affinity to ACE2, which may increase entry efficiency of SARS-CoV-2 into cells and increase the risk of infection upon exposure.
For more info, check any of the following resources:
This Website and Content was created by a team at the SIP Codeathon. The members are Diya Dinesh, Alexa Salsbury, Katilin Abrantes, Anne-Sophie Fratzscher, and Wenyu Zeng.


Ruth 3:6
And she went down unto the floor, and did according to all that her mother in law bade her.


| plotdiff {gridGraphics} | R Documentation |
grid.echo()
Functions to generate a scene using the graphics package,
reproduce the scene using grid.echo()
, test whether the
two results are identical, and report on any differences.
plotdiff(expr, label, dev = "pdf", antialias = TRUE, density = 100, width = 7, height = 7) plotdiffInit() plotdiffResult(warn = FALSE)
expr |
An expression that draws something using the graphics package. |
label |
A character value that is used to label files generated during testing. |
dev |
The graphics device used for drawing and echoing. Currently can only be
either |
antialias |
A logical value indicating whether to perform antialiasing when converting from PDF to PNG. |
density |
A numeric value indicating the resolution (dpi) to use when converting from PDF to PNG. |
width, height |
Numeric values indicating the size of the device to test on. |
warn |
A logical value indicating whether non-identical output should produce a warning or an error. |
In default usage, plotdiff()
is used to generate two PDF
files, one using the original expression and the other from a call
to grid.echo()
. The PDF files are then converted to PNG
files and the PNG files are compared (using ImageMagick). If
there are any differences, the
comparison generates a further PNG file that shows the differences.
All files are currently generated in the current working directory.
Text messages are also generated by plotdiff()
whenever a
difference is found, but those messages are stored up rather than
printed immediately.
The plotdiffResult()
function prints out all messages
since the last call to plotdiffInit()
.
Standard usage involves calling plotdiffInit()
, followed by
one or more plotdiff()
calls, then finally a call to
plotdiffResult()
.
Examples of the usage of these functions are provided in the numerous
test scripts in the test-scripts
directory of the package.
All functions are run for their side effects.
In the case of plotdiff()
, the generation of PDF and PNG files
and the accumulation of differences about messages.
In the case of plotdiffResult()
, a print out of the accumulated
messages, plus possibly either an error or warning.
Paul Murrell
## Not run: plotdiff(expression(plot(1)), "plot") ## End(Not run)


Student
Lecturer
Administrator
Student
Enrolled Courses
Courses
Grades
Timetable
Logout
Admin
Student
Lecturer
Course
Enrollment
Logout
Lecturer
View Courses Taught
View Course Enrolment
Edit Grades
See Student Performance
Timetable
Logout