Coding Archives - Nightingale https://nightingale.becomingcelia.com I sang during the night in early June Mon, 15 Mar 2021 01:10:21 +0000 en-US hourly 1 https://wordpress.org/?v=5.8.13 Project SIAT – UI / UX Coding https://nightingale.becomingcelia.com/2020/10/project-siat-ui-ux-coding.html https://nightingale.becomingcelia.com/2020/10/project-siat-ui-ux-coding.html#respond Thu, 15 Oct 2020 13:23:00 +0000 https://nightingale.becomingcelia.com/?p=800 In the post I wrote a month ago, Project SIAT – Get Started, I wrote about how I finished designing the webpage. With the design in hand, I moved into the second stage of making the website (in a hurry), front-end coding. The design I put on the previous post was a high-fidelity interface made […]

The post Project SIAT – UI / UX Coding appeared first on Nightingale.

]]>
In the post I wrote a month ago, Project SIAT – Get Started, I wrote about how I finished designing the webpage. With the design in hand, I moved into the second stage of making the website (in a hurry), front-end coding.

The design I put on the previous post was a high-fidelity interface made with Sketch. It will look exactly the final website I create but it is merely a design, in other words, it is a combination of images, text and shapes, which I put together via dragging and dropping. In order to make it into a real website that visitors can visit with a browser and interact with, I will need to write codes that make up the website and try to make it look exactly like the design as best as I can.

Before I get started with the project, I knew how to write HTML, CSS and can play around with the basics of JavaScript. For the project, my teacher suggested that I should learn React because the JavaScript library is very popular right now. It is for frontend development, allowing websites to update without reloading the page and is fast, scalable and simple. I knew nothing about React so therefore I went through the lessons and tutorials on Codecademy.

Image from reactjs.org

The process of making this website has brought me uncountable knowledge and practices, much more than what I have expected. Within these, the most beneficial ones are:

  • Learning about the basics of React
  • Practicing frontend programming languages like HTML and CSS, making my website with them independently for the first time
  • Self help skills, how to solve a problem by getting help from online resources efficiently

Below, I will introduce some of my codes, which is also a reminder for myself in the future.

This is the final file structure of the project:

├── App.js
├── App.scss
├── DropDown.js
├── DropDown.scss
├── Navigation.js
├── Navigation.scss
├── articlePage
│   ├── Article.js
│   ├── Article.scss
│   ├── ArticleBlock.js
│   ├── ArticleBlock.scss
│   └── webCrawler.js
├── assets
│   └── images
│       ├── artwork.png
│       ├── bear-fullwidth.png
│       ├── bear.png
│       ├── bg-dark-green.png
│       ├── elephant-fullwidth.png
│       ├── elephant.png
│       ├── icon.png
│       ├── pangolin-fullwidth.png
│       ├── pangolin.png
│       ├── rhino-fullwidth.png
│       ├── rhino.png
│       ├── thumbnail.png
│       ├── tiger-fullwidth.png
│       └── tiger.png
├── homePage
│   ├── FullWidthSpecies.js
│   ├── FullWidthSpecies.scss
│   ├── Home.js
│   ├── Home.scss
│   ├── Species.js
│   └── Species.scss
├── index.css
├── index.js

Amongst these files, the most amazing and important file in my opinion, is App.js. It is in the root of the project directory and it role in the website is somewhat like the central nervous system in a body, connecting different body parts and pass signals between them. It doesn’t (shouldn’t) include any specific code about the details (like the text or color) on each webpage, but it shows the logic of rendering the pages, e.g.

In React, if two pages, let’s call them A and B, have large amount of codes that are similar, they do not need to be two separated HTML files. Instead, page A and page B can be using the same files and mark the parts where they are different. Therefore, when the user switches from page A to page B, only a small part of the webpage needs to be re-rendered instead of the entire file. For instance, the same navigation bar and footer is used no matter which page it is in the website, therefore App.js is written like so:

