The Journey of #100DaysOfCode (@henna_dev)

#Day69 of #100DaysOfCode

Today Ireland greeted us with yet another sunny day :wink: which is pretty unusual of Ireland, where you get to experience 4 seasons in a day :stuck_out_tongue:
I and my husband enjoyed food and drinks in the sun :smiling_face_with_three_hearts: I am also pleased to say, I finally managed to cover the objective of saving the wounded boy in Horizon part 1 PS4 game :partying_face:

I realized I am not enjoying the front-end very much. It’s not very intuitive for me :-/ so I will continue with JavaScript for now. I may recap some Kotlin here and there because I need to understand concepts to improve upon my Android Development Skills … :purple_heart:

I continued on the Codecademy course and learned about JavaScript Runtime Environments… I documented on Medium:

Tomorrow I will study modules. Until then… :wave:

2 Likes

#Day70 of #100DaysOfCode

I have to say, I love looonng weekends, and I don’t want it to get over … :heart_eyes: Today was fun time with legos… I absolutely enjoyed creating an amazing wall frame… I only regret buying an expensive one from Copenhagen Airport rather than from Amazon where it was cheaper :roll_eyes:

I studied modules in Node and documented them. I am stuck on one problem where my exports give me an error, so I will try to fix that tomorrow.

Until tomorrow :wave:

3 Likes

#Day71 of #100DaysOfCode

Today the loooonnng weekend ended :frowning: so it was a little stressful day, thinking of all the work I have ahead of me :stuck_out_tongue: Today I spent time working on multiple things, Realm, MongoDB, and my Node.js message-mixer app to learn module exports and require functions.

On MongoDB front, I wanted to understand how to define JSON schema but I was not able to figure that out, so I had to enable development mode On for my realm app, add a new class to my application and then sync to Atlas and that will auto-generate the schema on cloud. I am working on Restaurant App using Atlas Sync .

POJO class:

open class Borough (
    @PrimaryKey
    var _id: ObjectId = ObjectId(),

    var borough: String? = null,

    var _partition: String = "borough"
): RealmObject() {
}

MongoDB Schema generated on Cloud

{
  "title": "Borough",
  "bsonType": "object",
  "required": [
    "_id",
    "_partition"
  ],
  "properties": {
    "_id": {
      "bsonType": "objectId"
    },
    "borough": {
      "bsonType": "string"
    },
    "_partition": {
      "bsonType": "string"
    }
  }
}

I also learned I cannot run distinct query from MongoDB Compass but I can execute it on mongo shell. Another thing I learned was the connection to shell does not happen with any other database than test . For this I think I will have to ask the expert :smiley:

MongoDB shell version v4.4.1
Enter password: 
connecting to: mongodb://**<truncated>**.mongodb.net:27017, **<truncated>**.mongodb.net:27017, **<truncated>**.mongodb.net:27017/database?authSource=admin&compressors=disabled&gssapiServiceName=**<truncated>**
{"t":{"$date":"2022-04-18T15:08:07.345Z"},"s":"I",  **<truncated>**,
"msg":"RSM host selection timeout",
"error":"FailedToSatisfyReadPreference: Could not find host matching read preference { mode: \"nearest\" } for set atlas-nudr3h-shard-0"}}


*** It looks like this is a MongoDB Atlas cluster. Please ensure that your IP whitelist allows connections from your network.

Error: connect failed to replica set **<truncated>**
connect@src/mongo/shell/mongo.js:374:17
@(connect):2:6
exception: connect failed
exiting with code 1

I found distinct boroughs and made a separate collection for them in the restaurant database

db.restaurants.distinct("borough")
[
	"Bronx",
	"Brooklyn",
	"Manhattan",
	"Missing",
	"Queens",
	"Staten Island"
]

db.Borough.insertMany([{borough:"Bronx"},{borough:"Brooklyn"},{borough:"Manhattan"}])

