175 Matching Annotations
  1. Jan 2021
    1. Exercise 3: Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments.
      def count(string, letter):
          char_count = 0
          for char in string:
              if char == letter:
                  char_count = char_count + 1
      
          print(char_count)
      
      
      
      if __name__ == "__main__":
          count("Bananaaaa", "a")
      
    2. Exercise 1: Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards.
      fruit = "Banana"
      index = len(fruit)
      
      while index > 0:
          print(fruit[index-1])
          index = index - 1
      
    1. Main Memory

      Is like the memories in our heads. Just like information stored in the memory is unretrievable when a machine is switched off, our memories are erased when we die.

  2. Nov 2020
    1. json('https://unpkg.com/world-atlas@1.1.4/world/110m.json')

      Curran: "The first thing we need for the map is the data that goes into it. The outlines of the countries. There's a great project called World Atlas and it's released as a package on npm so if you just do a Google search for "world atlas NPM" you'll find it. This is a project by Mike Bostock which converts the natural earth vector data to topoJson format which is an efficient format for representing data about geography. It's like a compressed version of geoJson but in any case this URL here is what you can copy to load in the low resolution shapes for the countries of the world.

      "It's a bunch of JSON data that has countries inside of it. From this data we can render polygons on the screen for each country which is our goal."

    2. svg = select('svg');

      The const declaration creates a read-only reference to a value. We're calling the D3 module select on the SVG element which was declared in the index.html file, and assigning it to a named constant called svg.

    3. geoPath

      This package converts the data path into an SVG path. A string that we can use on SVG paths.

      Preamble: "Let's look at a reference example of a map to see how everything else sort of fits together. My favorite way of finding examples is blockbuilder.org/ search. You could type a map into here and then just look at the ones with thumbnails and I know Mike Bostock has like the simplest most canonical example so I can search by mbostock as the username this looks like a good starting point. US states topoJson this is pretty close to what we want but we want to do the same thing for countries. One thing we need is geoPath from d3."

    4. geoNaturalEarth1

      The map projection style can be picked here. e.g. Geomercator, etc.

      Curran: "In the d3 geo package which is part of the default d3 bundle there is an embarrassment of riches in terms of different map projections that are available to you."

    5. topojson

      TopoJSON is an extension of GeoJSON that encodes topology.

      Curran explains: "Because the data is formatted as TopoJSON and there are d3 utilities to render GeoJSON data structures, we need to convert TopoJSON to GeoJSON in memory using a library that’s called topojson. Also written by Mike Bostock. This is an npm package, that can be loaded from unpkg. Use the minified version."

    6. const projection = geoNaturalEarth1(); const pathGenerator = geoPath().projection(projection);

      Setting up instances of the projection and geoPath here. The projection is passed into pathGenerator on line 7.

    7. feature

      Topojson.feature is the function that we need to convert our topojson into geojson. In our code we can say import {feature} from topoJson and then we can invoke feature, passing in as the first argument the data and the second argument is going to be the countries.

    1. onChange

      1)

      Let’s recap what happens when you edit an input:

      React calls the function specified as onChange on the DOM input element.

      In our case, this is the handleChange method in the TemperatureInput component.

    2. ReactDOM

      8)

      React DOM updates the DOM with the boiling verdict and to match the desired input values. The input we just edited receives its current value, and the other input is updated to the temperature after conversion.

    3. TemperatureInput

      7)

      React calls the render methods of the individual TemperatureInput components with their new props specified by the Calculator. It learns what their UI should look like.

    4. onTemperatureChange

      3)

      When it previously rendered, the Calculator had specified that onTemperatureChange of the Celsius TemperatureInput is the Calculator’s handleCelsiusChange method, and onTemperatureChange of the Fahrenheit TemperatureInput is the Calculator’s handleFahrenheitChange method. So either of these two Calculator methods gets called depending on which input we edited.

    5. render

      6)

      React calls the Calculator component’s render method to learn what the UI should look like. The values of both inputs are recomputed based on the current temperature and the active scale. The temperature conversion is performed here.

    6. handleCelsiusChange(temperature) { this.setState({scale: 'c', temperature}); } handleFahrenheitChange(temperature) { this.setState({scale: 'f', temperature}); }

      4)

      Inside these methods, the Calculator component asks React to re-render itself by calling this.setState() with the new input value and the current scale of the input we just edited.

    7. Calculator

      Calculator: A component that renders an < input > that lets you enter the temperature, and keeps its value in this.state.temperature. Additionally, it renders the BoilingVerdict for the current input value.

    8. BoilingVerdict

      8)

      React calls the render method of the BoilingVerdict component, passing the temperature in Celsius as its props.

      It accepts the celsius temperature as a prop, and prints whether it is enough to boil the water:

    9. handleChange

      2)

      The handleChange method calls this.props.onTemperatureChange() with the new desired value. Its props, including onTemperatureChange, were provided by its parent component, the Calculator.

    1. event

      https://developer.mozilla.org/en-US/docs/Web/API/Event

      The Event interface represents an event which takes place in the DOM.

      An event can be triggered by the user action e.g. clicking the mouse button or tapping keyboard, or generated by APIs to represent the progress of an asynchronous task. It can also be triggered programmatically, such as by calling the HTMLElement.click() method of an element, or by defining the event, then sending it to a specified target using EventTarget.dispatchEvent().

      The target property of the Event interface is a reference to the object onto which the event was dispatched

      Value comes from the HTMLInputElement interface https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement 605

  3. Oct 2020
    1. process

      Node has a handful of built-in identifiers. One of those globals is console, which we use to log out values to the terminal (console.log()). There's another global with the name of global. This object is a namespace which is available throughout the entire Node process. Process is another such global. It gives you access to the running node process.

  4. Sep 2020
    1. .select("-age")

      Then call the select method on this → inside give a string wit '-age' → this excludes the age field from the result objects

      query.select()

      Specifies which document fields to include or exclude (also known as the query "projection"). A projection must be either inclusive or exclusive. In other words, you must either list the fields to include (which excludes all others), or list the fields to exclude (which implies all other fields are included). The _id field is the only exception because MongoDB includes it by default. https://mongoosejs.com/docs/api/query.html#query_Query-select

    2. .sort({ name: "asc" })

      Call the sort() method on this → inside give an object with a key of 'name' and a value for 'asc' → This sorts them by name in ascending order.

      query.sort

      Sets the sort order. If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1. If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with - which will be treated as descending.

    3. .exec((err, filteredData) => {

      Finally call the exec() method, inside this give a callback function that takes in an error and an array of the filtered results

      query.exec()

      Executes the query. Inside a Callback function is specified, taking in error and any returned data.

    4. if (err) { console.log(err); } else { done(null, filteredData);

      Inside this, log any errors if they exist, otherwise give the filtered results array to the done() function as the second argument for marking

    5. Person.find({ favoriteFoods: { $all: [foodToSearch] } })

      In the queryChain function, call the find() method on the Person model → as the sole argument, give an object with a key of favoriteFoods and a value of an object with a key of $all and a value of an array with just the foodToSearch variable inside

    6. if (err) { console.log(err); } done(null, response);

      log any errors if they exist, otherwise call the done() function, giving null as the first argument and the JSON status as the second argument

    7. if (err) { console.log(err); } else { done(null, delrec)

      log the error if it exists, otherwise call the done() function with null as the first argument and the deleted record as the second

    8. if (err) return console.log(err); done(null, updatedDoc);

      If the error exists, log it, Otherwise run the done function with null as the first argument and the updated record as the second argument

    9. findAndUpdate

      Mongoose has some methods findOneAndUpdate() and findByIdAndUpdate() that allow us to update records in one step. We pass in a query object to find our desired record, a second object with our desired properties, a third object with an option to return the new record, and finally a callback function.

      In the findAndUpdate function, call the findOneAndUpdate() method on the Person Model

    10. if (err) return console.log(err); done(null, updatedPerson);

      Log the error if it exists, otherwise, call the done() function, giving null as the first argument, and the updatedResult as the second

    11. Person.findById(personId, (err, person)

      Call the findById on the Person Model, giving the personId as the first argument and a callback function as the second, taking in an error and a result

    12. findEditThenSave

      To Update records, it's a 3 step process: Find and Retrieve the record, Edit and make changes, and Save the changes to the database. We can combine the concepts we learned in the previous challenges to do this.

    13. if (error) { console.log(error); } else { done(null, result);

      If there is an error, log it, otherwise, call the done() method, giving the arguments null (no error) and result

    14. if (error) { console.log(error); } else { done(null, result); }

      If there is an error, log it, otherwise, call the done() method, giving the arguments null (no error) and result

    15. findOne

      model.findOne()

      Behaves like .find(), but it returns only one document (not an array), even if there are multiple items. It is especially useful when searching by properties that you have declared as unique.

    16. err, createdPeople

      As the second argument, give a function that takes in an error, and the returned data after the document has been written to the database → in this case an array of 'createdPeople'

    17. sriramSharma.save

      Call the save() method on this instance, giving it a function, which itself takes in an error and data

      document.save()

      Saves this document by inserting a new document into the database if document.isNew is true, or sends an updateOne operation only with the modifications to the database, it does not replace the whole document in the latter case.

    18. done(null, data)

      Otherwise, call the done() function, giving in 'null' as the first argument (since there is no error), and the data as the second argument, so that it can be tested.

    19. var Person = mongoose.model("Person", personSchema

      Create a Model from this schema with mongoose.model() and call it 'Person'

      We can now use Person() as a constructor to create Person Records (documents)

    20. personSchema = new Schema

      Inside the constructor, give an Object with key value pairs:

      1. For Name, give an object declaring a type of string, and required as true
      2. For Age, give a type of Number
      3. For Favourite Foods, give an array of Strings
    21. Schema

      You can think of a Mongoose schema as the configuration object for a Mongoose model. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection. You construct one, giving an object with key value pairs with properties and types the collection should have.

    1. Express

      Express is the most popular Node web framework, and is the underlying library for a number of other popular Node web frameworks. It provides mechanisms to:

      • Write handlers for requests with different HTTP verbs at different URL paths (routes).
      • Integrate with "view" rendering engines in order to generate responses by inserting data into templates.
      • Set common web application settings like the port to use for connecting, and the location of templates that are used for rendering the response.
      • Add additional request processing "middleware" at any point within the request handling pipeline.

      While Express itself is fairly minimalist, developers have created compatible middleware packages to address almost any web development problem. There are libraries to work with cookies, sessions, user logins, URL parameters, POST data, security headers, and many more. You can find a list of middleware packages maintained by the Express team at Express Middleware (along with a list of some popular 3rd party packages).

      https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction

    2. Node.js

      "As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications."

      "Node.js is similar in design to, and influenced by, systems like Ruby's Event Machine and Python's Twisted. Node.js takes the event model a bit further. It presents an event loop as a runtime construct instead of as a library.

      In other systems, there is always a blocking call to start the event-loop. Typically, behavior is defined through callbacks at the beginning of a script, and at the end a server is started through a blocking call like EventMachine::run(). In Node.js, there is no such start-the-event-loop call. Node.js simply enters the event loop after executing the input script. Node.js exits the event loop when there are no more callbacks to perform. This behavior is like browser JavaScript — the event loop is hidden from the user."

    1. urlencoded

      Returns middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.

      A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body). This object will contain key-value pairs, where the value can be a string or array (when extended is false), or any type (when extended is true).

      https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions

    2. req, res, next

      What is Middleware? It is those methods/functions/operations that are called BETWEEN processing the Request and sending the Response in your application method.

      FCC: Middleware functions are functions that take 3 arguments: the request object, the response object, and the next function in the application’s request-response cycle. These functions execute some code that can have side effects on the app, and usually add information to the request or response objects. They can also end the cycle by sending a response when some condition is met. If they don’t send the response when they are done, they start the execution of the next function in the stack. This triggers calling the 3rd argument, next().

      https://www.freecodecamp.org/learn/apis-and-microservices/basic-node-and-express/implement-a-root-level-request-logger-middleware

    3. req.query

      Docs: "This property is an object containing a property for each query string parameter in the route"

      https://expressjs.com/en/5x/api.html#req.query

      FCC: "Another common way to get input from the client is by encoding the data after the route path, using a query string. The query string is delimited by a question mark (?), and includes field=value couples. Each couple is separated by an ampersand (&). Express can parse the data from the query string, and populate the object req.query"

      https://www.freecodecamp.org/learn/apis-and-microservices/basic-node-and-express/get-query-parameter-input-from-the-client

    4. express.static

      express.static(root, [options])

      FCC: "An HTML server usually has one or more directories that are accessible by the user. You can place there the static assets needed by your application (stylesheets, scripts, images). In Express, you can put in place this functionality using the middleware express.static(path), where the path parameter is the absolute path of the folder containing the assets."

      https://expressjs.com/en/5x/api.html#express.static

    5. function

      app.METHOD(path, callback [, callback ...])

      Callback functions; can be: A middleware function. A series of middleware functions (separated by commas). An array of middleware functions. A combination of all of the above.

    6. res.send('Hello Express');

      res.send([body]) Sends the HTTP response.

      The body parameter can be a Buffer object, a String, an object, Boolean, or an Array. For example:

      res.send(Buffer.from('whoop')) res.send({ some: 'json' }) res.send('

      some html

      ') res.status(404).send('Sorry, we cannot find that!') res.status(500).send({ error: 'something blew up' })

      This method performs many useful tasks for simple non-streaming responses: For example, it automatically assigns the Content-Length HTTP response header field (unless previously defined) and provides automatic HEAD and HTTP cache freshness support.

      When the parameter is a Buffer object, the method sets the Content-Type response header field to “application/octet-stream”, unless previously defined as shown below:

      res.set('Content-Type', 'text/html') res.send(Buffer.from('

      some html

      ')) When the parameter is a String, the method sets the Content-Type to “text/html”:

      res.send('

      some html

      ') When the parameter is an Array or Object, Express responds with the JSON representation:

      https://expressjs.com/en/5x/api.html#res.send

    7. middleware

      Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

      Middleware functions can perform the following tasks:

      Execute any code. Make changes to the request and the response objects. End the request-response cycle. Call the next middleware function in the stack.

      If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

      The following figure shows the elements of a middleware function call:

    8. app.listen(process.env.PORT || 3000 )

      It tells your server to listen on a given port, putting it in running state. You can see it at the bottom of the file.

      It is inside comments because, for testing reasons, we need the app to be running in the background. All the code that you may want to add goes between these two fundamental parts.

  5. Aug 2020
    1. runtime

      "Runtime describes software/instructions that are executed while your program is running, especially those instructions that you did not write explicitly, but are necessary for the proper execution of your code.

      Low-level languages like C have very small (if any) runtime. More complex languages like Objective-C, which allows for dynamic message passing, have a much more extensive runtime.

      You are correct that runtime code is library code, but library code is a more general term, describing the code produced by any library. Runtime code is specifically the code required to implement the features of the language itself."

      via: https://stackoverflow.com/questions/3900549/what-is-runtime

    1. attr

      selection.attr(name[, value])

      "If a value is specified, sets the attribute with the specified name to the specified value on the selected elements and returns this selection.

      If the value is a constant, all elements are given the same attribute value; otherwise, if the value is a function, it is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]"

      https://devdocs.io/d3~5/d3-selection#selection_attr

  6. Jul 2020
    1. feature(data, data.objects.countries);

      "Topojson.feature is the function that we need to convert our topojson into geojson. In our code we can say import {feature} from topoJson and then we can invoke feature passing in as the first argument the data and the second argument is going to be the countries."

    1. data

      The data defined in the useState hook is also added to the dependency array of the useEffect hook. Every time data changes, the useEffect code block is triggered again.

    2. useEffect

      "The function passed to useEffect will run after the render is committed to the screen"

      We're making the SVG DOM element available to D3 by using the useEffect hook, so that it accesses the SVG after it is rendered.

    3. useEffect

      useEffect(didUpdate); Accepts a function that contains imperative, possibly effectful code.

      Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase). Doing so will lead to confusing bugs and inconsistencies in the UI.

      Instead, use useEffect. The function passed to useEffect will run after the render is committed to the screen. Think of effects as an escape hatch from React’s purely functional world into the imperative world.

      By default, effects run after every completed render, but you can choose to fire them only when certain values have changed.

      https://reactjs.org/docs/hooks-reference.html#useeffect

    1. dynamic

      A dynamic language (Lisp, Perl, Python, Ruby) is designed to optimize programmer efficiency, so you can implement functionality with less code. A static language (C, C++, etc) is designed to optimize hardware efficiency, so that the code you write executes as quickly as possible. https://stackoverflow.com/questions/20563433/difference-between-static-and-dynamic-programming-languages#:~:text=A%20dynamic%20language%20(Lisp%2C%20Perl,executes%20as%20quickly%20as%20possible.

    2. scripting language

      "A script or scripting language is a computer language with a series of commands within a file that is capable of being executed without being compiled. Good examples of server-side scripting languages include Perl, PHP, and Python. The best example of a client side scripting language is JavaScript."

      https://www.computerhope.com/jargon/s/script.htm#:~:text=A%20script%20or%20scripting%20language,side%20scripting%20language%20is%20JavaScript.

    3. first-class functions

      "A programming language is said to have First-class functions when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. " - developer.mozilla.org