<Navigation />
{/* will always run no matter which page it is on */}
<Switch>
{/* the part that changes depending on the url */}
    ...
</Switch>
<footer className="text-light">
{/* like the navigation part, doesn't change */}
    ...
</footer>

Let’s zoom into the <Switch> component. It decides what to render based on the url. For the code below, the second <Route> component says that if the path is equal to “/”, then code inside the component “Home” will be rendered. The first <Route> component is more complicated. It receive props called speciesId from another webpage, and it passes these props as attributes into the “Article” component. After this, the “Article” component will render codes depending on the attributes.

<Switch>
    <Route
        path="/article/:speciesId"
        render={(props) => <Article {...props} />}
    />
    <Route path="/">
        <Home />
    </Route>
</Switch>

I found this very interesting when learning to write it because I have never learned about making dynamic pages before and I thought that when the user enters a url, the file inside the specific folder pointed by the url will be rendered. Now I found out that the position of the file with codes of the webpage isn’t restricted in any specific folder. Instead, it can be anywhere and as long as the Router points to it, it can be rendered (therefore it is possible to have two address in the webpage leading to the same file.

As a component that exist in all pages, the dropdown menu from the navigation bar is a fancy component. As introduced in the last post, it is inspired by the dropdown menu of the National Geographic website. It takes me (a JavaScript noob) three hours to code the dropdown animation and the mouseover effect of the menu.

The menu on the National Geographic website is amazing, it seems like a lot of things are moving in all directions at the same time. I was deeply impressed by the design, but I had no idea how to start coding my own. Therefore I began to do careful observations and inspected the elements on the page one by one.

After a while, I started to get how everything works. Basically, there is a huge layer that covers the whole page — a <div> element called “menu-backdrop” that is placed above the original webpage but beneath the contents shown in the menu. When the user click on the “Menu” text in the navigation bar, menu-backdrop moves down on its own and the animation continues for about 1 second.

All the other contents that are above the backdrop show up one by one, from the top to the bottom at the same time as the backdrop moves down. The way they show up isn’t just in a sudden, or fading in, but they are translating — moving out from a layer where they are hidden beneath into places where users can see them.

Now that I got the general idea of how things are supposed to work, I started my attempts to turn the idea into code with the knowledges that I already know. The embarrassing here that I realized not long after I finished testing and debugging my code was that I was interacting directly with DOM elements in the webpage, which shouldn’t really happen since I am coding in React and not JavaScript. This had made my teacher rather speechless. She thought of rewriting the huge block of JavaScript code into React with me but later told me to keep it as it was — it was just too time-consuming.

activate() {
    document.getElementsByClassName(
      "dropdown-main-container"
    )[0].style.display = "flex";
    var elem = document.getElementById("menu-backdrop");
    // elem is the backdrop
    var label = document.getElementsByClassName("species-label")[0];
    // label is the red text that says "Species--" according to the above video
    var button = document.getElementsByClassName("dropdown-button")[0];
    elem.style.transitionDelay = "0s";
    label.style.transitionDelay = "0s";
    elem.classList.add("active");
    label.classList.add("active");
    button.innerHTML =
      'Close <i class="fa fa-angle-double-up" aria-hidden="true"></i>';
    var num = document.getElementsByClassName("slider").length;
    for (var count = 0; count < num; count++) {
      var classname = "slider-text" + count.toString(10);
      var item = document.getElementsByClassName(classname)[0];
      item.style.marginTop = "5rem";
      item.style.animationName = "slide-up";
      item.style.animationDelay = (count * 120 + 300).toString(10) + "ms";
    }
}

Below is the part that I think is the strangest but at the same time the most amazing. I am not sure if people usually code like this, but I am using a FOR loop to go through “slider-text” elements one by one according to their classes, then adding corresponding and unique styles onto them. “animationDelay” is different for each slider-text element and I am calculating it in the last line of code below.

var num = document.getElementsByClassName("slider").length;
for (var count = 0; count < num; count++) {
      var classname = "slider-text" + count.toString(10);
      var item = document.getElementsByClassName(classname)[0];
      item.style.marginTop = "5rem";
      item.style.animationName = "slide-up";
      item.style.animationDelay = (count * 120 + 300).toString(10) + "ms";
}

I wasn’t able to finish introducing the UI and UX part of the project. I started this post more than 3 months ago and hasn’t found time to finish it up and I am going to take my mocks soon so I gotta start preparing for it. So the above is what I have so far and I am posting it since I probably will not have time to finish it this year. Will finish it once I got time after the mocks!

The post Project SIAT – UI / UX Coding appeared first on Nightingale.

]]>
https://nightingale.becomingcelia.com/2020/10/project-siat-ui-ux-coding.html/feed 0
CS Revision – Arrays https://nightingale.becomingcelia.com/2020/08/cs-revision-arrays.html https://nightingale.becomingcelia.com/2020/08/cs-revision-arrays.html#respond Sat, 29 Aug 2020 09:14:28 +0000 https://nightingale.becomingcelia.com/?p=923 Arrays are list of similar items, usually used in loops and repetitions. They contain similar items. The items in the list are the elements of the array. One-dimensional array are lists identified by the use of a single name and each item int eh list can be found by an index number showing the place […]