db.Borough.find({})
{ "_id" : ObjectId("625d9151be17483a1e2ac403"), "borough" : "Bronx" }
{ "_id" : ObjectId("625d9151be17483a1e2ac404"), "borough" : "Brooklyn" }
{ "_id" : ObjectId("625d9151be17483a1e2ac405"), "borough" : "Manhattan" }
{ "_id" : ObjectId("625d91b4be17483a1e2ac406"), "borough" : "Missing" }
{ "_id" : ObjectId("625d91b4be17483a1e2ac407"), "borough" : "Queens" }
{ "_id" : ObjectId("625d91b4be17483a1e2ac408"), "borough" : "Staten Island" }


On the node js front, I managed to find the error that I was facing with the module.exports. I had to type this dot function name to refer it than calling it without the keyword.

Also, the stack overflow answer helped me figure out, I am calling the function incorrectly.

I added the challenge code to Github as it was an interesting Encryption challenge :smiley:

Until tomorrow :wave:

3 Likes

#Day72 of #100DaysOfCode

Today was a little stressful day… :-/ Sometimes, it’s just hard to manage everything at once… but I am hopeful it will soon be okk.

I continued working on the restaurant app and found out that the schema I had created was incorrect. I defined borough as a partition key on the cloud and that will stay the same in all collections and documents. I cannot change it to be something else… so I made some destructive schema changes… :grimacing:

Now my new schema looks like the below:

open class Borough (
    @PrimaryKey
    var _id: ObjectId = ObjectId(),

    var borough: String? = "borough",

    var location: String = ""
): RealmObject() {
}

I had to remove _partition since my selected key was borough so I kind of kept the same value for it and kept location as a separate field.

I did some error handling today as well. I found out that turning the development mode off reset the sync settings as well.
If you select the partition key as one of the fields from the collection, and when you select permissions from the template, it will select the default partition key instead of the field you selected as the partition key.

Now, the next step I am figuring out is creating UI dynamically after retrieving values from the database or if I am not able to do that, I will create a spinner and add the values from db there.

That is all today. Until tmrw :wave:

3 Likes

#Day73 of #100DaysOfCode

Today I was a mixed bag of emotions which includes stress, tiredness, frustration, rage, fear, and … more :speak_no_evil:

It was a long day, but I managed to implement the code for dynamically generating the buttons for data I retrieved from Atlas and displayed on UI.

I am struggling with setting margins of my buttons and I don’t know how to do that :’( My Kotlin code for button code looks like:

        Realm.getInstanceAsync(config, object: Realm.Callback() {
            override fun onSuccess(realm: Realm) {

                val locationList: RealmResults<Borough> = realm.where<Borough>().findAll()
                locationList.forEach{borough ->
                    setUpUI(borough.location)
                }
            }
        })

    private fun setUpUI(location: String) {

        // create the layout params that will be used to define how your
        // button will be displayed
        val params: LinearLayout.LayoutParams = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
        )
        params.marginStart = 30
        params.marginEnd = 30
        val button = Button(this)
        button.text = location
        button.layoutParams = params

        button.setOnClickListener{
            openPartition(location)
        }
        linearLayout.addView(button)

    }

So this will display the borough received from the database. The UI screen looks as below:

Selecting one of the locations will display the restaurant names in that location. The next step is to add the Maps library to point the location on the map. Fill figure that out tomorrow.

I would appreciate some help on setting margins and background color for buttons… :smiley: Thanks in advance =)

3 Likes

I don’t know anything about Kotlin but it seems like you would just increase the value of both
params.marginStart = 30
&
params.marginEnd = 30
to something higher and the buttons will smash in. Maybe just shooting in the dark but I bet it works.

1 Like

#Day74 of #100DaysOfCode

Today was a low-energy day… Sometimes I think I add more work to my plate than my capacity to do it… :-/ I wish I could time travel, I would have made different decisions… anyways that was my rant for today…

I could not do much on the Restaurant App, except for adding Maps Activity and generating an API key from Google Console for it…

It appears data binding has become the default in google activity generation as MapActivity is using it, but I am not using data binding in my app, I would need to fix this…

Map Activity


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMapsBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

        // Add a marker in Sydney and move the camera
        val sydney = LatLng(-34.0, 151.0)
        mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }

In the next step, I would need to add a click listener to my Recycler View and then on click of the location, display it on the Map…

Until tomorrow

3 Likes