The post CS Revision – Arrays appeared first on Nightingale.

]]>
Arrays are list of similar items, usually used in loops and repetitions. They contain similar items. The items in the list are the elements of the array.

One-dimensional array are lists identified by the use of a single name and each item int eh list can be found by an index number showing the place in the list.

What to consider when using a one-dimensional array:

  • name of the array depending on its uses
  • size depending on the number of elements in the array
  • datatype depending on the type of element stored (names, ages, address, etc)

Example of arrays syntax in pseudocode:

DECLARE teachernames: ARRAY[0:2] of String
teachernames[0] <--- "Mr. Li"
teachernames[1] <--- "Ms. Lloyd"
teachernames[2] <--- "Mrs. Fox"
FOR i 0 TO 2
    OUTPUT teachernames[i]
NEXT

So generally, DECLARE arrayname: ARRAY[0:arraylength] of datatype.

The concept of parallel arrays is very convenient to use in problem solving. Parallel arrays have the same sizes and use the same variable for their indexes.

Going through an array item by item is called traversing the array.

The post CS Revision – Arrays appeared first on Nightingale.

]]>
https://nightingale.becomingcelia.com/2020/08/cs-revision-arrays.html/feed 0
An underrated HTML tag https://nightingale.becomingcelia.com/2020/05/an-underrated-html-tag.html https://nightingale.becomingcelia.com/2020/05/an-underrated-html-tag.html#comments Sat, 02 May 2020 10:31:21 +0000 https://nightingale.becomingcelia.com/?p=619 I learnt this from https://itnext.io/html-underrated-tags-119ef3e45b94. This is an amazing post. So basically, the tag is the <base></base> tag. It is used like this: So if the base is mentioned earlier, all the relative links will be according to this. This is very useful when you are using a tool like site sucker, which saves files from […]

The post An underrated HTML tag appeared first on Nightingale.

]]>
I learnt this from https://itnext.io/html-underrated-tags-119ef3e45b94. This is an amazing post.

So basically, the tag is the <base></base> tag. It is used like this:

<base href=”https://www.example.com/" target=”_blank”>
<a href="a-post.html">A post</a>

So if the base is mentioned earlier, all the relative links will be according to this. This is very useful when you are using a tool like site sucker, which saves files from a webpage. Some resources like images might not be correctly displayed if you saved a single file locally, but it will if you add the base tag, telling the html file that all the media files with relative links are from this webpage.

An example:

https://codepen.io/adrian-legaspi/pen/qBErzEq

The post An underrated HTML tag appeared first on Nightingale.

]]>
https://nightingale.becomingcelia.com/2020/05/an-underrated-html-tag.html/feed 1
Revision for Computer Science test: Storage https://nightingale.becomingcelia.com/2020/02/revision-for-computer-science-test-storage.html https://nightingale.becomingcelia.com/2020/02/revision-for-computer-science-test-storage.html#respond Sat, 08 Feb 2020 08:22:32 +0000 https://nightingale.becomingcelia.com/?p=465 Memory and Storage Primary Memory Primary memory, also known as main memory, is the only type of memory that could be directly accessed by the microprocessor. It is transistor-based, therefore is faster to do reading and writing. There are two types of primary memory: ROM and RAM. ROM (Read Only Memory) ROM or Read Only […]

The post Revision for Computer Science test: Storage appeared first on Nightingale.

]]>
Memory and Storage

Primary Memory

Primary memory, also known as main memory, is the only type of memory that could be directly accessed by the microprocessor. It is transistor-based, therefore is faster to do reading and writing. There are two types of primary memory: ROM and RAM.

ROM (Read Only Memory)

ROM or Read Only Memory, is used for system startups. For example, one data it saves is BIOS, Basic Input / Output System. The contents of the ROM chip can only be read and cannot be modified.

RAM (Random Access Memory)

RAM or Random Access Memory, stores the memory of running applications. It can also be used to store data and files. It can write into and read from and the contents of the memory could be changed. The larger the RAM, the faster the computer runs. When RAM gets nearly full, the computer needs to save some of the files at the hard disk drive. When the file is needed, the computer needs to swap from RAM memory to the hard disk drive, then swap back. Swapping needs a lot of time and the computer needs to do a lot of work. Therefore, the computer will be slower and the performance of it will be affected. Its only drawback is that it is temporary and volatile.

When there is more RAM, the computer will run faster.

Textbook
ROMRAM
read-onlyread and write
instructions for startuptemporary files and data used by running applications
data it stored cannot be modifieddata can be modified
SmallerBigger
CheaperMore expensive

Secondary Storage

Secondary storage is not directly accessible to the computer system. Different from primary memory, secondary storage is auxiliary and is usually used for permanent data storage (as implied in its name, it is storage instead of memory). There are two types of secondary storage: HDD – Hard-Disk Drive and SSD – Solid-state Drive.

HDD (Hard-disk drive)

Hard-disk drive is the most common way to store data on a computer. Data is stored in a digital format on the magnetic surfaces of a disk, also called platters. These platters can spin at a high speed of 7000 times a second. There are also a number of read-write heads that can move from the edge of a disk to the center of the disk for 50 times a second.

sectors and tracks

Data are stored on the surfaces of sectors and tracks. Each sector in a given track stores a given number of bytes.

Hard-disk drives are slow in data access when compared with RAM in primary memory. Many applications need to constantly access data and files so there will be a large amount of head movement, causing latency.

applications not responding is a result of latency

SSD (Solid-state Drive)

SSD solves the problems that exist in Hard-disk drives. It is at least 15 times faster than a hard-disk drive. It doesn’t rely on magnetism and has no moving parts within it. They store data by controlling the movement of electrons on the NAND chips (that sounds amazing but I don’t really know the details of it).

HDDSSD
– has moving parts– doesn’t have moving parts, thus more reliable
– very common for computers but heavier– lighter and is more suitable for laptops
– needs time to start the platters and head accelerating– does not need to get up to speed before working properly
– gets hot when running because of the moving parts in it– run much cooler so again more suitable for laptops
– thicker because of the moving parts– thinner since no moving parts
– slower in accessing, reading and writing data– faster in accessing data and no latency
– Unlimited reads and writes– limited reads and writes and doesn’t last long
– Large storage capacity– Smaller storage capacity

Offline Storage

Offline storage is disconnected from the computer and has to be plugged into the computer to be used. Offline storage is portable, contains data that needs to be shared.

Examples:

CD and DVD disks

CDs and DVDs use optical storage. They have a thin layer of alloy or light-sensitive organic dye to store data. Their tracks, unlike platters in HDD, are single and spiral from the center of the disk to the edge. Data are stored in the pits and bumps on the track, and a read laser is used to read the data. CDs and DVDs can be designed to be R, read only, or RW, which means that it is able to read and write into it for multiple times.