#Day75 of #100DaysOfCode

Today was a much better day than yesterday… I relieved myself a bit from the stress I had and the day went well… I managed to plot maps and implement a click listener in the recycler view but somehow my map is not displaying the location directly :frowning:

I am happy, I am close to finishing it :blush:

I updated my Recycler Adapter Click listener as below, this should update the activity file too…


    override fun onBindViewHolder(holder: RestaurantHolder, position: Int) {
        val restaurant = getItem(position)
        holder.bindValues(restaurant!!)

        holder.itemView.setOnClickListener {
            val intent = Intent(parent.context, MapsActivity::class.java)
            intent.putExtra("LATITUDE", restaurant.address!!.coord[0])
            intent.putExtra("LONGITUDE", restaurant.address!!.coord[1])
            parent.context.startActivity(intent)
        }
    }

The MAP Activity retrieves the value like this which is also correct

         latitude = intent.getDoubleExtra("LATITUDE", 0.0)
         longitude = intent.getDoubleExtra("LONGITUDE", 0.0)

Both latitude and longitude are global variables and are displaying the location but something is not working. It appears the correct values are not getting passed in the content extras and that’s troubling it… I will fix this tomorrow.

 override fun onMapReady(googleMap: GoogleMap) {

        // Add a marker in Sydney and move the camera
        val position = LatLng(latitude, longitude)
        mMap.addMarker(MarkerOptions().position(position).title("Marker in Sydney"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(position))
    }

Until tomorrow

2 Likes

#Day76 of #100DaysOfCode

Today was a good day, I made some progress in the restaurants. I have to thank these wonderful two people :hugs: to help me with the concepts I was stuck at, @Josman_Perez_Exposit who is a gem of a person I worked with in my previous team, helped me understand Cloud functions and triggers and how implementation will work from within the app :orange_heart: and another one is my friend Oya from Android Community :purple_heart: who helped me figure out the error with margins.

I made some good progress in Restaurant App. The error in the setting up margins was the linear layout type I used in the XML code. I was using LinearLayoutCompat on which the code was not working. Changing it to LinearLayout and using the same code fixed it.

    private fun setUpUI(location: String) {

        // create the layout params that will be used to define how your
        // button will be displayed
        val params: ViewGroup.MarginLayoutParams= ViewGroup.MarginLayoutParams(
            ViewGroup.MarginLayoutParams.MATCH_PARENT, ViewGroup.MarginLayoutParams.WRAP_CONTENT
        )

        params.setMargins(30,15,30,15) //left, top, right, bottom

        val button = Button(this)
        button.text = location
        button.layoutParams = params
        button.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent))

        linearLayout.addView(button)
        button.setOnClickListener{
            openPartition(location)
        }

    }

XML code (New): 
    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center"/>

XML Code (Old):
    <androidx.appcompat.widget.LinearLayoutCompat
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center"/>

The UI screen now looks like this:

I am not able to fix the Map screen yet, I am getting the correct values of both Longitude and Latitude but the marker is not getting displayed on the Map. It can be one of the below or some unfound error

  • gms dependency is not happening,
  • map key needs to be added to manifest file
  • data-binding needs to be added to whole app or removed from Maps Activity

I also implemented Auth Trigger in the app, This fires a function when a new user sign-ups in the app. This will store the data of the user in the new User collection I added.

The POJO class code for User Collection looks like:

open class User (
    @PrimaryKey var _id: String = "",

    var borough: String? = "",

    var email: String = "",

    var friends: RealmList<Friend> = RealmList(),

    var sharedRestaurantId: RealmList<ObjectId> = RealmList(),

    var name: String = ""
): RealmObject() {}

My Function code looks like the below:

exports = async function addNewUser({user}) {
  console.log(JSON.stringify(user));
  const dbName = context.values.get('db_name');
  const users = context.services.get('mongodb-atlas').db(dbName).collection("User");
  const email = user.data.email == undefined ? "" : user.data.email;
  const name = user.data.name == undefined ? "" : user.data.name;
  console.log(`id: ${user.id} name: ${name}`);
  
  try{
    
    users.insertOne({
    _id: user.id,
    borough: `user=${user.id}`,
    email: email,
    name: name,

  });
  } catch(error){
    console.error(error.toString());
    return
  }
};