spiral shaped disk

The difference between DVDs and CDs is that DVDs are dual layer and has plastic reflectors sandwiched between. DVDs can store more data because of this.

DVDs are usually 4GB. Songs are stored in DVDs because DVDs can be stacked and are easier to sell.

Other types of offline storage media

Magnetic storage system

Transistor based

A transistor is a semiconductor device used to amplify or switch electronic signals and electrical power.

Optical storage system

  • CD
  • DVD

Binary Systems and Hexadecimal

Binary Systems

Binary is the only language machines understand without a compiler. It is based on number 2. When converting from binary to denary, times each place of the binary number by its corresponding value, from right to left, 1, 2, 4, 8, 16. When converting from denary into binary, see the values 1, 2, 4, 8, 16, and choose the ones that add up into the denary number by writing “1” under them. If you are not choosing a number, write “0” under them. An easier way of doing so is to simply divide the number by 2 and take all the remainders from top to bottom and arrange them from right to left.

Hexadecimal

Computers do not understand hexadecimals, but it is easier for humans to understand them. These numbers are base 16. To convert from denary to hexadecimals, divide the denary number by 16 and take the remainder from top to bottom, arrange them from right to left to form the hexadecimal number. If the remainder is larger than 10, write them in letter form, for example, A, B, C.

Uses of hexadecimal

Hexadecimal are very common. They are used to express colors, known as “hex colors”. The size of each hex color is 3 bytes and 6 nibbles. Each digit in a hexadecimal is 1 nibble.

Hexadecimal is also used in MAC addresses. MAC address is unique for every device and will never change. With MAC address it is possible to find a device.

A MAC address (not mine)

The format of a MAC address is NN:NN:NN:DD:DD:DD, where N is the identity of the manufacturer and D is the serial number of the device.

Links

Difference between Primary Memory and Secondary Storage

Difference between hard-disk drives and floppy diskettes

That’s the end. Happy revision and test on Tuesday!

The post Revision for Computer Science test: Storage appeared first on Nightingale.

]]>
https://nightingale.becomingcelia.com/2020/02/revision-for-computer-science-test-storage.html/feed 0
Conversation Machine https://nightingale.becomingcelia.com/2019/11/conversation-machine.html https://nightingale.becomingcelia.com/2019/11/conversation-machine.html#respond Fri, 08 Nov 2019 05:36:00 +0000 The post Conversation Machine appeared first on Nightingale.

]]>
import random def has_questionmark(qus): wordlist = qus.split() last_word = wordlist[-1] split_last_word = list(last_word) if '?' in split_last_word: return True def has_special_words(qus): wordlist = qus.split() first_word = wordlist[0] first_word = first_word.lower() special_words = ['what', 'where', 'when', 'how', 'why', 'are','do','did'] if first_word in special_words: return True def is_a_yn_question(qus): wordlist = qus.split() first_word = wordlist[0] first_word = first_word.lower() special_words = ['do', 'did', 'are'] if first_word in special_words: return True def is_a_question(qus): if has_questionmark(qus) or has_special_words(qus): return True print('nSpeak to me!') while True: question = input('') if question == 'q': break if is_a_question(question): if is_a_yn_question(question): choice = random.randint(0,1) if choice: print('Yes.n') else: print('No...n') else: print('This is not a question.')

The post Conversation Machine appeared first on Nightingale.

]]>
https://nightingale.becomingcelia.com/2019/11/conversation-machine.html/feed 0
POTW – It all adds up https://nightingale.becomingcelia.com/2019/09/potw-it-all-adds-up.html https://nightingale.becomingcelia.com/2019/09/potw-it-all-adds-up.html#respond Wed, 25 Sep 2019 02:05:00 +0000 https://nightingale.becomingcelia.com/2019/09/25/potw-it-all-adds-up/ This code is to find out the 3-digit numbers that have their digits add up to 9. The problem was originated from the “Problem of the week” from the university of Waterloo. The original question is stated here: https://www.cemc.uwaterloo.ca/resources/potw/2019-20/English/POTWD-19-NA-02-P.pdf The digit positive integer is the sum of all of its digits. For example, the digit sum […]

The post POTW – It all adds up appeared first on Nightingale.

]]>

This code is to find out the 3-digit numbers that have their digits add up to 9. The problem was originated from the “Problem of the week” from the university of Waterloo. The original question is stated here: https://www.cemc.uwaterloo.ca/resources/potw/2019-20/English/POTWD-19-NA-02-P.pdf

The digit positive integer is the sum of all of its digits. For example, the digit sum of the integer 1234 is 10, since 1 + 2+ 3 + 4 = 10. Find all three-digit positive integers whose digit sum is exactly 9.

This is the answer that I got, it can also be found out through running the code by pressing the green button:

108
117
126
135
144
153
162

171
180
207
216
225
234
243
252
261
270
306
315
324
333
342
351
360
405
414
423
432
441
450
504
513
522
531
540
603
612
621
630
702
711
720
801
810
900
Show Less…

Well, but there is another problem that I do not know how to solve. The problem can be found here: https://www.cemc.uwaterloo.ca/resources/potw/2019-20/English/POTWE-19-AE-02-P.pdf. If you find out the answer, please leave a comment!

The post POTW – It all adds up appeared first on Nightingale.

]]>
https://nightingale.becomingcelia.com/2019/09/potw-it-all-adds-up.html/feed 0
Largest and Smallest Number Flowchart https://nightingale.becomingcelia.com/2019/08/largest-and-smallest-number-flowchart.html https://nightingale.becomingcelia.com/2019/08/largest-and-smallest-number-flowchart.html#respond Wed, 28 Aug 2019 08:06:00 +0000 https://nightingale.becomingcelia.com/2019/08/28/largest-and-smallest-number-flowchart/ Grade 9 Computer Science class has started. Although I have learned how to code in C and Python before, I have never drawn a flowchart. I had planned for my code, but not as precise as a flowchart. My first flowchart, a super easy one, to find the largest and smallest number from the 5 […]

The post Largest and Smallest Number Flowchart appeared first on Nightingale.

]]>

Grade 9 Computer Science class has started. Although I have learned how to code in C and Python before, I have never drawn a flowchart. I had planned for my code, but not as precise as a flowchart. My first flowchart, a super easy one, to find the largest and smallest number from the 5 numbers, can be found here.

The post Largest and Smallest Number Flowchart appeared first on Nightingale.

]]>
https://nightingale.becomingcelia.com/2019/08/largest-and-smallest-number-flowchart.html/feed 0
ID Tech Camp: Intro to Coding for Machine Learning https://nightingale.becomingcelia.com/2019/07/id-tech-camp-intro-to-coding-for-machine-learning.html https://nightingale.becomingcelia.com/2019/07/id-tech-camp-intro-to-coding-for-machine-learning.html#respond Sat, 06 Jul 2019 15:39:00 +0000 https://nightingale.becomingcelia.com/2019/07/06/id-tech-camp-intro-to-coding-for-machine-learning/ In the past week (July 1 to July 2), I participated in a coding camp organized by the ID Tech organization called “Intro to Coding for Machine Learning”. I found the camp so exciting. I have learned to code before, but never with other students or a formal teacher (Dad taught me C and Python […]

The post ID Tech Camp: Intro to Coding for Machine Learning appeared first on Nightingale.

]]>

In the past week (July 1 to July 2), I participated in a coding camp organized by the ID Tech organization called “Intro to Coding for Machine Learning”. I found the camp so exciting. I have learned to code before, but never with other students or a formal teacher (Dad taught me C and Python before). The first few days of the camp was about the basics of the basics, as some people in our class are beginners. Although I learned things that I have learned before in the first few days, I did many interesting projects. We made some small games such as Hangman and Tic Tac Toe, BattleBots that can compete with each other. We also did some bigger project like basic Machine Learning with a self-built Neuron Network and TensorFlow (though I did not really know what the difference is between these two). I will continue to learn Machine Learning in my next camp the week after next week. What I am going to show here is some interesting projects that I did.