The borough here is the partition key that is defined for sync. Although it does not make any sense, but at this time, I want to have a functional app before I make any such changes.

My function gives the following error and I don’t know why and how to fix it, I will look at this tomorrow

Error:

db: string required

Logs:
[
  "{\"id\":\"62646c31c76b8cc188123638\",\"type\":\"normal\",\"custom_data\"
:{},\"data\":{\"email\":\"Mary\"},\"identities\"
[{\"id\":\"62646c3175608ee40e94d276\",\"provider_type\":\"local-userpass\"}]}"
]

Until Tomorrow :wave:

1 Like

#Day77 of #100DaysOfCode

Today was a day of being at peace… I have been restless in the past week and I think I needed time to switch off all the stress and drama of work life… :person_in_lotus_position:

I started with my yoga practices again and spend some time in nature feeding the birds, it felt good and I am at peace in my head.

I could not do a lot on the restaurant app as for the next steps I need to read and understand concepts so that I can implement them. I read about user objects and how meta-data and custom user data are retrieved from auth providers when a user authenticates.

The code I was using in functions, was giving a db_name string error because I never defined that value. Check User Objects and Values for more information.

Once I defined the value, I am now getting a different error of the form:

{"message":"'db_name' is not defined","name":"ReferenceError"}

I believe the cloud engineer will be able to suggest a remedy to this. I am still not able to fix Maps Activity. I asked one of my fellow Android Community friends to take a look at my code… :crossed_fingers:

Once the Map activity is fixed, I would add a share option and push notification and with that, I will be close to finishing the app…

I am nervous and scared :-/ I am short of time for finishing this. But if I look back, I am in such situations quite a lot :wink: and mostly I have come out as a winner… Let’s see this time… :grimacing:

Until tomorrow :wave:

1 Like

#Day78 of #100DaysOfCode

Today was a long day, learning to embrace new challenges, it’s not easy but possible and maybe achievable… :innocent:

I managed to fix two errors in the app. I would like to thank @ChristanMelchior for his help in debugging the email-password auth issue where I had incorrect code to retrieve the password and my password would give invalid on login. :orange_heart:

The major evening got spent finding the error in Maps Activity, why was it not plotting the locations, only if I had paid attention to geography :-/ I added breakpoints and log statements and yet I could not capture that I was using Longitude and Latitude in reverse :woman_facepalming:

I fell back to the Udacity Kotlin course on Maps SDK and I noticed that Longitude has -ve value… Changing the values fixed the issue and I was able to plot the map.

As a final step, I need to share the location with another user, and another user to receive notification of sharing.

The Maps Screen now shows the restaurant with a street and name in the snippet.

There is a way to customize the snippet, but at this moment, I want to finish the MVP. I am excited about learning more concepts now… although I am absolutely exhausted… but you seldom achieve success within comfort zone :wink:

Until tomorrow… :wave:

1 Like

#Day79 of #100DaysOfCode

Today was a slow day, reflecting back on the past and pondering over what ifs… :thinking: Sometimes Life feels like a Detroit game, where one makes a decision and it changes the path forward… :grimacing: Lol the biggest drawback, is the decision cannot be remade…

I miss working together in a team that once I used to do, :frowning: I fall back to my Android Community that I became a part of during my Scholarship back in 2018 and I told them about my 100 Days and Akin and Oya who are amazing friends of mine said this and it made my day… I am a bit emo today :wink:

The day changed for the better by the end… :smiley:

On my restaurant application front, I made only small progress, I added a click listener to the marker of the app, on clicking it would ask the username and will call a function on the cloud and add that friend to the list and send the location to him … I added a menu icon to go to Friends Screen to see friends added and restaurants shared… It is a little tricky implementation here, so I will spend some time thinking about this.

On other hand, I watched a course that my colleague from the previous team has deployed on the Amazon EC2 instance and which will be part of our new LMS system, Although I felt it was based on old UI and may not explain a lot of things but I got a hang of Triggers and Functions.

I learned

  • Triggers can be Database, Authentication, and Scheduled
  • Functions are executed on the console as system user or application authentication
  • Functions executed as system user by-passes all rules
  • Functions can also be called from within the client application via the SDK code.

The last section is what I will be implementing in my restaurant app, and I need to learn how.

Until tomorrow… :wave:

2 Likes

#Day80 of #100DaysOfCode

Today was our very first Dublin MUG Event… It went well and was a good experience… :tada:

Sneak Peak

I learned a few things from our talks, query optimization was one of the good topics. Learned about blocking sorts and removing redundant indexes to avoid blocking sorts. Learned about data modeling in MongoDB, linked vs embed relationships. Although I am not very experienced in MongoDB hopefully I will learn about it soon.

I was in the office today, so I met a few old colleagues and I got told I left a mark when I left my old team… That made my day, it felt sooo good… :orange_heart: They hired 5 more people once I left… :wink: I remember getting a remark “One Woman Army” that felt awesome… :purple_heart: I guess I miss the compliments I used to get but I am happy my VP notices my work and appreciates me publicly :wink:

I also got back to Codecademy, I wanted to start with a backend project, so I learned about CLI and NPM package, but I could not do a lot today.

I will update my presentation more tomorrow as I am now relieved that this event is over … :grimacing:

Until tomorrow… :wave:

3 Likes

#Day81 of #100DaysOfCode

Today was another slow day… My days are very up and down like a high and low tide :grimacing: and it’s not pretty… I am glad to have an amazing partner who helps stabilize my mental state in this challenging period I am finding myself in :stuck_out_tongue:

Today I continued on the Codecademy path getting to know some backend programming. The topic for today was Unit testing.

What is Unit Testing?

Unit testing means testing the behavior of code in small, independent units. Units are typically designed to be the smallest meaningful chunk of independently testable code. This is in comparison to integration testing, in which a set of modules are tested as a group.

Mocha and Chai, Test Suites and Test Cases

Mocha and Chai are two JavaScript frameworks commonly used together for unit testing.

Mocha is a testing framework that provides functions that are executed in a specific order, and that logs their results to the terminal window.

The tests written in Mocha use the keywords describe and it . These keywords, provided by Mocha, provide structure to the tests by batching them into test suites and test cases.

A test suite is a collection of tests all relating to a single functionality or behavior. A test case or a unit test is a single description of the desired behavior of the code that either passes or fails. Test suites are batched underneath the describe keyword, and test cases are batched under the it keyword.

Additionally, Mocha provides tools for cleaning the state of the software being tested in order to ensure that test cases are being run independently of each other.

Sometimes other tools are used to stub or mock the desired behaviors of other units that a given unit of code might interact with. The independence of test cases is a key principle of unit testing, as it allows the cause of errors to be pinpointed more specifically if a test case fails, thereby speeding up the debugging process.

Assertions

The base component of test cases are assertions . Assertions are tied to particular values (whereas test cases are descriptions of behavior) and they will fail if the expected value does not match the actual value.

Every assertion in a test case must be met in order for the test case to pass.

Chai is an assertion library that is often used alongside Mocha. It provides functions and methods that helps compare the output of a certain test with its expected value. Chai provides clean syntax that almost reads like English!

Example of a Chai assertion: expect(exampleArray).to.have.lengthOf(3);

This code will check whether that the variable exampleArray has a length of three or not.

Failing and Passing Tests

Robust tests are accurate for both failing and passing conditions! When writing tests, make sure that the test fails if the feature that it is testing was not implemented properly, as well as making sure that the test passes if it is. Tests that will erroneously pass can be enormously misleading and might lead to broken code getting merged and deployed.

That is all today, will continue on some examples tomorrow.

2 Likes

#Day82 of #100DaysOfCode

Today, I went to the office in need of human connections :wink: I don’t survive working in silos as my situation is currently and office visit absolutely did me good… I may make frequent visits :smiley:

Today I went back to my unfinished Intermediate JavaScript section and wrote a blog on implementing modules in Browser

I am absolutely pleased finishing 82nd Day today, 18 more to go… but there are still soo many things I want to learn… :grimacing:

Until tomorrow :performing_arts:

1 Like

#Day83 of #100DaysOfCode

Today was a good day :orange_heart: I was going through a bad week and today I said to myself " Enough, Get Over It :wink: " Lol… I partly give credits to my husband :stuck_out_tongue: I realized I am a sensitive person, I get too attached to stuff, which leads to disappointments and drains my energy…

I visited Pet Store today in need of some dopamine and I got my dose :purple_heart: We decided to buy 2 dwarf bunnies, they are still young and will call us in a week… Can’t wait to have them home :orange_heart:

Husband seeing the Fishes: They are having a scrum meeting… :joy:

I continued on the modules in the ES6 section:

Renaming Imports to avoid Naming Collisions

what happens if two modules that are imported have the same function name like greet below

/* inside greeterEspanol.js */
const greet = () => {
  console.log('hola');
}
export { greet };
 
/* inside greeterFrancais.js */
const greet = () => {
  console.log('bonjour');
}
export { greet };

The following syntax will give an error that the identifier greet has already been defined.

import { greet } from 'greeterEspanol.js';
import { greet } from 'greeterFrancais.js';

There is a syntax for renaming imported resources by adding in the keyword as like:

import { exportedResource as newlyNamedResource } from '/path/to/module'

so two same greet functions can be renamed like below:

/* main.js */
import { greet as greetEspanol } from 'greeterEspanol.js';
import { greet as greetFrancais } from 'greeterFrancais.js';
 
greetEspanol(); // Prints: hola
greetFrancais(); // Prints: bonjour

Default Exports and Imports

Every module also has the option to export a single value to represent the entire module called the default export . Often, though not always, the default export value is an object containing the entire set of functions and/or data values of a module.

The syntax for exporting a default object looks like this:

const resources = { 
  valueA, 
  valueB 
}
export { resources as default };

With this syntax, the object containing the module’s resources is first declared and then exported.
It appears resources object is being exported as a named export, but the clause as default renames the exported object to default , a reserved identifier that can only be given to a single exported value.

The shorthand syntax for the same is:

const resources = {
  valueA,
  valueB
}
export default resources;

Importing default values

The syntax for importing default exports looks like this:

import importedResources from 'module.js';

It should be noted that if the default export is an object, the values inside cannot be extracted until after the object is imported, like so:

// This will work...
import resources from 'module.js'const { valueA, valueB } = resources; 

// This will not work...
import { valueA, valueB } from 'module.js'

Tomorrow will continue with a challenge …

Have a good Weekend… :tada:

3 Likes

#Day84 of #100DaysOfCode

It was a rainy day, but the day went by fine. I was observant of nature around… I watched a kid emptying his packet of crisps to feed the birds, I also felt sad for Sunday market sellers who had few customers because of rain. We had a coffee and churros :yum: :yum:

My husband went for Gaurav Kapoor standing comedy show while I spent my evening by myself, I had a good lunch at Nandos and spent time on my presentation. I finished a practice challenge on modules, during which I realized, I need to do some codewars to keep my Javascript in check.

Both of the projects are on Github. Tomorrow I will continue work on my presentation.

WorkAround Explorer Challenge to practice modules

First Problem on Codewars

Until tomorrow :performing_arts:

2 Likes

#Day85 of #100DaysOfCode

Today was a good day, I spent some time walking along the coast and worked on my Devoxx presentation. I am happy with the current workflow.

Today I spent time on some more codewars and read about mocha and chai test cases and documented that :smiley: A day spent well :tada:

Codewars Problems on Github (String repeat and Average)

Until tomorrow… :performing_arts:

2 Likes

#Day86 of #100DaysOfCode

The last two weeks have been difficult but I am in a much better place now. I made peace with things beyond my control. :dove: My tarot card prediction also highlighted the same :wink:

I am freaking out a bit as I am only 9 days away from my Devoxx talk and I still have a long way to go to finish and practice but I am hopeful I will be able to do it… because I don’t have any alternative :stuck_out_tongue:

Today I spent most of the time understanding Realm backend, the task tracker tutorial uses a lot of functions, triggers, and even partition strategies… I am appreciative of @Nathan_Contino from the docs team, for being patient with me and answering my never-ending questions… :purple_heart:

Some of the functions I understood

CreateNewUserDocument

This function is called when a new user registers on the application

exports = async function createNewUserDocument({user}) {
  const cluster = context.services.get("mongodb-atlas");
  const users = cluster.db("tracker").collection("User");
  return users.insertOne({
    _id: user.id,
    _partition: `user=${user.id}`,
    name: user.data.email,
    canReadPartitions: [`user=${user.id}`],
    canWritePartitions: [`project=${user.id}`],
    memberOf: [
      {"name": "My Project", "partition": `project=${user.id}`}
    ],
  });
};

This is a hybrid partition strategy approach, user, and channel. Learn more on partition strategies.

The most interesting part was Sync permissions. It checks for read and write partitions by calling functions:

canReadPartition

exports = async function(partitionValue) {
  const cluster = context.services.get("mongodb-atlas");
  const userCollection = cluster.db("tracker").collection("User");
  try {
    const user = await userCollection.findOne({ _id: context.user.id });
    // If the user's canReadPartitions array contains the partition, they may read the partition
    return user.canReadPartitions && user.canReadPartitions.includes(partitionValue);
  } catch (error) {
    console.error(`Couldn't find user ${context.user.id}: ${error}`);
    return false
  }
}

canWritePartition

exports = async function(partitionValue) {
  const cluster = context.services.get("mongodb-atlas");
  const userCollection = cluster.db("tracker").collection("User");
  try {
    const user = await userCollection.findOne({ _id: context.user.id });
    // If the user's canWritePartitions array contains the partition, they may write to it
    return user.canWritePartitions && user.canWritePartitions.includes(partitionValue);
  } catch (error) {
    console.error(`Couldn't find user ${context.user.id}: ${error}`);
    return false
  }
};

I started a new topic in JavaScript: Asynchronous Operations

An asynchronous operation is one that allows the computer to “move on” to other tasks while waiting for the asynchronous operation to complete. Asynchronous programming means that time-consuming operations don’t have to bring everything else in our programs to a halt.

Operations like making a network request or querying a database can be time-consuming, but JavaScript allows us to execute other tasks while awaiting their completion.

What is a Promise?

Promises are objects that represent the eventual outcome of an asynchronous operation. A Promise object can be in one of three states:

  • Pending : The initial state— the operation has not completed yet.
  • Fulfilled : The operation has completed successfully and the promise now has a resolved value . For example, a request’s promise might resolve with a JSON object as its value.
  • Rejected : The operation has failed and the promise has a reason for the failure. This reason is usually an Error of some kind.

All promises eventually settle, enabling to write the logic for what to do if the promise fulfills or if it rejects.

That is all for today. Tomorrow will spend time on the presentation and Restaurant App.

Cheers, :performing_arts:

1 Like

#Day87 of #100DaysOfCode

Adulthood is hard, adjusting to new situations is hard, and bonding with someone is sometimes hard… Lol… The only things I can think of now are the hard things… I wish life was easier :stuck_out_tongue: but then some would say, where’s the fun in that… :wink:

Today was okayish, my morning went well… I had a one-day 5:00 am club wake-up… :sunny: I was able to add more details to my presentation and I also answered a few realm queries on our forums.

I tried to understand the difference between User Objects, Custom-user-data and User meta-data. I have to say it messed up my brain. :face_with_peeking_eye:

I found out custom-user data is only a convenience thing, it pre-fetches the custom user-data object so it’s accessible from the user object in the functions, w/o having to query a realm or MongoDB Atlas. Custom user data is only refreshed when the user’s login token gets refreshed, so it can be up to 20 minutes old at any time. So, it’s better to just query MongoDB directly in the functions

I made some progress on Restaurant App, instead of using a click-listener on the marker, I will have a menu option to click and start Friends Activity. Here I will have a function to add the friend and then share the location with him.

The next part left is how will the friend receive this data and how will this be displayed on Map. It has been a good experience working on this application, but I wish I had more time to streamline my thoughts…

I am a bit exhausted today so that’s all for today.

Until tomorrow, :performing_arts:

1 Like