Below is the Hangman Game in Python, which is my second favorite project:

—–

# Hangman Game
import random

secret_word = random.choice([“apple”, ‘banana’, ‘orange’, ‘strawberry’, ‘blueberry’, ‘watermelon’, ‘melon’, ‘mouse’, ‘delicious’, ‘python’])
trials = 15
win = False
# two lists
wordlist = list(secret_word)
blanks = []
i = len(secret_word)
while i > 0:
    blanks.append(‘-‘)
    i -= 1

# guessing starts
while trials > 0:
    if win:
        break
    else:
        user_guess = input(“Guess: “)
        trials -= 1
        times = 0 #which letter
        for i in wordlist:
            if user_guess == i:
                blanks[times] = wordlist[times]
                print(‘Yes! “‘ + user_guess + ‘” is in the word!’)

            times += 1

        if user_guess not in wordlist:
            print(‘Sorry, “‘ + user_guess + ‘” is not in the word! You have ‘ + str(trials) + ” trials left.”)

        for j in blanks:
            print(j, end=”)
        print(“n”)

        if ‘-‘ not in blanks:
            print(‘Congrats! You guessed the word! It is “‘ + secret_word + ‘”!’)
            win = 1
            
        
if trials == 0:
    print('Sorry, you already tried for 15 times. The word is "' + secret_word + '", please play the game again!')

—–

This is still considered as an easy one (actually it is extremely easy. Lol I spent 1 hour on this).

Another game, my favorite, is the Tic Tac Toe Game:

—–

class Board:
    
    def __init__(self):
        self.spots = []
        for i in range(9):
            self.spots.append(None)

    def checkwin(self):
        
        for i in range (0, 9, 3):
            if (self.spots[i]==self.spots[i+1] == self.spots[i+2]) and self.spots[i] != None:
                return True
        
        for i in range(3):
            if (self.spots[i] == self.spots[i+3] == self.spots[i+6]) and self.spots[i] != None:
                return True
            
        if (self.spots[0] == self.spots[4] == self.spots[8]) and self.spots[0] != None:
            return True
        
        if (self.spots[2] == self.spots[4] == self.spots[6]) and self.spots[2] != None:
            return True
        
        return False

    def printSpot(self, spotNum: int):
        if self.spots[spotNum] == None:
            return spotNum
        else:
            return self.spots[spotNum]

    def print_board(self):
        print(” “, self.printSpot(0), ” | “, self.printSpot(1), ” | “, self.printSpot(2))
        print(“—–|—–|—–“)
        print(” “, self.printSpot(3), ” | “, self.printSpot(4), ” | “, self.printSpot(5))
        print(“—–|—–|—–“)
        print(” “, self.printSpot(6), ” | “, self.printSpot(7), ” | “, self.printSpot(8))
    
        
    def placesign(self, playerplace):
        if current_player == player1:
            self.spots[int(playerplace)] = player1sign
        elif current_player == player2:
            self.spots[int(playerplace)] = player2sign

# Start            
my_board = Board()
player1 = input(“Player 1, please type your name: “)
while True:
    player1sign = input(player1 + “, please type your mark (O or X): “)
    if str(player1sign) == “O” or str(player1sign) == “X”:
        break
    else:
        print(“Sorry, that’s not an ‘O’ or ‘X’!”)
print(“Hello, ” + player1 + “!”)
player2 = input(“Player 2, please type your name: “)
if player1sign == “O”:
    player2sign = “X”
else:
    player2sign = “O”
print(“Hello, ” + player2 + “!”)
current_player = player1

trials = 0
win = False
chosed = []
print(“This is the board:”)
my_board.print_board()

# Loop Starts
while trials < 9:
    if current_player == player1:
        while True:
            playerplace = input(player1 + “, please make your move (1 – 9): “)
            if playerplace in chosed:
                print(“Sorry, the place was already taken!”)
            elif playerplace not in chosed:
                chosed.append(playerplace)
                break
        my_board.placesign(playerplace)
        my_board.print_board()
    else:
        while True:
            playerplace = input(player2 + “, please make your move (1 – 9): “)
            if playerplace in chosed:
                print(“Sorry, the place was already taken!”)
            elif playerplace not in chosed:
                chosed.append(playerplace)
                break
        my_board.placesign(playerplace)
        my_board.print_board()
    
    if my_board.checkwin() == True:
        win = True
        break
    print(current_player)
    if current_player == player1:
        current_player = player2
    else:
        current_player = player1
    
    trials += 1

if win == True:
    print(“Congratulations! ” + current_player.title() + ” wins!”)
elif win == False:
    print(“This is a draw! Play the game again!”)

This program is much longer and has included the use of class, loops, and methods. I actually felt so proud of myself as a beginner after seeing this works, with no errors when I play it with my mum. (Mum was like: “Is this what you learned for the whole week? There’s nothing special about it!”, thinking: “There are much better ones on the web!”) Dad (Programming as his first job after his graduation) was kind of surprised for what I have done (and confused how I could make so many errors). Anyway, I like these games a lot and if you want to have a try, please try here:

Hangman:
Tic Tac Toe:
Despite these, we also have lots of happy memories at the id tech camp!



The post ID Tech Camp: Intro to Coding for Machine Learning appeared first on Nightingale.

]]>
https://nightingale.becomingcelia.com/2019/07/id-tech-camp-intro-to-coding-for-machine-learning.html/feed 0
.items in dictionary (Python) https://nightingale.becomingcelia.com/2019/05/items-in-dictionary-python.html https://nightingale.becomingcelia.com/2019/05/items-in-dictionary-python.html#respond Mon, 20 May 2019 16:08:00 +0000 https://nightingale.becomingcelia.com/2019/05/20/items-in-dictionary-python/ The items() method returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list. Details: https://www.w3schools.com/python/ref_dictionary_items.asp

The post .items in dictionary (Python) appeared first on Nightingale.

]]>
The items() method returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list.

Details: https://www.w3schools.com/python/ref_dictionary_items.asp

The post .items in dictionary (Python) appeared first on Nightingale.

]]>
https://nightingale.becomingcelia.com/2019/05/items-in-dictionary-python.html/feed 0
The Daffodil Numbers https://nightingale.becomingcelia.com/2019/02/the-daffodil-numbers.html https://nightingale.becomingcelia.com/2019/02/the-daffodil-numbers.html#respond Sun, 17 Feb 2019 06:12:00 +0000 https://nightingale.becomingcelia.com/2019/02/17/the-daffodil-numbers/ The post The Daffodil Numbers appeared first on Nightingale.

]]>
//Daffodil Numbers! #include <stdio.h> int main(){     int i, j, k = 0;     for( i = 1; i<= 9; i++){         for( j = 0; j <= 9; j++){             for( k = 0; k <= 9; k++)                 if( 100*i+10*j+k == i*i*i+j*j*j+k*k*k)                     printf("%dn", 100*i+10*j+k);         }     }     return 0; } //And up-side-down triangles! #include <stdio.h> int main(){     int n;     scanf( "%d", &n);      for( int i = 0; i < n ; i++ ){         int hstart = i;         int hstop = 2*n-1-i;         for( int j = 0; j < 2*n-1-i; j++){             if( j < hstart){                 printf( " ");             } else if( j < hstop) {                 printf( "#");             } else {                 printf( " ");             }         }         printf( "n");     }     return 0; }

The post The Daffodil Numbers appeared first on Nightingale.

]]>
https://nightingale.becomingcelia.com/2019/02/the-daffodil-numbers.html/feed 0